#ICEM CFD solver interface routine for the manager.
#
# Copyright (c) 1993-2004 ICEM Systems.
# Copyright (c) 1994-2004 ACUSIM Software

proc acusolve_write_input {} {
    global file_name acusolve_output_path env solution

    get_boco_topo

    set problem_dir	$file_name(transfer_dir)
    if {[info exists file_name(solver_params)] && ($file_name(solver_params) != "")} {
	set paramfile   $file_name(solver_params)
    } else {
	set paramfile	$file_name(mesh_dir)/acusolve.par
    }
    set icmfile		$env(ICEM_ACN)/icemcfd/output-interfaces/acusolve.icm
    set geomfile	$env(ICEM_ACN)/icemcfd/output-interfaces/acusolve_geom
    set perlscript	$env(ICEM_ACN)/icemcfd/output-interfaces/acusolve.pl
    set aux		""
    set crd_scale	1.0
    set inp_flag	1
    set pbc_flag	0
    set pbc_pnt1	"0,0,0" 
    set pbc_pnt2	"0,0,1" 
    set nic_flag	0
    set intern_wall	1
    set verbose		1
    
    set save_params {
	problem_dir problem paramfile aux crd_scale inp_flag pbc_flag 
	pbc_pnt1 pbc_pnt2 nic_flag intern_wall verbose
    }
    foreach p $save_params {
	if [info exists solution(acusolve-$p)] {
	    set $p $solution(acusolve-$p)
	}
    }
    
    set domain [domain_select $file_name(domains_dir) \
		"Select an unstructured domain." unstruct 0]
    if {$domain == {}} return

    set problem	[file tail [file rootname $domain]]

    if {![dialog .acusolve "AcuSolve" \
      "Please edit the following AcuSolve options." {
        {problem -type string -title "AcuSolve problem name"
	    -help "Name of the problem; no imbedded spaces" }
        {problem_dir -type path -title "AcuSolve problem directory"
	    -help "Directory where problem files are saved and run"}
        {paramfile -type path -title "Parameter file"
	    -help "AcuSolve parameter file name"}
        {bocofile -type path -title "Boundary condition file"
	    -help "Boundary condition file name"}
        {crd_scale -type string -title "Coordinates scaling factor"
	    -help "Multiply coordinates by this number"}
        {aux -type string -title "User auxiliary script"
	    -help "Optional script/command to execute after translation"}
        {inp_flag -opt {{"Yes" 1} {"No" 0}} -title "Write .inp file"
	    -help "Should a new .inp file be written?"}
        {nic_flag -opt {{"Yes" 1} {"No" 0}} 
	    -active {$inp_flag} -title "Create .nic files for OptiMesh"
	    -help "Should generic initial condition files be created?"}
        {intern_wall -opt {{"Yes" 1} {"No" 0}} -title "Write internal wall"
	    -help "Should internal (non-manifold) walls be translated as BC?"}
    }]} return

# OLD Style pbc: Changed May 2004
#
#	{pbc_flag -opt {{"None" 0} {"Periodic" 1} {"Axisymmetric" 2}}
#	    -active {$inp_flag} -title "Periodic condition"
#	    -help "Type of periodic BC in the problem"}
#	{pbc_pnt1 -type string -title "Point 1 on axis of rotation"
#	    -active {$inp_flag&&$pbc_flag==2}
#	    -help "First point on the axis of axisymmetric periodic BC"}
#	{pbc_pnt2 -type string -title "Point 2 on axis of rotation"
#	    -active {$inp_flag&&$pbc_flag==2}
#	    -help "Second point on the axis of axisymmetric periodic BC"}

    if {![file exists $bocofile]} {
        errormsg "Bound. Cond. file $bocofile doesn't exist"
        return
    }
 
    if {![file exists $paramfile]} {
        errormsg "AcuSolve parameter file $paramfile doesn't exist"
        return
    }
 
    foreach p $save_params {
	set solution(acusolve-$p) [set $p]
    }

    if [file exists $problem_dir] {
	if ![file isdirectory $problem_dir] {
	    mess "Error: $problem_dir is not a directory" mess red
	    return
	}
    } else {
	cmd_mkdir $problem_dir
    }

    set plfile $problem_dir/plfile
    set fp [open $plfile w]

    puts $fp "-b $bocofile"
    puts $fp "-dom $domain"
    puts $fp "-par $paramfile"
    puts $fp "-pb $problem"
    puts $fp "-dir $problem_dir"
    puts $fp "-icm $icmfile"
    puts $fp "-geom \"$geomfile\""
    if {$aux != ""} { puts $fp "-aux $aux" }
    puts $fp "-scale $crd_scale"
    puts $fp "-inp $inp_flag"
    puts $fp "-pbc $pbc_flag"
    puts $fp "-pnt1 $pbc_pnt1"
    puts $fp "-pnt2 $pbc_pnt2"
    puts $fp "-nic $nic_flag"
    puts $fp "-iw $intern_wall"
    puts $fp "-v $verbose"

    close $fp


# next two lines modified by FS August 2004
#     set command "perl \"$perlscript\" \"$plfile\""
#     runxcom ICEM-CFD/ACUSOLVE-Interface $command "" 1 0
    set command "perl \"$perlscript\" \"$plfile\""
    runxcom ICEM-CFD/ACUSOLVE-Interface $command "" 1 0
}

