
# This code is shared by all the ICEM CFD GUI's.
#
# Copyright (c) 1993 - 1995 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

if [info exists env(PROFILE_TCL)] {
    # http://tcllib.sourceforge.net/doc/profiler.html
    puts "Profiling Tcl application ..."
    source $guibase_dir/profiler.tcl
    
    # what can be: calls, compileTime, exclusiveRuntime, nonCompileTime,
    #      totalRuntime, avgExclusiveRuntime, or avgRuntime
    proc prof_worst {{what exclusiveRuntime} {funcs ""} {reset 1}} {
	if {$funcs == ""} {
	    set funcs [lrange [lreverse [::profiler::sortFunctions $what]] 0 9]
	}
	foreach f $funcs {
	    puts [::profiler::print [lindex $f 0]]
	}
	if $reset { ::profiler::reset }
    }
    proc prof_all {{what exclusiveRuntime}} {
	set fp [open profile_out w]
	set funcs [lreverse [::profiler::sortFunctions $what]]
	foreach f $funcs {
	    puts $fp [::profiler::print [lindex $f 0]]
	}
	close $fp
	puts "wrote profile_out"
    }
    proc prof_pat {pat {what avgRuntime}} {
	set fp [open profile_out w]
	set funcs [lreverse [::profiler::sortFunctions $what]]
	foreach f $funcs {
	    if ![string match $pat [lindex $f 0]] continue
	    puts $fp [::profiler::print [lindex $f 0]]
	}
	close $fp
	puts "wrote profile_out"
    }
    
    ::profiler::init
}

#remove all others in auto_path except tcl and tk

set saved_path $auto_path
set auto_path ""
foreach d $saved_path {
   if {([file tail $d] == [file tail $tcl_library]) \
             || ([file tail $d] == [file tail $tk_library])} {
      lappend auto_path $d
   }
}

if [info exists tcl_platform(platform)] {
    set is_win [string compare $tcl_platform(platform) unix]
} else {
    set is_win [expr ![file exists /etc/passwd]]
}

# This is necessary for Windows ...
foreach i [array names env] { set env([string toupper $i]) $env($i) }

# Do this early because the user might have a messed up HOME environment.
if [catch {glob ~}] {
    if $is_win {
	set defhome c:/
    } else {
	set defhome /tmp
    }
    if [info exists env(HOMEDRIVE)] {
	lappend messages_at_startup [list "Warning: your home directory $env(HOMEDRIVE):$env(HOMEPATH) (%HOMEDRIVE%:%HOMEPATH%) doesn't exist: reset to c:/\n" red]
	set env(HOMEDRIVE) c:
	set env(HOMEPATH) /
	set env(HOME) c:/
    } elseif [info exists env(HOME)] {
	lappend messages_at_startup [list "Warning: your home directory $env(HOME) (\$HOME) doesn't exist: reset to $defhome\n" red]
	set env(HOME) $defhome
    } else {
	lappend messages_at_startup [list "Warning: you don't have a home directory (\$HOME): reset to $defhome\n" red]
	set env(HOME) $defhome
    }
}

if ![info exists has_blt] {
    set has_blt [expr {[info commands blt::table] != ""}]
}
set has_blt 0

if ![info exists tdv_default] { set tdv_default .v.view }

# First pre-process the args and get the ones we need before reading in the
# init files.

set rebuild_digest 0
set del_after_digest 0
set compile_tcl 0
set licensing_flags ""

# First extract the -tool argument and source that file.  That sets up
# all tool-specific information.

set to_scr 0
for {set i 0} {$i < $argc} {incr i} {
    set arg [lindex $argv $i]
    if !$to_scr {
	switch -- $arg {
	    -tool             { incr i; set tool_file [lindex $argv $i] }
	    -licensing        { incr i; set licensing_flags [lindex $argv $i] }
	    -use              { incr i }
	    -rd               { set rebuild_digest 1 }
	    -del_after_digest { set del_after_digest 1 }
	    -ct               { set compile_tcl 1 }
	    --                { set to_scr 1 }
	}
    }
}

