
# 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

# This is for windows.
regsub -all \\\\ $env(ICEM_ACN) / env(ICEM_ACN)

if [file exists $env(ICEM_ACN)/icemcfd/version] {
    set fp [open $env(ICEM_ACN)/icemcfd/version r]
    set my_version [gets $fp]
    close $fp
} else {
    set my_version ?
}

set whoami " $my_version"
set whoami_fl "GeoMesh Manager $my_version"

global bindir
set bindir $env(ICEM_ACN)/bin

set starting_config ""
set starting_geo ""
set black_and_white 0
set icem_version 3.1
set icem_fluent 0
set icem_starcd 0
set icem_stamp  0
set icem_powermesh 0
set icem_input_for_fluent 0
set icem_tvda_for_powermesh 0
set icem_dxf_for_powermesh 0
set icem_tagging 0
set icem_tnh 0
set dlrem n

set comak_parts ""
set comak_objects 0
set solver ""
set standalone 0
set batch 0

# set home [glob ~]  this can fail on windows 
set cur [pwd]
cd
set home [pwd]
cd $cur

set gui_name(Conf) Project
set gui_name(conf) project
set gui_name(Geo) Subproject
set gui_name(geo) subproject
set gui_name(geopart) "Global CAD Parts"
set gui_name(meshpart) "Subproject CAD Parts"

for {set i 0} {$i < $argc} {incr i} {
    set arg [lindex $argv $i]
    case $arg in {
	-bw {
	    tk_setPalette white
	    # tk colormodel . mono
	    set black_and_white 1
	}
	-v {
	    # Unused ...
	    incr i
	    set icem_version [lindex $argv $i]
	}
	-fluent {
	    set icem_fluent 1
	    set env(ICEM_FLUENT) 1
            set my_version 3.3.0
	    set whoami_fl "GeoMesh Manager $my_version"
	    set whoami $whoami_fl
            if {![info exists env(FLUENT_ARCH)]} {
              set env(FLUENT_ARCH) 0
            }
	}	
        -powermesh {
            set icem_powermesh 1
	    set env(ICEM_POWERMESH) 1
            set my_version 3.3.0
            set whoami_fl "ICEM CFD Powermesh Manager $my_version"
            set whoami $whoami_fl
        }
	-exec {
	    incr i
	    set starting_command [lindex $argv $i]
	}
	-batch {
	    set standalone 1
	    set batch 1
	}
	default {
	    if {$starting_config == ""} {
		set starting_config $arg
	    } else {
		if {$starting_geo == ""} {
		    set starting_geo $arg
		}
	    }
	}
    }
}

if $batch {
    set tk_version 0
    proc enable_interface {} {}
    proc disable_interface {} {}
}

if {!$batch && [string match Windows* [winfo server .]]} {
    proc backslashify {s {n 1}} {
	set what ""
	for {set i 0} {$i < $n} {incr i} { append what \\\\ }
	regsub -all / $s $what s
	if {$n > 1} {
	    regsub -all {([^\])\\([^\])} $s \\1$what\\2 s
		      }
	return $s
    }
    set is_win 1
    set host_vendor nt
} else {
    proc backslashify {s {n 1}} {
	return $s
    }
    set is_win 0
    set host_vendor unix ;# not quite but ...
}

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
}

# The scripts sourced below expect these variables to be set.

if [info exists env(ICEMAN_DIR)] {
    set scriptlib $env(ICEMAN_DIR)
} else {
    set scriptlib $env(ICEM_ACN)/lib/iceman
}

if [info exists env(GUIBASE_DIR)] {
    set guilib $env(GUIBASE_DIR)
} else {
    set guilib $env(ICEM_ACN)/lib/guibase
}

if [info exists env(BETTIS_DIR)] {
    set bettislib $env(BETTIS_DIR)
} else {
    set bettislib $env(ICEM_ACN)/lib/bettis
}

set cfdcae "ICEM CFD/CAE"
if $icem_fluent { set cfdcae GeoMesh } 
if $icem_powermesh { set cfdcae "ICEM CFD Powermesh" }

