# run additional programs:  $utcmd $utoptions  with file  $ut_file
#			    in background if  $utback = "&"  
#			    with backup-file if  $utbackup = "1"  
#
# Copyright (C) 2004  G. Lamprecht, W. Lotz, R. Weibezahn; IWD, Bremen University

proc utility {f austext} {
	

  upvar 1 $austext a

  global  vv utcmd utoptions ut_file utback utbackup

  set a "";  set ab "";  set tmpfilnam .utility.tmp

  writescr0 $f "[datime] $vv(so6) $utcmd $utoptions $ut_file $utback"

  if {($utbackup==1)&&($ut_file!="")} {# create backup-file

    set dateiliste [lsort [glob -nocomplain -- *]]
    set i 1;  while {[string match "*$ut_file-$i.bak*" "$dateiliste"]!=0} {incr i}
    set backupfilename "$ut_file-$i.bak"
    set ab "\n$vv(so7) ---> $backupfilename"
    exec cp $ut_file $backupfilename
    set ab "${ab}\n$vv(so8) ---> $ut_file"

  }

  if {($utcmd=="changecode")&&($utoptions!="-analyse")} {# changecode with file modification

    exec mv $ut_file .tmp-$ut_file
    eval mkCmd_wait $f $utcmd [list "$utoptions .tmp-$ut_file $ut_file"]
    if {[file isfile $ut_file]&&([file size $ut_file]>0)} {FileDelete .tmp-$ut_file} \
    else {exec mv .tmp-$ut_file $ut_file}
    set ab "${ab}\n[datime] $vv(tea5)"

  } elseif {$utback=="&"} {# program call in background

    eval set res [catch "exec $utcmd $utoptions $ut_file $utback" message]
    set a "${a}\n$message"
    if {$res!=0} {set a "${a}\n$vv(re3)=$res"} else {set a "${a}\n$vv(sbck)"}

  } else {# program call in foreground

    if {[string first xterm $utcmd]>=0} {
      eval set res [catch "exec $utcmd $utoptions $ut_file" message]
      if {$res!=0} {set a "${a}\n$vv(re3)=$res\n$message\n"}
    } else {
      eval mkCmd_wait $f $utcmd [list "$utoptions $ut_file"]
    }

    set ab "${ab}\n[datime] $vv(tea5)"

  }

  set a  "${a}$ab\n"

}
