#
# RunWin 
#

proc RunWin { { w .wrun  }  } {
    if { [info commands RunFiniteElemCode] != "" } {
	RunWinOld $w
    } else {
	OpenProcWin $w
    }
}

proc RunWinOld { { w .wrun  }  } {
    global wRunWin GIDDEFAULT
    set wRunWin $w
    catch { destroy $w }
    toplevel $w
    set pare [winfo parent $w]
    set posx [expr [winfo x $pare]+[winfo width $pare ]/4]
    set posy [expr [winfo y $pare]+[winfo height $pare ]/4]
    wm geometry $w [join "+$posx + $posy" ""]
    wm title $w [_ "Calculating"]
    label $w.lt -text [_ "Calculate"]...
    catch { $w.lt conf -font -Adobe-times-medium-r-normal--*-180* }
#     set imm [image create photo -file $GIDDEFAULT/bitmaps/cimne-draw.gif]
#     label $w.bmp -image $imm
   label $w.bmp -bitmap @$GIDDEFAULT/bitmaps/cimne-draw
    frame $w.fr1
    button $w.fr1.b1 -text [_ "Calculate"] -command "Calculate $GIDDEFAULT"
#    button $w.fr1.b2 -text "Postprocess" -command "Postprocess $GIDDEFAULT"

    set ProjectName [file root [lindex [.central.s info Project] 1]]
    set directory $ProjectName.gid
    set basename [file tail $ProjectName]


    button $w.fr1.b3 -text [_ "Delete calc files"] -command \
	    "DeleteCalculationFilesInRunWin $w $basename $directory"
    button $w.fr1.b4 -text [_ "Close"] -command "destroy $w"
    pack $w.fr1.b1 $w.fr1.b3 $w.fr1.b4 -side left -padx 5 -pady 5 -ipadx 5
    pack $w.lt $w.bmp $w.fr1 -side top

}

proc DeleteCalculationFilesInRunWin { w name directory } {

    set res [mkDialogN $w.modal [list -text [_ "Sure, delete all calculation files?"] \
		-aspect 250 -justify left]  [list [_ "Cancel"] CANCEL] [list [_ "Ok"] OK]]
    if { $res == "CANCEL" } { return }

    set res [catch { DeleteCalculationFiles $name $directory}]
    if { $res == 0 } { 
	mkDialogN $w.modal [list -text [_ "All files deleted"] \
		-aspect 250 -justify left] [list [_ "Ok"] OK]
    } else {
	mkDialogN $w.modal [list -text [_ "Problems deleting files"] \
		-aspect 250 -justify left] [list [_ "Ok"] OK]
    }
}

proc GiveProcessPids { name } {
    set aa ""
    catch { set aa [exec ps -f | grep $name | grep -v /bin/time | grep -v grep] }
    set retnums ""
    while 1 {
	set newpos [expr [string first \n $aa]-1]
	if { ![catch { [expr [lindex $aa 0] > 0] } ] } {
	    lappend retnums [lindex $aa 0]
	} else { lappend retnums [lindex $aa 1] }
	if { $newpos < 0 } { break }
	set aa [string range $aa [expr $newpos+2] end]
    }
    return $retnums
}

proc TestIfExists { name window { DoIfFinished ""} } {
    set aa [GiveProcessPids $name]
    if { ![winfo exists $window] } { return }
    if { [lindex $aa 0] == "" } {
	destroy $window
	if { $DoIfFinished != "" } { eval $DoIfFinished }
	return 
    }
    after 3000 TestIfExists $name $window
}

proc FillResultsWindow { w file LastSize } {
    if { ![winfo exists $w] } { return }
    if { [catch { set newsize [file size $file] }] } { $w.f.t del 0.0 end ; return }
    if { $newsize > $LastSize } {
	$w.f.t insert end [exec tail [join "+ $LastSize c" ""] $file]
	$w.f.t yview end
	set LastSize $newsize
    }
    after 3000 FillResultsWindow $w $file $LastSize
}