if !$batch {
    if $icem_powermesh {
	# use smaller window and fonts for Powermesh - GWH 13.5.96
	# 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--18*
	    -*-*-bold-r-normal--*-160*
	    fixed
	}]
	set normalfont [first_existing_font {
	    Rom14.500
	    -*-times-bold-r-normal--14*
	    -*-*-bold-r-normal--*-140*
	    fixed
	}]
	set smallfont [first_existing_font {
	    Rom14.500
	    8x13
	    fixed
	}]
    } else {
	# 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*
	    -*-*-bold-r-normal--*-160*
	    fixed
	}]
	set normalfont [first_existing_font {
	    Rom14.500
	    -*-times-medium-r-normal--18*
	    -*-*-bold-r-normal--*-140*
	    fixed
	}]
	set smallfont [first_existing_font {
	    Rom14.500
	    8x13
	    fixed
	}]
    }
    
    option add *font $normalfont
    
    source $guilib/settings.tcl
    
    foreach b {Button Menubutton Radiobutton Checkbutton} {
	if !$black_and_white {
	    option add *$b.background "#ffddff"
	}
	option add *$b.relief raised
	option add *$b.borderwidth 2
    }
}

if !$black_and_white {
    set warningcolor "#880000"
    set errorcolor "#880000"
    set partlist_inactivecolor "#eeddcc"
} else {
    set warningcolor black
    set errorcolor black
    set partlist_inactivecolor black
}

# Simple utility  functions.

proc beep {} {puts stdout "\007" nonewline; flush stdout}
proc lfirst {list} {lindex $list 0}
proc llast {list} {lindex $list [expr {[llength $list] - 1}]}

proc ldelete {list elem} {
    set res {}
    foreach l $list {
	if {$l != $elem} {lappend res $l}
    }
    return $res
}

# Figure out what ICEM_ACN should be.  If the env variable isn't set, then
# set it and complain later.

if {![info exists env(ICEM_ACN)]} {
    set env(ICEM_ACN) /icem
    set complain_icem_acn 1
}

# Figure out if STAMP should be activated or be invisible

if {[info exists env(ICEM_STAMP)]} {
    set res $env(ICEM_STAMP)
    if {$res  == "on" || $res  == "ON"} {set icem_stamp 1}
    if !$icem_stamp {puts stdout "NO activation for ICEM_STAMP"}
}

# Figure out if ICEM INPUT should be made available for GeoMesh

if {[info exists env(ICEM_INPUT)]} {
    set res $env(ICEM_INPUT)
    if {$res  == "on" || $res  == "ON"} {set icem_input_for_fluent 1}
    if !$icem_input_for_fluent {puts stdout "NO activation for ICEM_INPUT"}
}

# Figure out if other Translators should be made available

if {[info exists env(ICEM_TVDA)]} {
    set res $env(ICEM_TVDA)
    if {$res == "on" || $res == "ON" || $res == "1"} {set icem_tvda_for_powermesh 1}
    if !$icem_tvda_for_powermesh {puts stdout "NO activation for ICEM_TVDA"}
}

if {[info exists env(ICEM_DXF)]} {
    set res $env(ICEM_DXF)
    if {$res == "on" || $res == "ON" || $res == "1"} {set icem_dxf_for_powermesh 1}
    if !$icem_dxf_for_powermesh {puts stdout "NO activation for ICEM_DXF"}
}

# disable file locking when running ICEM CFD products
set env(ICEM_NOLOCK) y

# Disable annoying behavior on windows.
set env(ICEM_NO_FOLDER) 1

# Fix a bug on IBM.
set env(ICEM_NO_SPACE_CHECK) 1

# allow longer file names
#set env(FILE_NAME_KEY) "1-27"

# Needed to make pcube run.
set env(PCUBE_STD) 1

if [info exists env(ICEM_TAGGING)] {
    set icem_tagging 1
}

if [info exists env(ICEM_TNH)] {
    set icem_tnh 1
}

