
# This code creates the ICEM CFD Manager.
#
# Copyright (c) 1993 - 1996 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

# The GUI interface to padamm.

set padamm_rebuild_file 0

# set the xterm program path

foreach xt {
    /usr/bin/X11/xterm /usr/openwin/bin/xterm
    /usr/openwin3.0/bin/xterm /usr/X11/bin/xterm
} {
    if [file exists $xt] {set xterm_prog $xt; break}
}

if {![info exists xterm_prog]} {
    puts stdout "Can't find an xterm!  Will try to do without..."
}

proc app_padamm {} {
    global place partname padamm_rebuild_file padamm_path
    global standalone padamm_terse remotehost padamm_back
    global inputfile gui_name is_win
    
    if {[info exists is_win] && $is_win} {
	errormsg "Padamm is not supported on Windows"
	return
    }
    
    # Yuck.
    case $padamm_terse in {true {set terse 1} false {set terse 0}}
    
    if {$place == ""} {
	errormsg "Can't run PADAMM -- the $gui_name(conf) or \
geometry is not set."
	return
    }
    
    # This is really annoying.  There should be a standard extension for
    # these index files.
    set files [glob -nocomplain "$place/transfer/*"]
    set inputs {}
    foreach file $files {
	set fname [file tail $file]
	case $fname in {
	    {core a.out Padammo* psave *.log fluent vsaero xyz} continue
	}
	set clines [catch {exec /bin/grep {PADAMM COMMAND FILE} $file}]
	if {!$clines} {lappend inputs $fname}
    }
    if $terse {
	set padamm_rebuild_file 1
	set input padamm_command
    } else {
	set padamm_rebuild_file 0
	toplevel .pick_input
	set input [select_one_lc .pick_input \
		   "-text {Pick a Padamm command file, or create a new one.}" \
		       $inputs [lindex $inputs 0] \
		       {{edit Edit {run_editor \
			   "$place/transfer/[.pick_input.entry get]"}}
			   {delete Delete {exec /bin/rm \
			       "$place/transfer/[.pick_input.entry get]"; \
				   set qq [lfirst [.pick_input.list curselection]]; \
				   if {$qq != ""} {.pick_input.list delete $qq}}}
			   {rebuild Rebuild {global padamm_rebuild_file select_done
			       set padamm_rebuild_file 1
			       set select_done okay}}}]
    }
    if {$input == "*cancel*"} return
    
    if {$input == ""} {
	errormsg "No input file given"
	return
    }
    set inputfile $input
    set ifile $place/transfer/$input
    
    if {![file exists $ifile] || $padamm_rebuild_file} {
	if !$terse {
	    if {[query_question .query "Rebuild padamm file $ifile?"] \
		== "*cancel*"} return
	}
	if {![rebuild_padamm_input $ifile]} return
	if !$terse {
	    if {[query_question .query "Edit padamm file $ifile?"] \
		== "*okay*"} {run_editor $ifile}
	}
    }
    
    if $terse {
	infomsg "Removing all existing domains..."
	catch {eval exec /bin/rm -f [glob -nocomplain $place/domains/domain.*]}
	set fp [open $place/transfer/user.ing w]
	puts $fp end; close $fp
    } else {
	if {![remove_some_domains $ifile Padamm]} return
	exec /bin/rm -f $place/transfer/user.ing
    }
    
    set back [pwd]
    cd $place/transfer
    if $terse {
	set command "nice +4 $padamm_path o=Padammo"
    } else {
	set command "$padamm_path o=Padammo"
    }
    if $standalone {wm withdraw .}
    
    if 0 {
	this needs to be done in a different way
	set mailcmd "echo Padamm is done. \| \
		 Mail -s Padamm [exec whoami]@[exec uname -n]"
	set command "$command \; $mailcmd"
    }
    
    if {$padamm_back == "true"} {
	infomsg "Running padamm in the background -- you can terminate\
		icemcfd and padamm will still run to completion"
	
	set in  [open $input r]
	set out [open /tmp/$input.tmp w]
	while {[gets $in line] >= 0 } {
	    if {[regexp {^[ 	]*sfon|^[Cc][ 	]*sfon} $line ]} {
		puts $out $line
		puts $out "  nopl"
	    } else {
		puts $out $line
	    }
	}
	close $in
	close $out
	set input /tmp/$input.tmp
        set command "$command i=$input"
        set command "nohup $command >& /tmp/padamm.out.[pid] < /dev/null &"
	runxcom_remote PADAMM $command "" 0 1
    } else {
        set command "$command i=$input"
	runxcom_remote PADAMM $command "" 1 0
    }
    
    cd $back
}