proc ResultsWindow { w file } {

    catch { destroy $w }
    toplevel $w
    wm title $w [_ "Results"]
    wm geometry $w -250+200

    frame $w.f
    text $w.f.t -width 80 -height 40 -xscroll "$w.f.xscroll set" \
	    -yscroll "$w.f.yscroll set" -wrap none
    scrollbar $w.f.yscroll -relief sunken -command "$w.f.t yview"
    scrollbar $w.f.xscroll -relief sunken -command "$w.f.t xview" \
	    -orient horizontal
    pack $w.f.yscroll -side right -fill y
    pack $w.f.xscroll -fill x -side bottom
    pack $w.f.t -expand yes -fill y -anchor nw
    
    button $w.b -text [_ "Close"] -command "destroy $w"
    pack $w.b -side bottom
    pack $w.f -side top

    FillResultsWindow $w $file 0
}

proc Calculate { GIDDEFAULT } {
    global wRunWin

    set aa [.central.s info Project]
    set ProblemType [lindex $aa 0]
    set ProjectName [lindex $aa 1]
    
    set ProjectName [file root $ProjectName]
    set directory $ProjectName.gid
    set basename [file tail $ProjectName]
    

    if { $ProjectName == "UNNAMED" } {
	mkDialogN .modal [list -text [_ "Before calculating, a project title is needed. Save project to get it"] \
		-aspect 250 -justify left]  [list [_ "Ok"] OK]
	destroy $wRunWin
	return
    }
    if { ![.central.s info variables CalcWithoutMesh] } {
	if { [lindex [.central.s info Mesh] 0] == 0 } {
	    mkDialogN .modal [list -text [_ "Don't forget to generate the mesh"] -aspect 250 \
		    -justify left] [list [_ "Ok"] OK]
	    destroy $wRunWin
	    return
	}
    }
    switch $ProblemType {
	vulcann {
	    set analysistype [lindex [.central.s info gendata] 2]
	    if { $analysistype != "Thermal" } {
		mkDialogN .modal [list -text [_ "Sorry, only Thermal analysis allowed"] \
				-aspect 250 -justify left] [list [_ "Ok"] OK]
		destroy $wRunWin
		return
	    }
	    set scriptexe $GIDDEFAULT/vulcan-t-ramsan
	    set programexe vulcan
	    set resfile $directory/$basename.res
	}
	omega1 {
	    set scriptexe $GIDDEFAULT/omega-ramsan
	    set programexe Omega
	    set resfile $directory/$basename.rss
	}
	default {
	    if { [catch { set res [RunFiniteElemCode $GIDDEFAULT $basename \
		    $directory] }] } {
		mkDialogN .modal [list -text [_ "Can't calculate this type of problem"] \
				-aspect 250 -justify left] [list [_ "Ok"] OK]
		destroy $wRunWin
		return
	    }
	    if { $res == "" } { return }
	    set scriptexe [lindex $res 0]
	    set programexe [lindex $res 1]
	    set resfile [lindex $res 2]
	}
    }

    mkDialog $wRunWin.calc [list -text [_ "Calculating. Wait, please"]... -aspect 250 \
		-justify left] [list [_ "Stop"] ""]
    #tkwait visibility $wRunWin.calc
    update idletasks

    set DefaultFileNAmeInCalcFile \
	    [.central.s info variables DefaultFileNAmeInCalcFile]
    if { $DefaultFileNAmeInCalcFile == 0 } {
	.central.s process escape escape escape escape utilities variables \
		DefaultFileNAmeInCalcFile 1 escape
    }

    .central.s process escape escape escape escape files WriteCalcFile

    if { $DefaultFileNAmeInCalcFile == 0 } {
	.central.s process escape escape escape escape utilities variables \
		DefaultFileNAmeInCalcFile 0 escape
    }

    puts [exec $scriptexe $basename $directory]
    after 500

#     if { $resfile != "" } {
# 	ResultsWindow .wresults $resfile
# 	tkwait visibility .wresults
# 	catch { raise $wRunWin.calc }
#     }


    TestIfExists $programexe $wRunWin.calc
    set rescatch [catch { tkwait window $wRunWin.calc } ]

    set aa [GiveProcessPids $programexe]
    if { [lindex $aa 0] != "" } {
	exec kill -9 $aa

	mkDialogN $wRunWin.modal [list -text [_ "Calculation killed"] -aspect 250 \
	    -justify left]  [list [_ "Ok"] OK]
	return
    }

    mkDialogN $wRunWin.inter [list -text [_ "Running interface. Wait, please"]... \
            -aspect 250 -justify left]  [list [_ "Stop"] ""]

    switch $ProblemType {
	vulcann {
	    set posfile $directory/$basename.pos
	    set probtype [lindex [.central.s info gendata] 4]
	    set probword 2t
	    if { $probtype == "3D" } { set probword 3t }
	    exec echo "$probword\n$posfile\nc1\nc2\nc3\na" | interfla &
	    set interfaceexe interfla
	}
	omega1 {
	    exec om2sol $directory/$basename
	    set interfaceexe om2sol
	}
	default {
	    if { [catch { set res [RunInterfaceCode $GIDDEFAULT $basename \
		    $directory] }] } {
		destroy $wRunWin.inter
		mkDialogN .modal  [list -text [_ "Calculation failed"] \
	                -aspect 250 -justify left]  [list [_ "Ok"] OK]
		destroy $wRunWin
		return
	    }
	    if { $res == "" } {
		destroy $wRunWin.inter
		mkDialogN $wRunWin.killed  [list -text [_ "Calculation finished"] -aspect 250 \
			-justify left] [list [_ "Ok"] OK]
		return
	    }
	    set interfaceexe $res
	}
    }
    tkwait visibility $wRunWin.inter
    grab $wRunWin.inter
    TestIfExists $interfaceexe $wRunWin.inter
    catch { tkwait window $wRunWin.inter }
    set aa [GiveProcessPids $interfaceexe]
    if { [lindex $aa 0] != "" } {
	exec kill $aa
	mkDialogN $wRunWin.killed  [list -text [_ "interface killed"] -aspect 250 \
		-justify left] [list [_ "Ok"] OK]
#	set genname $ProjectName.gid/$basename-flavia
#	exec rm $genname.dat $genname.res >& /dev/null
    } else {
	mkDialogN $wRunWin.killed [list -text [_ "Calculation finished"] -aspect 250 \
		-justify left] [list [_ "Ok"] OK]
    }
}