if !$is_win {
    set uname [exec uname -a]
    
    if !$batch {
	set display_stuff [split $env(DISPLAY) :]
	set display_host [lindex $display_stuff 0]
	set display_rest [lindex $display_stuff 1]
	set hostname1 [exec uname -n]
	set hostname2 [lindex [split $hostname1 .] 0]
	
	set local_display [expr {($display_host == $hostname1) || \
				     ($display_host == $hostname2) || \
				     ($display_host == "") || \
				     ($display_host == "localhost")}]
	set console_display 1
	foreach n [split $display_rest .] {
	    if {$n != 0} { set console_display 0 }
	}
	
	# This is required on the sun.
	if {$local_display && ([file exists /usr/openwin] || \
				   [file exists /usr/openwin3.0])} {
	    if [info exists env(ICEM_SUN_DISPLAY_BUG)] {
		set env(DISPLAY) :$display_rest
	    }
	}
	# This is required on the SGI.
	if {!$local_display && \
		([string match "IRIX*5*" $uname] || \
		     [string match "IRIX*6*" $uname]) && \
		![file exists /usr/etc/resolv.conf]} {
	    puts "The ICEM CFD Manager may have problems connecting to your display."
	    puts "The reason is that the file /usr/etc/resolv.conf does not exist."
	    puts "If you have trouble starting up, please give the command, as root:"
	    puts "        ln -s /etc/resolv.conf /usr/etc/resolv.conf"
	}
    }
    # This is required on the IBM.
    if {[string match "AIX*" $uname]} {
	if {![info exists env(LIBPATH)]} {
	    set env(LIBPATH) /lib:/usr/lib
	}
	set env(LIBPATH) $env(LIBPATH):$env(ICEM_ACN)/lib
    }
}

if $is_win {
    if ![info exists env(LM_LICENSE_FILE)] {
	set env(LM_LICENSE_FILE) $env(ICEM_ACN)/lic/license.dat
    }
}

if [info exists env(PRINTER)] {
    set printer_name $env(PRINTER)
} else {
    set printer_name PostScript
}

# Load any configuration parameters that are needed before the widgets
# are created.

set rc $home/.iceman_resources
if [file exists $rc] {source $rc}

if {$icem_fluent && [file exists $scriptlib/fluent_resources.tcl]} {
    source $scriptlib/fluent_resources.tcl
}

# Load up all the sub-scripts that we use.

if !$batch { wm withdraw . }

source $env(ICEM_ACN)/icemcfd/output-interfaces/solver_table.tcl

set guifiles {
    scroller
    query
    select-one
    questionbox
    pathentry
    my-dialog
    misc
    checkbox
    exec_cmds
    forms
    formutil
    toplevel
}

set scriptfiles {
    commands
    vcbox
    pickone
    picksome
    putarray
    pickordered
    dialog
    programs
    solvers
    sparams
    modals
    routines
    padammif
    misc_iceman
    sysinfo
    messages
    partlist
    domains
    domselect
    game
    locking
    license
    help_table
    help_iceman
}

foreach f $guifiles {
    source $guilib/$f.tcl
    
}

foreach f $scriptfiles {
    source $scriptlib/$f.tcl
}

if !$batch {
    source $scriptlib/interface.tcl
}

if $is_win {
    source $scriptlib/runcom_win.tcl
} else {
    source $scriptlib/runcom_unix.tcl
}

if [file exists ./bettis-routines.tcl] {
    source ./bettis-routines.tcl
} elseif [file exists $bettislib/bettis-routines.tcl] {
    source $bettislib/bettis-routines.tcl
}

set small_screen_hack 0
proc busy {args} {}

if !$batch { add_menu_buttons }

locate_useful_programs

proc mess {str {c ""} {f ""}} { infomsg "$str\n" }

if !$batch {
    set help_base manager/Manager
    help_setup
    help_info_define

    wm geometry . +100+100
    #putcenter .
    wm maxsize . [winfo screenwidth .] [winfo screenheight .]
    #wm minsize . [winfo width .] [winfo height .]
    
    focus .
    update
    wm deiconify .
}

# Some global variables.

proc reset_label_vars {} {
    global confname geoname partname sheetname partfile solver
    
    set confname ""
    set geoname ""
    set partname ""
    set sheetname ""
    set partfile ""
}
reset_label_vars

