# mkcmd_wait executes the command given by parameter "cmd" in procedure "startProc"
#
# is called from mkcommand.4/mkCmd_wait: 
# ... exec $xtermcall -e $wishcall $xtem_path/xtem_async $name &...
#
# as a concrete example:
#
#    set xtermcall xterm
#    set wishcall /usr/local/bin/wishx
#    set name  [tk appname]
#    set w_mkCmd [eval exec $xtermcall -e $wishcall $xtem_path/xtem_async $name &]
#    tkwait variable n_mkCmd
#
# Copyright (C) 2000  G. Lamprecht, W. Lotz, R. Weibezahn; IWD, Bremen University

proc TestPut {level text args} {
  global bell_level testPut
  set s "$text"; if {$args!=""} {set s "${s}<$args>"}
  if {($testPut>0)&&($level>=$bell_level)} \
	{puts stdout "*** [lindex [info level [expr [info level]-1]] 0]: \t<$s>";flush stdout}
}

proc killProc {}  {global pid; foreach p $pid {catch "exec kill -s SIGKILL $p"}}

proc startProc {cmd} {
  global  env pid xtem
  set FID [open "| $cmd"]
  set pid [pid $FID]
  TestPut 3 "TestPut <$cmd><$FID><$pid>"
  puts stdout "----- $cmd (PID=$pid) -----"
  fconfigure $FID -blocking 0
  fileevent  $FID readable [list xtem_async_read $FID]
  send  $xtem "set p_mkCmd $pid"
}

proc xtem_async_read {FID} {
   global pid xtem

   # if called program writes something to stdout.
   # also necessary for recognising eof condition.
   catch {read $FID} r
   if { "$r" != "" } {puts -nonewline stdout "$r"}
   if [eof $FID] {
      TestPut 3 "EOF gotten $FID"
      fconfigure $FID -blocking 1
      if [catch {close $FID} c] {puts stdout "$c"}
      puts stdout ""; flush stdout; send $xtem mkCmd_xit
      return

   }

}


set pid 0
wm withdraw .
set xtem [lindex $argv 0]
set bell_level [lindex $argv 1]
set testPut [lindex $argv 2]
send $xtem  set n_mkCmd \"[winfo name .]\"