if ![info exists guibase_dir] {
    if [info exists env(GUIBASE_DIR)] {
	set guibase_dir $env(GUIBASE_DIR)
    } else {
	set tgui [file dirname $tool_file]/guibase
	if [file exists $tgui] {
	    set guibase_dir $tgui
	} else {
	    set guibase_dir $env(ICEM_ACN)/lib/guibase
	}
    }
}

# These are the variables that should be customized by the tool file.
if ![info exists version] {
    if {[info exists env(ICEM_ACN)] && \
	    [file exists $env(ICEM_ACN)/icemcfd/version]} {
	set fp [open $env(ICEM_ACN)/icemcfd/version r]
	set version [string trim [read $fp]]
	close $fp
    } else {
	set version 4.x
    }
} else {
    set version [string trim $version]
}
if ![info exists whoami]  { set whoami "ICEM CFD" }
if ![info exists copyright] {
    if {[info exists env(ICEM_ACN)] && \
	    [file exists $env(ICEM_ACN)/icemcfd/copyright]} {
	set fp [open $env(ICEM_ACN)/icemcfd/copyright r]
	set copyright [string trim [read $fp]]
	close $fp
    } else {
	set copyright "Copyright (c) 2003 ICEM CFD Engineering"
    }
}

set tool_options ""
set tool_dir ""
set tool_bin ""
set tool_dir ""
set tool_dir2 ""
set tool_files ""
set tool_files2 ""
set tool_dir3 ""
set tool_files3 ""
set guibase_files_extra ""

set batch_type ""

set black_and_white 0
set use_xwindows 0
set use_dbuffer 1
set dlremote ""
set xwindows_fast 0
set use_lang ""
set language_text_encoding ""
set language_text_form_override 0
set no_pack_main 0

set tool_arguments ""
set tool_extra(2) blank

set source_dirs ""

# This needs to be defined early.

if $is_win {
    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
    }
} else {
    proc backslashify {s {n 1}} {
	return $s
    }
}

proc load_fileset {dir dfiles ifiles} {
    global rebuild_digest compile_tcl source_dirs is_win env tcl_version
    global del_after_digest prog_guide_files no_remove_after_digest
    
    if $rebuild_digest {
        puts "Rebuilding digest $dir/digest..."
        set out [open $dir/digest.in w]
	fconfigure $out -translation binary
        foreach f $dfiles {
            set fp [open $dir/$f.tcl r]
	    fconfigure $fp -translation binary
            set stuff [read $fp]
            close $fp
            puts $out $stuff nonewline
        }
        close $out
        digest create $dir/digest $dir/digest.in
        catch {exec rm -f $dir/digest.in}
	
	if $del_after_digest {
	    foreach f $dfiles {
		if {[info exists prog_guide_files] && 
		    ([lsearch $prog_guide_files $f] >= 0)} continue
		if {[info exists no_remove_after_digest] && 
		    ([lsearch $no_remove_after_digest $f] >= 0)} continue
		catch {exec rm -f $dir/$f.tcl}
		#puts "rm -f $dir/$f.tcl"
	    }
	}
    }
    
    set dmt 0
    if {([info commands digest] != "") && [file exists $dir/digest]} {
	set dmt [file mtime $dir/digest]
	puts "Loading digest $dir/digest"
	uplevel \#0 digest load \"$dir/digest\"
    }
    
    set try_ptcl [expr ![info exists env(USE_40)]]
    foreach f $dfiles {
	set file $dir/$f.tcl
	set file2 $dir/$f.ptcl
	set mt 0; set mt2 0
	if [file exists $file] {
	    set mt [file mtime $file]
	}
	if {$try_ptcl && ($tcl_version == 8.0) && [file exists $file2]} {
	    set mt2 [file mtime $file2]
	}
	
	if {($mt >= $mt2) && ($mt > $dmt)} {
	    if $dmt { puts "Loading file $f.tcl" }
	    uplevel \#0 source \"$file\"
	    
	} elseif {($mt2 > $mt) && ($mt2 > $dmt)} {
	    puts "Loading file $f.ptcl"
	    uplevel \#0 source \"$file2\"
	}
    }
    foreach f $ifiles {
	set file $dir/$f.tcl
	if $dmt { puts "Loading file $f.tcl" }
	uplevel \#0 source \"$file\"
    }
    lappend source_dirs $dir
}