if ![check_path_all [pwd]] {
    puts "Current path name has some problems: can't run ICEM CFD"
    puts "Path is \"[pwd]\""
    exit 1
}

if ![check_path_all $env(ICEM_ACN)] {
    puts "ICEM_ACN variable has some problems: can't run ICEM CFD"
    puts "ICEM_ACN is \"$env(ICEM_ACN)\""
    exit 1
}

set runcoms 1
set solver $solver
if $icem_fluent { set solver fluent } 
#if $icem_powermesh { set solver "" }

set place ""

proc update_place {args} {
    global confname geoname place
    if {($confname == "") || ($geoname == "")} {
	set place ""
    } else {
	set place mulcad/$confname/$geoname
    }
}

trace variable confname w update_place
trace variable geoname w update_place

# This is an annoying trick.
set domains(xxx) {}

# These are in the form of a list of triples: {name file sheetno}.
set global_parts {}
set local_parts {}

proc tkerror err {
    global errorInfo is_win
    warningmsg {An internal error has occurred: check the window \
from which icemcfd was run.  Please report this error to ICEM Systems.}
    enable_interface
    if $is_win {
	warningmsg $errorInfo
    } else {
	puts stderr "$errorInfo"
    }
}

set rc $home/.iceman_init
if [file exists $rc] {source $rc}
set rc .iceman_init
if [file exists $rc] {source $rc}

if {$icem_fluent && [file exists $scriptlib/fluent_init.tcl]} {
    source $scriptlib/fluent_init.tcl
}

set install_date "(date unknown)"
if !$icem_fluent {
	if ![catch {open $env(ICEM_ACN)/release_date r} fp] {
	    set install_date [gets $fp]
     	    close $fp
        }
} else {
        if ![catch {open $scriptlib/install_date_fluent r} fp] {
            set install_date [gets $fp]
            close $fp
        }
}

if !$batch {
    update
    if $icem_fluent {
	infomsg "Welcome to the $whoami - Copyright (c) 1993 - 1999 ICEM CFD Engineering"
	infomsg "Version of $install_date."
    } elseif $icem_powermesh {
	infomsg "Welcome to the $whoami - Copyright (c) 1993 - 1999 ICEM CFD Engineering"
	infomsg "Version of $install_date."
    } else {
	infomsg "Welcome to $whoami."
	if [file exists $env(ICEM_ACN)/release_date] {
	    set fp [open $env(ICEM_ACN)/release_date r]
	    infomsg "Version of [gets $fp]"
	    close $fp
	}
    }
    infomsg "For help on using this program, type ?, or select a topic \
from the help menu."
}

catch {check_sysinfo}

# ----------------------------------

if [info exists complain_icem_acn] {
    warningmsg "The environment variable ICEM_ACN wasn't set.\n\
A value of $env(ICEM_ACN) is being used for now,\nbut you should set \
it in your .cshrc file."
}

set env(ICEM_CASE_SENSITIVE) y
if ![info exists env(MOZILLA_HOME)] {
    set env(MOZILLA_HOME) $env(ICEM_ACN)/netscape
}

set env(USE_40) 1  ;# this is to prevent the new GUI stuff from happening

if {![info exists env(PATH)] && [info exists env(Path)]} {
    set env(PATH) $env(Path)
}