proc rebuild_padamm_input {pifile} {
    global place partfile waiting_for_part rebuild_indices
    global domains padamm_terse gui_name
    
    set place $place
    
    if {$partfile == ""} {
	set waiting_for_part 1
	if {[query_waitvar .query "There is no part defined -- please select one."] \
	    == "*cancel*"} {
		set waiting_for_part 0
		return 0
	    }
    }
    
    if {![part_is_mulcad]} {
	errormsg "Current part isn't in mulcad!"
	return 0
    }
    set tail [file tail $partfile]
    if {![string match "iparta.*" $tail]} {
	if {[query_question .query "Part is not an IPARTA file -- \
really use it for the PADAMM input file?"] == "*cancel*"} {return 0}
    }
    
    if {![file exists $place/mesh/header]} \
	{errormsg "Can't find the mesh/header file."; return 0}
    
    exec sed "s~\.\./parts/iparta\..*~\.\./parts/[file tail $partfile]~" \
	< $place/mesh/header > $pifile
    #	exec cp $place/mesh/header $pifile
    
    set indices [glob -nocomplain $place/mesh/index*]
    set inums {}
    foreach index $indices {
	if {![regexp {.*index([0-9]+)$} $index dummy num]} continue
	lappend inums $num
    }
    if {$inums == ""} {
	errormsg "There are no index files in the mesh directory."
	return 0
    }
    
    if {$padamm_terse == "true"} {
	set picked [numsort $inums]
    } else {
	toplevel .isel
	set picked [pickord .isel {-text "Select the domains \
you want to include in the PADAMM input file.  Type the F1 key in this \
window for help."} $inums]
    }
    
    if {($picked == "*cancel*") || ($picked == "")} {return 0}
    
    infomsg "Writing file $pifile..."
    foreach num $picked {
	if {[file exists $place/mesh/index$num]} then \
	    {exec sh -c "cat $place/mesh/index$num \
				 >> $pifile"} else \
	    {errormsg "No such index file index$num"}
    }
    exec sh -c "echo end >> $pifile"
    
    # this is temporary
    for {set i 0} {[file exists /tmp/xxx.$i]} {incr i} {}
    exec sed "s/C block/block/" < $pifile > /tmp/xxx.$i
    exec /bin/cp /tmp/xxx.$i $pifile
    exec /bin/rm /tmp/xxx.$i
    infomsg "Done."
    
    return 1
}

# ----------

if {![info exists standalone]} {
    set standalone 1
    set is_win 0
    set batch 0
    
    if {![info exists env(ICEM_ACN)]} {
	puts stdout "Error: Please set the ICEM_ACN environment variable"
	exit
    }
    
    set inputfile index
    set padamm_terse false
    set padamm_back false
    set remotehost ""
    set rargs {}
    for {set i 0} {$i < $argc} {incr i} {
	set arg [lindex $argv $i]
	case $arg in {
	    -q  {set padamm_terse true}
	    -rh {incr i; set remotehost [lindex $argv $i]}
	    default {lappend rargs $arg}
	}
    }
    
    # 3 arguments -- confname, geoname, and partname.
    if {[llength $rargs] != 3} {
	puts {Usage: padammif [-q] [-rh host] confname geoname partfile}
	exit 1
    }
    set confname [lindex $rargs 0]
    set geoname [lindex $rargs 1]
    set place mulcad/$confname/$geoname
    set partfile $place/parts/[lindex $rargs 2]
    set padamm_path $env(ICEM_ACN)/icemcfd/padamm
    set xterm_params "-geometry =80x24+10+50 -fn 9x15bold -fg black \
-cr black -bg wheat -sb -sl 10000"
    set runcoms 1
    
    proc first_existing_font {fonts} {
	foreach f $fonts {
	    catch {destroy .xxx}
	    if {![catch "toplevel .xxx; button .xxx.yyy -font $f"]} {
		destroy .xxx
		return $f
	    }
	}
	puts stderr "Fatal error: no fonts available from list: $fonts"
	exit 1
    }
    
    # If this is an IBM, use different fonts because of an X server bug.
    set bigfont [first_existing_font {Rom14.500 -*-times-medium-r-normal--24* fixed}]
    set normalfont [first_existing_font {Rom14.500 -*-times-medium-r-normal--18* fixed}]
    set smallfont [first_existing_font {Rom14.500 8x13 fixed}]

    option add *font $normalfont
    
    option add *foreground black
    option add *background "#ffeedd"
    option add *activeForeground black
    option add *activeBackground "#bbffff"
    option add *selectForeground black
    option add *selectBackground "#ffee11"

    if {![file exists $place]} {
	puts stdout "Directory $place doesn't exist!"
	exit
    }
    
    # This should be a modal, but there is no modal editing here.
    foreach i {/usr/bin/ame /usr/sbin/jot /usr/bin/vi /usr/ucb/vi} {
	if [file exists $i] {set editor $i; break}
    }
    if {![info exists editor]} {
	puts "Warning: can't find an editor!"
	set editor /bin/cat
    }
    
    proc beep {} {puts stdout "\007" nonewline; flush stdout}
    proc lfirst {list} {lindex $list 0}
    proc llast {list} {lindex $list [expr {[llength $list] - 1}]}
    proc enable_interface {} {}
    proc disable_interface {} {}
    
    set scriptlib $env(ICEM_ACN)/lib/iceman
    set guilib $env(ICEM_ACN)/lib/guibase
    
    source $guilib/select-one.tcl
    source $guilib/query.tcl
    source $guilib/settings.tcl
    source $guilib/pathentry.tcl
    source $guilib/exec_cmds.tcl
    source $guilib/toplevel.tcl
    source $scriptlib/misc_iceman.tcl
    source $scriptlib/runcom_unix.tcl
    source $scriptlib/pickordered.tcl
    source $scriptlib/putarray.tcl
    source $scriptlib/picksome.tcl
    source $scriptlib/domains.tcl
    source $scriptlib/messages.tcl
    source $scriptlib/partlist.tcl
    
    set gui_name(Conf) Configuration
    set gui_name(Geo) Geometry
    set gui_name(conf) configuration
    set gui_name(geo) geometry
    
    foreach i [winfo child .] {catch {destroy $i}}
    
    message .message -aspect 200 -padx 30 -pady 30 -text \
	"PADAMM Interface.\n\n\
$gui_name(Conf)\t = $confname\n\
Geometry\t = $geoname\n\
Part file     \t = [file tail $partfile]"
    
    frame .query -relief raised -borderwidth 2
    query .query
    pack append . .message {top fill expand} .query {top fill}
    
    wm geometry . +300+300
    #putcenter .
    wm maxsize . [winfo screenwidth .] [winfo screenheight .]
    wm minsize . 400 [winfo height .]
    focus .
    update
    
    app_padamm
    exit
}
