
# This code is shared by all the ICEM CFD GUI's.
#
# Copyright (c) 1993 - 1995 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

proc start_process_internal {ident win command prompt} {
    global process_fd enable_exec echo_flag process_prompt process_ident
    global process_command process_window use_xwindows tcl_version
    
    set sw $win.$ident
    if { [ winfo exists $sw ] } {
	error "you must exit and re-start this application to use this function"
    }

    busy 1
    
    set process_ident $ident
    mess "Initializing: [lrange $command 1 end]\n"
    set process_command($ident) $command
    
    eval application_main [lrange $command 1 end]
    
    set process_prompt($ident) [string trim $prompt]
    
    frame $sw -background black
    
    while 1 {
	set line [fetch_output]
	#really_puts "LINE \"$line\" PP \"$process_prompt($ident)\""
	if [string match $process_prompt($ident)* $line] {
	    mess $line black
	    break
	} else {
	    mess "$line\n" blue
	}
    }
    
    set enable_exec 1
    set echo_flag 1
    
    pack $sw -side top -fill both -expand 1 -padx 1 -pady 1
    set process_window($ident) $sw
    update idle
    
    set cmd "create_window [winfo width $sw] [winfo height $sw] [winfo id $sw]"
    switch $use_xwindows {
	1 { append cmd " -x" }
	2 { append cmd " -ogl" }
    }
    command $cmd
    
    setup_events $win
    
    busy 0
    return 1
}

proc command_internal {com echo} {
    global enable_exec process_fd last_line all_lines echo_flag
    global mess_allflag cmdlog_fp process_ident process_prompt
    global process_window command_hook output_queue
    
    if [string match quit* $com] { exit 0 }
    
    if !$enable_exec {
	mess "Please complete the current command first before performing\
		another one.\n" red
	return
    }
    
    if {$mess_allflag || ($echo == 1)} {
	mess "$com\n" green
    }
    
    set last_line ""
    set all_lines ""
    if $mess_allflag {
	set echo_flag 1
    } elseif {$echo > 0} {
	set echo_flag $echo
    } else {
	set echo_flag 0
    }
    
    if [info exists command_hook] { $command_hook $com }

    set inp ""
    set lines [split $com \n]
    if {[llength $lines] > 1} {
        set inp tmp_input
        set fp [open tmp_input w]
        for {set i 1} {$i < [llength $lines]} {incr i} {
            puts $fp [lindex $lines $i]
        }
        close $fp
    }
    
    set enable_exec 0
    catch {set res [command_execute \{$inp\} [lindex $lines 0] ] }


    if {$inp != ""} { cmd_rm $inp }

    set id $process_ident
    while 1 {
	set line [fetch_output]
	if [string match $process_prompt($id)* $line] {
	    if $echo_flag { mess $line black }
	    break
	} else {
	    set last_line $line
	    lappend all_lines $line
	    if $echo_flag { mess "$line\n" blue }
	}
    }
    
    set enable_exec 1
    set output_queue ""
}