if !$is_win {
    if [info exists env(PATH)] {set path [split $env(PATH) :]} else {set path ""}
    foreach dir "$path /usr/X11/bin /usr/bin/X11 /usr/openwin/bin /usr/openwin3.0/bin " {
	if [file executable $dir/xterm] {set xterm_prog $dir/xterm; break}
    }
    
    if {![info exists xterm_prog]} {
	warningmsg "Can't find an xterm!  Please report this problem to\n\
ICEM Systems.  Running for now with degraded functionality."
    }
    
    if {![string match "OSF1*" $uname]} {
	
	if ![info exists env(LD_LIBRARY_PATH)] {
	    set env(LD_LIBRARY_PATH) $env(ICEM_ACN)/ddn/shared_lib
	} else {
	    append env(LD_LIBRARY_PATH) :$env(ICEM_ACN)/ddn/shared_lib
	}
	
	# ----------------------------------
	if {![string match "IRIX*" $uname]} {
	    if {![info exists env(LD_LIBRARY_PATH)]} {
		set env(LD_LIBRARY_PATH) .
	    }
	    
        if {[string match "SunOS*5.*" $uname]} {
	    foreach dir "/usr/openwin/lib \
	/usr/openwin3.0/lib /lib /usr/X11/lib /usr/lib/X11 \
	/opt/SUNWits/Graphics-sw/xgl/lib /usr/lib /lib" {
		append env(LD_LIBRARY_PATH) :$dir
	    }
        } else {
            foreach dir "/lib /usr/X11/lib /usr/lib/X11 \
        /usr/lib /lib" {
                append env(LD_LIBRARY_PATH) :$dir
            }
        }
	    set saved_ld_library_path $env(LD_LIBRARY_PATH)
	    
	    proc update_ld_library_path {} {
		global env saved_ld_library_path
		
		set env(LD_LIBRARY_PATH) $saved_ld_library_path
		
		append env(LD_LIBRARY_PATH) :$env(ICEM_ACN)/lib
		foreach dir [glob -nocomplain $env(ICEM_ACN)/ddn/lib.*] {
		    append env(LD_LIBRARY_PATH) :$dir
		}
		foreach dir [glob -nocomplain $env(ICEM_ACN)/ddn/shared*lib] {
		    append env(LD_LIBRARY_PATH) :$dir
		}
	    }
	    update_ld_library_path
	} else {
	    proc update_ld_library_path {} {}
	}
    } else {
	proc update_ld_library_path {} {}
    }
    
    # ----------------------------------
    
    if {[string match "SunOS*5.*" $uname] && ![info exists env(XGLHOME)]} {
	set env(XGLHOME) /opt/SUNWits/Graphics-sw/xgl
    }
    
    # This warns the user that the license is about to expire.
    # Also it sets up the list of features that are available.
    
    # Don't bother with this any more
    # check_license_expiration
}

if !$batch { add_menu_items }

if {![check_dirtree]} exit

set ddn_directory .ddn_directory

if {[file exists parts] && [file exists parts/$ddn_directory]} {
    set ptime [file mtime parts]
    set dtime [file mtime parts/$ddn_directory]
    if {$ptime > $dtime} {
	infomsg "Updating DDN directory in parts -- it looks like it is out of date..."
	update_partlist d 1
    }
}

# Yuck.
set orc $home/.icemanrc
if [file exists $orc] {
    infomsg "Note: the file ~/.icemanrc is no longer used by the manager -- \
customization code should now be put in the file ~/.iceman_init"
}

if {$starting_config != ""} {
    if ![file exists mulcad/$starting_config] {
	cmd_mkdir mulcad/$starting_config
    }
    if ![get_config_lock $starting_config] {
	set starting_config ""
    }
}

if {$starting_config != ""} {
    set confname $starting_config
    if {!$icem_fluent && !$icem_powermesh} {
	if ![file exists objects/$confname] {
	    cmd_mkdir objects/$confname
	}
    }
    if {$starting_geo != ""} then {set geoname $starting_geo} else \
	{set geoname [lfirst [possible_geometries]]}
    if {$geoname == ""} {
	set geoname $default_geoname
	infomsg "No $gui_name(geo) given; using default \"$geoname\""
    }
    if ![file exists mulcad/$confname/$geoname] {
	cmd_mkdir mulcad/$confname/$geoname
    }
    if {!$icem_fluent && !$icem_powermesh} {
	if ![file exists objects/$confname/$geoname] {
	    cmd_mkdir objects/$confname/$geoname
	}
    }
    
    # Here we will assume that the DDN directories are okay.
    update_partlist - 0
} else {
    update_partlist d 0
    config_open 0
}

if $icem_powermesh {
    set solver [get_modal_choices_presets solver]
    if {$solver == "CFDS-FLOW3D"} {set env(ICEM_POWERMESH) 2}
}

if !$batch {
    foreach b {Button Menubutton Radiobutton Checkbutton} {
        option add *$b.background [. cget -background]
    }
}

infomsg "Ready."

if [info exists starting_command] { eval $starting_command }