proc acusolve_run_solver {} {
}

proc acusolve_solution_start {} {
    global file_name acusolve_output_path env solution is_win
    
    set problem_dir	$file_name(transfer_dir)
    set problem		"acusolve"
    set acu_home	""
    set acu_machine	""
    set acu_version	"latest"
    set nprocs		"1"
    set hosts		""
    set run_opts	""

    if {![info exists env(ACUSIM_HOME)]} {
        errormsg "ACUSIM_HOME not defined; find and source .acusim"
        return
    }
    if {![info exists env(ACUSIM_MACHINE)]} {
        errormsg "ACUSIM_MACHINE not defined; find and source .acusim"
        return
    }
    if {![info exists env(ACUSIM_VERSION)]} {
        errormsg "ACUSIM_VERSION not defined; find and source .acusim"
        return
    }

    set acu_home    $env(ACUSIM_HOME)    
    set acu_machine $env(ACUSIM_MACHINE) 
    set acu_version $env(ACUSIM_VERSION)
    
    set save_params {
	problem_dir problem acu_home acu_machine acu_version nprocs hosts
	run_opts
    }
    foreach p $save_params {
	if [info exists solution(acusolve-$p)] {
	    set $p $solution(acusolve-$p)
	}
    }

    if {![dialog .acusolverun "Run AcuSolve" \
      "Please edit the following AcuSolve run options." {
        {problem -type string -title "AcuSolve problem name"
	    -help "Name of the problem; no imbedded spaces"}
        {problem_dir -type path -title "AcuSolve problem directory"
	    -help "Directory where problem files are saved and run"}
	{acu_home -type path -title "ACUSIM home directory"
	    -help 
	    "ACUSIM install directory; if undefined, find and source .acusim"}
	{acu_machine -type string -title "ACUSIM machine"
	    -help "ACUSIM machine type"}
	{acu_version -type string -title "ACUSIM release"
	    -help "ACUSIM release number"}
	{nprocs -type string -title "Number of processors"
	    -help "Number of processors"}
	{hosts -type string -title "List of hosts for parallel run"
	    -help "Comma separated list of hosts to run in parallel"}
	{run_opts -type string -title "Additional acuRun options"
	    -help "Pass these additional parameters to acuRun"}
    }]} return

    foreach p $save_params {
	set solution(acusolve-$p) [set $p]
    }

    set env(ACUSIM_HOME)    $acu_home
    set env(ACUSIM_MACHINE) $acu_machine
    set env(ACUSIM_VERSION) $acu_version
    
    set acudir "$acu_home/$acu_machine/$acu_version"

    set acuRun "$acudir/bin/acuRun"
    set acuRun "$acuRun -np $nprocs"
    if {$hosts != ""} { set acuRun "$acuRun -hosts $hosts" }
    set acuRun "$acuRun $run_opts"

    if $is_win {
	set cmdfile "cmdfile.bat"
    } else {
	set cmdfile "cmdfile"
    }
    set fp [open $problem_dir/$cmdfile w]
    if $is_win {
	set acu_cnf ".\Acusim.cnf:~\Acusim.cnf:$acudir\script\Acusim.cnf"
	if {[info exists env(ACUSIM_CNF_FILES)]} {
	    set acu_cnf $env(ACUSIM_CNF_FILES)
	}
	puts $fp "set ACUSIM_HOME=$acu_home"
	puts $fp "set ACUSIM_VERSION=$acu_version"
	puts $fp "set ACUSIM_MACHINE=$acu_machine"
	puts $fp "set ACUSIM_CNF_FILES=$acu_cnf"
	puts $fp "$acuRun"
	puts $fp "echo done > solver_is_done"
    } else {
	puts $fp "\#!/bin/csh -f"
	puts $fp "source $acudir/script/.acusim"
	puts $fp "$acuRun"
	puts $fp "echo done > solver_is_done"
    }
    close $fp
    if $is_win { } else {
	cmd_chmod 0755 $problem_dir/$cmdfile
    }
    set ltime [file mtime $problem_dir/$cmdfile]

    set back [pwd]
    cd $problem_dir
    cmd_rm solver_is_done
    set pid [exec ./$cmdfile &]
    
    mess "Started acuRun in the directory [pwd]\n"

    set lfile ""
    for {set tries 0} {$tries < 10} {incr tries} {
	set files [glob -nocomplain "$problem.*.Log"]
	foreach file $files {
	    if { $ltime < [file mtime $file] } {
		set lfile $file
		set ltime [file mtime $file]
	    }
	}
	if { $lfile != "" } { break }
	after 1000
    }
    if {$lfile == ""} {
	mess "Warning: acuRun doesn't seem to have started\n"
    } else {
	mess "acuRun log redirected to $lfile\n"
    }

    set lrun 0
    if { [regexp {^(.+)\.([0-9]+)\.Log$} $lfile a b c] == 1 } {
	set lrun $c
    }
    
    if $is_win { 
	set bltwish "$env(ICEM_ACN)/bin/wish" 
    } else {
	set bltwish "$env(ICEM_ACN)/bin/bltwish" 
    }
    set acutail "$env(ICEM_ACN)/icemcfd/output-interfaces/acusolve_tail.tcl"
    if $is_win { 
	regsub -all \\\\ $bltwish / bltwish
	regsub -all \\\\ $acutail / acutail
    }
    if [file exists $lfile] {
	set mpid [exec $bltwish $acutail $lfile &]
    }
    cd $back

    # Apparently this does not exit until the job is done: oops
    acusolve_control_menu $pid $problem_dir "$acudir/bin" $lrun $lfile
}