source $guibase_dir/commands.tcl

if ![info exists batch_mode] { set batch_mode 0 }

if [info exists tool_file] { source $tool_file }


if {(!$batch_mode) && (!([info exists ai_environment] && $ai_environment)) } {
   if {[info exist bwidget_path] && [file exists $bwidget_path]} {
      lappend  auto_path $bwidget_path
      package require BWidget
   } elseif {[file exists $tool_dir/../bwidget]} {
      lappend auto_path $tool_dir/../bwidget
      package require BWidget 
   }
}

if {([info exists ai_environment] && $ai_environment) } {
    set tool_options {
	{ -script script_file 1 }
	{ -med_root med_root_ignore_value 1 }
    }
}

foreach opt $tool_options {
    if {[llength $opt] > 3} {
	set [lindex $opt 1] [lindex $opt 3]
    }
}

set script_args ""

set to_scr 0
for {set i 0} {$i < $argc} {incr i} {
    set arg [lindex $argv $i]
    if $to_scr {
	lappend script_args $arg
    } else {
	switch -glob -- $arg {
	    -bw            { set black_and_white 1 }
	    -x             { set use_xwindows 1 }
	    -gdi           { set use_xwindows 1 }
	    -ogl           { set use_xwindows 2 }
	    -xfast         { set use_xwindows 1; set xwindows_fast 1 }
	    -no_pack_main  { set no_pack_main 1 }
	    -nodb          { set use_dbuffer 0 }
	    -host          { incr i; set dlremote [lindex $argv $i] }
	    -lang          { incr i; set use_lang [lindex $argv $i] }
	    -tool          { incr i }
	    -licensing     { incr i }
	    -use           { incr i; set use [lindex $argv $i] }
            -use_embed     { incr i; set use_embed [lindex $argv $i] }
            -geometry      { incr i }
	    -rd            { }
	    -batch         { }
	    -graphics_type {
		if {[lindex $argv [incr i]] == "X11"} {
		    set use_xwindows 1
		}
	    }
	    -- { set to_scr 1 }
	    -help - -h {
		puts "Options:"
		foreach opt $tool_options {
		    if {[lindex $opt 2] == ""} {
			puts "\t[lindex $opt 0]"
		    } else {
			puts "\t[lindex $opt 0] value"
		    }
		}
		
		exit 0
	    }
	    -* {
		set found 0
		foreach opt $tool_options {
		    if {$arg == [lindex $opt 0]} {
			set var [lindex $opt 1]
			switch [lindex $opt 2] {
			    "" { set $var 1 }
			    list    { incr i; lappend $var [lindex $argv $i] }
			    default { incr i; set $var [lindex $argv $i] }
			}
			set found 1
			break
		    }
		}
		if !$found {
		    if [info exists unknown_options_are_tool_arguments] {
			lappend tool_arguments $arg
		    } else {
			puts stderr "Warning: ignored unknown option \"$arg\""
			puts stderr "Type \"CMD -help\" for a list of valid options"
		    }
		}
	    }
	    default { lappend tool_arguments $arg }
	}
    }
}

set guibase_files {
    bocofile
    checkbox
    choose_one
    cursors
    coloredit
    forms
    formutil
    fileselect
    histogram
    misc
    my-dialog
    my-tkerror
    process
    process_internal
    poll
    mainwindow
    display_sub
    query
    pathentry
    scontrol
    sizes
    iges
    questionbox
    help
    hardcopy
    exec_cmds
    bubble
    cursors
    show_logfile
    bltemu
    configfile
    wizard
    toplevel
    csystem
    command_coords
    toolbars
    commands
    foptionMenu
    bocofile
    busy
    readers
}