proc Postprocess { GIDDEFAULT } {
    global wRunWin
    set aa [.central.s info Project]
    set ProblemType [lindex $aa 0]
    set ProjectName [lindex $aa 1]
    set ProjectName [file root $ProjectName]
    set basename [file tail $ProjectName]
    set directory $ProjectName.gid
    switch $ProblemType {
	vulcann {
	    set genname $ProjectName.gid/$basename-flavia
	    set fullname $genname.res
	    set probtype [lindex [.central.s info gendata] 4]
	    set program sol2pc
	    if { $probtype == "3D" } { set program sol3pc }
	    set options "-g 1000"
	}
	omega1 {
	    set genname $ProjectName.gid/$basename.flavia
	    set fullname $genname.res
	    set probtype [lindex [.central.s info gendata] 8]
	    set program sol2pc
	    if { $probtype == "3D_ELEMENTS" } { set program sol3pc }
	    set options "-g 1000"
	}
	default {
	    if { [catch { set res [RunPostProcessCode $GIDDEFAULT $basename \
		    $directory] }] } {
		mkDialogN .modal [list -text [_ "Can't run postprocess for this type of problem"] \
		       -aspect 250 -justify left]  [list [_ "Ok"] OK]
		destroy $wRunWin
		return
	    }
	    if { $res == "" } { return }
	    set genname [lindex $res 0]
	    set fullname [lindex $res 1]
	    set program [lindex $res 2]
	    set options [lindex $res 3]
	}
    }

    if { ![file exists $fullname] } {
	mkDialogN .modal [list -text [_ "There aren't results to postprocess"] -aspect 250 \
	       -justify left] [list [_ "Ok"] OK]
	return
    }
    set execline "exec $program $genname $options &"
    eval $execline
}