proc acusolve_control_menu {pid problem_dir bindir lrun lfile} {
    global acu_job_running env is_win

    set bltwish "$env(ICEM_ACN)/bin/bltwish" 
    set acumon  "$env(ICEM_ACN)/icemcfd/output-interfaces/acusolve_monitor.tcl"
    set logfile "$problem_dir/$lfile"

    if $is_win { 
	set acusig "$bindir/acuSig.bat"
    } else {
	set acusig "$bindir/acuSig"
    }

    if $is_win { 
	regsub -all \\\\ $bltwish / bltwish
	regsub -all \\\\ $acumon  / acumon
	regsub -all \\\\ $logfile / logfile
	regsub -all \\\\ $acusig  / acusig
    }

    toplevel .kill
    if !$is_win { 
	button .kill.b1 -text "Launch AcuSolve Monitor" \
		-command "exec $bltwish $acumon 0 $lrun $logfile &"
	button .kill.b2 -text "Kill AcuSolve Run Now" \
		-command "acusolve_kill $pid"
    }
    button .kill.b3 -text "Stop Run at End of Current Step" \
		-command "exec $acusig -pdir $problem_dir -stop"
    button .kill.b4 -text "Output Results at End of Current Step" \
		-command "exec $acusig -pdir $problem_dir -out"
    button .kill.b5 -text "Close Window" -command "destroy .kill"
    if $is_win { 
	pack .kill.b3 .kill.b4 .kill.b5 -expand 1 -fill x
    } else {
	pack .kill.b1 .kill.b2 .kill.b3 .kill.b4 .kill.b5 -expand 1 -fill x
    }
    wm geometry .kill +10+10
    wm title .kill "AcuSolve Job Control"

    # This doesn't look right!
    while {[check_process_exists $pid]} {
	after 5000 "set acu_job_running 1"
	vwait acu_job_running
    }
    destroy .kill
    warningmsg "\nAcuSolve Job <$pid> has terminated!\n"
    popup AcuSolve "AcuSolve job <$pid> has terminated"
}

proc acusolve_kill {pid} {

    set pids $pid
    set ps [exec ps -eo ppid,pid]
    foreach a [split $ps "\n"] {
	if { [regexp {^ *([0-9]+) +([0-9]+) *$} $a b c d ] == 1 } { 
	    if {$c == $pid} {
		set pids "$pids $d"
	    }
	}

    }
    warningmsg "\n killing pids <$pids>\n"
    exec kill $pids
}