if {!([info exists ai_environment] && $ai_environment)} {
    load_fileset $guibase_dir "$guibase_files $guibase_files_extra" ""
    load_fileset $tool_dir    $tool_files ""
    if {$tool_files2 != ""} { load_fileset $tool_dir2   $tool_files2 "" }
    if {$tool_files3 != ""} { load_fileset $tool_dir3   $tool_files3 "" }

    if {$rebuild_digest || $compile_tcl} { exit 0 }

    if {[info commands tool_source_extra_files] != ""} {
	tool_source_extra_files
    }
}

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

if ![info exists mainwindow_menubar] {
    set mainwindow_menubar 0
    foreach i {ICEM ICEPAK AIRPAK ORCA TDM STARLT} {
	if {[info exists env(${i}_USE_MENUBAR)] && $env(${i}_USE_MENUBAR)} {
	    set mainwindow_menubar 1
	}
    }
}

set tcl_precision 14
set job_confirm 0
set bubble_delay 1000

if ![info exists host_vendor] { set host_vendor unknown }

if {(!$batch_mode) && (!([info exists ai_environment] && $ai_environment)) } {
    if $black_and_white {
	tk_setPalette white
	# tk colormodel . mono
    }
    
    set display_vendor [winfo server .]
    
    switch -glob -- $display_vendor {
	{*Silicon Graphics*}                { set display_type sgi }
	{*Hewlett-Packard *}                { set display_type hp }
	{*Sun Microsystems*}                { set display_type sun }
	{*International Business Machines*} { set display_type ibm }
	{*Digital Equipment Corporation*}   { set display_type dec }
	default                             { set display_type other }
    }
    
    # puts "Display vendor: $display_type -- $display_vendor"
    
    set screenw ""
    if [info exists env(ICEM_FONT_SIZE)] {
	set screenw $env(ICEM_FONT_SIZE)screen
    }
    compute_sizes $screenw
    source $guibase_dir/settings.tcl
    set default_text_font $normalfont
    set default_title_font $bigfont
    option add *font $default_text_font
}

set user_name [cmd_whoami]
set host_name [cmd_uname_n]

set process_ident ""

set language_table {
    { Japanese shiftjis { ja ja_JP JP Japanese } 1 }
    { English  ""       { C } 0 }
    { TEST     ""       { TEST } 0 }
}
#--- sep.08.2000 
# this may enable in future days...
#
#if ![info exists language_text_prefix] {
#    eval "set t \$${tool_id}_dir"
#    set language_text_prefix [file join $t lib locale ${tool_id}_${data_format}_]
#}
if [info exists language_text_file] { 
    set fp [open $language_text_file r]
    if {[info exists env(LANG)] && [string match *JP* $env(LANG)]} {
	fconfigure $fp -encoding shiftjis
    }
    eval [read $fp]
    close $fp
} elseif [info exists language_text_prefix] {
    set lang English
    if {$use_lang != ""} {
	set lang $use_lang
	foreach l $language_table {
	    if {[string tolower $lang] == [string tolower [lindex $l 0]]} {
		set language_text_encoding [lindex $l 1]
		set language_text_form_override [lindex $l 3]
		break
	    }
	}
    } elseif [info exists env(LANG)] {
	set more 1
	foreach l $language_table {
	    set suff [lindex $l 0]
	    foreach v [lindex $l 2] {
		set l1 [string tolower $v]
		if {[string match $l1* [string tolower $env(LANG)]]} {
		    if [file exists ${language_text_prefix}$suff.tcl] {
			set lang $suff
			set language_text_encoding [lindex $l 1]
			set language_text_form_override [lindex $l 3]
			set more 0
			break
		    }
		}
	    }
	    if !$more break
	}
    }
    set language_text_file ${language_text_prefix}$lang.tcl
    set fp [open $language_text_file r]
    if {$language_text_encoding != ""} {
	fconfigure $fp -encoding $language_text_encoding
    }
    eval [read $fp]
    close $fp
}

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

if ![info exist viewer_win_orient] {set viewer_win_orient v}

if {!([info exists ai_environment] && $ai_environment)} {
  if $batch_mode {
    if [do_batch_job $batch_type] {
	exit 0
    }
  } else {
    
    if [catch {
	top_setup
	if {[info command special_make_main_window] != ""} {
	    special_make_main_window
	} else {
	    make_main_window $viewer_win_orient
	}
	make_message_window
	make_tool_windows
    } res] {
	puts $res
	puts $errorInfo
	tk_dialog .init_error Error $errorInfo "" -1 OK
	exit 1
    }
    proc delete_window_protocol {} {
	set mess "Please use the Done or Quit commands to dismiss the form\
	or exit the program."
	tk_dialog .delete_window_protocol "Delete window" $mess "" 0 Okay
    }
    
    if !$toplevel(single) {
	top_withdraw .
    }
    adjust_window_geometry
    
    if [info exists tool_phases] {
	set current_phase [lindex [lindex $tool_phases 0] 1]
	if {$current_phase != ""} set_phase
    }
    
    if {$display_type == "sgi"} {
	# The window manager does something a bit strange.
	set topform_geo +0+[expr {[winfo rooty $tdv_default] + [winfo rooty .v]}]
    } else {
	set topform_geo +0+[winfo rooty $tdv_default]
    }
    if $is_win {
	set botform_geo -0-25
    } else {
	set botform_geo -0-0
    }
    if !$toplevel(single) {
	# Make sure that the message and edit windows and other toplevel ones
	# get iconified and deiconified together.
	bind .v <Unmap> { if {"%W" == ".v"} { withdraw_toplevels .v 0 } }
	bind .v <Map>   { if {"%W" == ".v"} { withdraw_toplevels .v 1 } }
    }
    
    if {($host_vendor == "sun") && ($display_type == "sun") && \
	    ($env(DISPLAY) != ":0") && ($graphics_type == "native")} {
	append initial_warning "Note: to gain better graphics\
		performance on the Sun, you should set your DISPLAY\
		variable to :0 rather than $env(DISPLAY). \
		This enables XGL to use DGA.\n"
    }
    
    if {[info command app_print_startup_message] != ""} {
	app_print_startup_message
    } else {
	mess "$whoami" {} {} 0
	if [info exists compile_date] { mess ", built $compile_date" {} {} 0 }
	mess "\n" {} {} 0
	mess "$copyright\n" {} {} 0
    }
    if [info exists extra_startup_message] {
	mess "$extra_startup_message\n" {} {} 0
    }
    if [info exists extra_startup_message2] {
	mess "$extra_startup_message2\n" {} {} 0
    }
    
    if [info exists initial_warning] {
	mess $initial_warning red {} 0
    }
    
    # Now start the process going, etc.
    
    if {[info commands app_help_setup] != ""} {
	app_help_setup
    } else { 
	   help_setup
    }
    
    if {$tcl_version >= 8.0} bubble_setup
    
    update
    
    if [catch {
	set cmd [tool_command]
	if {$cmd != ""} {
	    start_process $tool_id $tdv_default $cmd $tool_prompt
	}
	tool_setup
    } res] {
	tk_dialog .init_error Error $errorInfo "" -1 OK
	exit 1
    }
    
    foreach w [winfo children .] {
	if {[winfo exists $w] && ([winfo class $w] == "Toplevel")} {
           if {[wm protocol $w] != "WM_DELETE_WINDOW"} {
              wm protocol $w WM_DELETE_WINDOW delete_window_protocol
           }
	}
    }
 }
}



