#----------------------------------------------------------------------------
#
# PADT---------------------------------------------------- Phoenix Analysis &
#                                                         Design Technologies
#
#----------------------------------------------------------------------------
#
#       Package: AI-Environment GUI Management
#
#
#          File: init.tcl
#
#
#     Developer: Matt Sutton
#
#
#   Description: This file is responsible for initializing the entire MED,
#                HEXA, Visual3 and whatever else might be needed in AI*Env
#                The following iterpreters are used to manage the legacy
#                code issues.
#                1. The toplevel GUI Med interpreter is the master interpreter
#                2. The low level Med batch interpreter exists in ICEM 4.2
#                   and is used for compatiblity reasons.
#                3. A slave intepreter of Med named Hexa is created for
#                   managing the Hexa legacy code base.
#                4. A slave intepreter of Med named Vis3 is create for 
#                   managing the Visual3 legacy code base.
#           
#
#-----------------------------------------------------------------------------
# For support: 1-480-813-4884 ext. 125 -or- matt.sutton@padtinc.com
#-----------------------------------------------------------------------------

if [info exist env(AI_ENV_TCLLIB_DIR)] {
   lappend auto_path $env(AI_ENV_TCLLIB_DIR)
} else {
   lappend auto_path $env(ICEM_ACN)/lib/tcllib1.4
}

package require struct
if !$batch_mode {
    package require BWidget 1.4.0
}


set error_report(identifier) "$whoami $version"
set error_report(maintainer) wayne.christopher@ansys.com
set error_report(host) www-berkeley.ansys.com
set error_report(user) icemcfd_error_report

#-----------------------------------------------------------------------------
# TO DO: Remove for release for general code cleanliness.  It won't hurt
# anything unless the user has the environment variable ICEM_DEBUG set
# to one and the TclPro debugger listening for a remote debugging session.
# Relatively unlikely...
if { [info exists env(ICEM_DEBUG)] } {
    if { $env(ICEM_DEBUG) == 1 } {
	source "e:\\Program Files\\TclPro1.4\\win32-ix86\\bin\\prodebug.tcl"
	debugger_init
    }
}
if { [info exists env(ICEM_PROFILE_AI)] } {
    if { $env(ICEM_PROFILE_AI) == 1 } {
	global AIENVProfileData
	package require Tclx 8.3
	profile -commands -eval on
    }
}

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

# Hide the interpreter and tk windows.  This is done outside of a function
# so that it is the first thing sourced.
if !$batch_mode {
    script_interp eval wm withdraw .
    wm withdraw .
    update idletasks
    if [catch {WinLoadIcon ai_env}] {
	catch {WinLoadIcon icemcfd}
    }
}
catch { console hide }

# Disable the ICEM CFD one-window code
set toplevel(single) 0
if {$tcl_platform(platform) == "windows"} {
    set botform_geo -0-25
} else {
    set botform_geo -0-0
}

set use_select_toolbar 1
set form_all_transient 1
set socket_done 0

if {$tcl_platform(platform) == "unix"} {
    set_env ICEM_NO_MODAL_SPLASH 1
}

# Windows 64 with tcl 8.4.11 does not have math functions floor and ceil.

proc ceil {v} {
    if {$v == int($v)} {
	return [expr int($v)]
    } else {
	return [expr int($v + 1)]
    }
}

proc floor {v} {
    if {$v == int($v)} {
	return [expr int($v)]
    } else {
	return [expr int($v - 1)]
    }
}

#-----------------------------------------------------------------------------
#     A I * E N V I R O N M E N T / M E D    I N I T I A L I Z A T I O N
proc AIEnvMain {} {

    global InitializationTime
    global AppName Version version
    global env guibase_dir
    global is_win bindir
    global toplevel
    global batch_mode env file_name
    global argv argc script_file script_args
    global v3_script_file
    global use_xwindows black_and_white
    global icon_size1 icon_size2 displ_orient_set
    global tool_arguments aie_guiOpt
    global AIEnvProduct BccProduct AIEnvDir
    global prog_guide_files
    global use_xwindows_set
    global socket_done
    global CurBuildProgressValue
    global license_is_academic tdv_current_viewer
    global tool_dir2 gui_style_mode tdv_show_ansys_logo

    # for old hexa replay compats
    global _tempx _tempy _tempz
    global _temp2x _temp2y _temp2z

    global ansys_license_exists

    # we need to parse these args like -x before calling
    # any routines that might need what is set by them.
    set to_scr 0
    set script_file ""
    set script_args ""
    set v3_script_file ""
    set tool_arguments ""
    set black_and_white 0
    set use_xwindows 0
    set use_xwindows_set 0
    set icon_size1 "24"
    set icon_size2 "35"
    set displ_orient_set 0
    set do_bcc 0
    set exit_after 0
    set BccProduct ""

    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; set use_xwindows_set 1}
                -gdi           { set use_xwindows 1; set use_xwindows_set 1 }
                -batch         { }
                -use           { incr i }
                -wb            { 
                    global use_workbench use_embed
                    set use_workbench 1
                    set use_embed 1
                    set_env AI_ENV_IN_WB 1
                }
                -wb1 {
                    set_env AI_ENV_IN_WB1 1
                }
                -wb2 {
                    set_env AI_ENV_IN_WB2 1
                }
                -comPort { 
                    global wb_comPort
                    incr i; 
                    set wb_comPort [lindex $argv $i]
                }
                -tcomPort { 
                    global wb_tcomPort
                    incr i; 
                    set wb_tcomPort [lindex $argv $i]
                }
                -comPath {
                    global wb_comPath
                    incr i
                    set wb_comPath [lindex $argv $i]
                    source $wb_comPath
                }
                -wb_brep_load { 
                    global wb_brepLoad
                    incr i; 
                    set wb_brepLoad [lindex $argv $i]
                }
                -wb_dsmesh_load { 
                    global wb_dsMeshFile
                    incr i; 
                    set wb_dsMeshFile [lindex $argv $i]
                }
                -wb_cur_dir { 
                    global wb_curdir
                    incr i;
                    set wb_curdir [lindex $argv $i]
                    if [catch {cd $wb_curdir}] {
                        set wb_curdir ""
                    }
                }
                -wb_command { 
                    global wb_command
                    incr i;
                    lappend wb_command [lindex $argv $i]
                }
                -wb_init_proj_name { 
                    global wb_initProjName
                    incr i; 
                    set wb_initProjName [lindex $argv $i]
                }
                -wb_backup { 
                    global wb_backup
                    incr i; 
                    set wb_backup [lindex $argv $i]
                }
                -wb_skip_loading { 
                    global wb_skip_loading
                    set wb_skip_loading 1
                }
                -wb_load { 
                    incr i; 
                    set load_file [lindex $argv $i]
                    if {![info exists tool_arguments] || $tool_arguments == ""} {
                        lappend tool_arguments $load_file
                    } else {
                        linsert tool_arguments 0 $load_file
                    }
                }
                -wb_primary_file { 
                    global wb_primary_file
                    incr i; 
                    set wb_primary_file [lindex $argv $i]
                }
                -wb_lin2quad {
                    if [info exists env(AI_ENV_IN_WB1)] {
                        global wb1_options
                        set wb1_options(lin2quad) 1
                    }
                }
                -wb_subset2parts {
                    if [info exists env(AI_ENV_IN_WB1)] {
                        global wb1_options
                        set wb1_options(subset2parts) 1
                    }
                }
                -wb_updatebunching {
                    if [info exists env(AI_ENV_IN_WB1)] {
                        global wb1_options
                        set wb1_options(updatebunching) 1
                    }
                }
                -script {
                    incr i
                    set script_file [lindex $argv $i]
                }
                -v3_script {
                    incr i
                    set v3_script_file [lindex $argv $i]
                }
                -app {
                    incr i
                    set a [file split [lindex $argv $i]]
                    set AIEnvProduct [lindex $a end]
                    if {[llength $a] > 1} {
                        global AIEnvProductDirectory
                        set AIEnvProductDirectory [eval file join $a]
                    }
                }
                -4 {}
                -socket_done {
                    incr i
                    set socket_done [lindex $argv $i]
                }
                -bcc {
                    set do_bcc 1
                    set exit_after 1
                    incr i
                    set BccProduct [lindex $argv $i]
                }
                -- { set to_scr 1 }
                -* {
                    puts stderr "Warning: ignored unknown option \"$arg\""
                }
                default { lappend tool_arguments $arg }
            }
        }
    }

# set Ansys licensing features existence
    array set ansys_license_exists {
	    aa_r_me 0
	    aa_a_cfd 0
	    aa_a 0
	    aa_r 0 	
	    aa_r_cfd 0
	    aa_t_i 0 	
	    aa_t_a 0 	
	    aa_t_me 0 
	    aa_t_cfd 0 
	    aa_mesh 0	
	    aa_r_ad 0 
	    aienv 0
	    aiglobal 0
	    aihexa 0
	    aimed 0
	    aiprism 0
	    aiquad 0
	    aitetra 0
	    aivis3 0
	    aibfcart 0
	    aiaddon 0
	    aioutcfd 0
	    aiedgeom 0
	    aicart3d 0
	    aihexct5e 0	
        amesh_extended 0
	    amesh 0
	    acfd 0
        acfd_preppost 0
        acfd_fluent 0
        acfd_cfx 0
        acfd_flo 0
        acfd_polyflow 0
    }
    
    if ![info exists env(AWP_ROOT)] {
       set_env AWP_ROOT $env(ICEM_ACN)/../..
    }
    
    CheckAnsysLILicensing
    
    # Setup Product Flavor based on Licensing if needed (replace call to test_licensing)
    if {([info exist env(AI_ENV_TEST_LICENSING)] && ($env(AI_ENV_TEST_LICENSING) == 1)) || [info exist env(USE_ANSYS_ACADEMIC_LICENSING)]} {
       InitializeProductFlavor
    }
    
    if {[info exists env(AI_ENV_ANSYS_SOLVERS)] && ![info exist env(USE_ANSYS_ACADEMIC_LICENSING)]} {
        set AppName "ICEM CFD"
        set Version "$version - (ANSYS Solvers)"
        set_env AI_ENV_CFD 1
        set aie_guiOpt(splashImage) splash.gif
    } else {
        set AppName "ICEM CFD"
        set Version "$version"
    }

    if {$BccProduct != ""} { set AIEnvProduct "" }
    
    set InitializationTime [clock seconds]
    
    DeterminePlatform
        
    # set any special distribution options

    if ![info exist env(AI_ENV_PRODUCT)] {
        set_env AI_ENV_PRODUCT fea2.0
    }
    if {![info exist AIEnvProduct] || $AIEnvProduct == ""} {
       set AIEnvProduct $env(AI_ENV_PRODUCT)
    }

	if [info exists AIEnvProductDirectory] {
		if ![file exists [file join $AIEnvProductDirectory scripts init.tcl]] {
			unset AIEnvProductDirectory
		}
	}  

    SetupMedSourceFileDirectories
    
    # Setup Med
    InitializeMed

    # Setup Mesh Environment based on Lisensing
    InitializeLicenseEnvironments
    
    # Setup Post-processing
    InitializeVisual3p

    # Setup Help
    chmhlp_intialize

    if $do_bcc {
	    if {$BccProduct != ""} {
	        bcc_do_solver $BccProduct
	    } else {
	        bcc_do_solver $AIEnvProduct
	    }
    }
    
    if $exit_after { exit 0 }
    
    if [info exist AIEnvProductDirectory] {
		set s [file join $AIEnvProductDirectory scripts init.tcl]
	} else {
        set s [file join $AIEnvDir scripts $AIEnvProduct init.tcl]
	}
	if [file exist $s] {
	    uplevel \#0 source \"$s\"
	} 
	
	set current_bg [tdv_logo_background]
	
    global use_workbench common_tool_dir 
    set common_tool_dir "$env(ICEM_ACN)/../../commonfiles/images" 
    
    if [info exist use_workbench] {
        set aie_guiOpt(treeGeom) top
        set aie_guiOpt(gradBackground) 1
        set aie_guiOpt(bindingStyle) wb
        if $current_bg {
            set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_large_black.ppm]
        } else {
            set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_large_white.ppm]
        }
    }

    if {[info exist env(AI_ENV_ACADEMIC_NEW)] && ![info exist env(AI_ENV_NO_WATERMARK)]} {
        if $current_bg {
            set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_academic_large_black.ppm]
        } else {
            set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_academic_large_white.ppm]
        }
	    set_env ICEM_ACADEMIC 1
    }

    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 }
	    }
	    ::profiler::init
    }

    # set the default value for GUI options

    if [info exist aie_guiOpt(bindingStyle)] {
       if {$aie_guiOpt(bindingStyle) == "wb" } {
          set aie_guiOpt(wbStyleCircle) 0
          set aie_guiOpt(wbStyleAxes) 1
       }
    }

    if {$gui_style_mode == "wb"} {
        set grad_backg 1
        set tree_geom top
    } else {
        set grad_backg 0
        set tree_geom bot
    }

    if ![info exist env(ICEM_ACADEMIC)] {
        if {$tdv_show_ansys_logo && $gui_style_mode == "wb"} {
            if $current_bg {
                set logo_image [file join $tool_dir2 ANSYS_large_black.ppm]
            } else {
                set logo_image [file join $tool_dir2 ANSYS_large_white.ppm]
            }
        } else {
            set logo_image ""
        }
    } else {
        if $current_bg {
            set logo_image [file join $tool_dir2 ANSYS_academic_large_black.ppm]
        } else {
            set logo_image [file join $tool_dir2 ANSYS_academic_large_white.ppm]
        }
    }

    foreach {n v} [list iconZoneStyle  default \
                        withMedModel   1 \
                        withMedGWin    1 \
                        treeGeom       $tree_geom \
                        winTitle       $AppName \
                        version        $Version \
                        v3ExitCmd      v3_exit \
                        initAfterCmd   "" \
                        initLicense    1 \
                        logoImage      $logo_image \
                        logoPos        "" \
                        gradBackground $grad_backg \
                        wbStyleCircle  0 \
                        wbStyleAxes    1 \
                        splashImage    splash.gif \
                        delaySplash    0 \
                        topTTKRF       aie.ttkrf] {
        if ![info exist aie_guiOpt($n)] {
           set N [string toupper $n] 
           if [info exist env(AI_ENV_OPT_$N)] {
              set aie_guiOpt($n) $env(AI_ENV_OPT_$N)
           } else {
              set aie_guiOpt($n) $v
           }
        }
    }
     
    set AppName $aie_guiOpt(winTitle)
    set Version $aie_guiOpt(version)
    
    set CurBuildProgressValue 0
    if {!$batch_mode && ![info exist use_workbench]} {
        DoSplash
        HideBuildProgress
    }

    # Finally, build the GUI
    
    set reset_show_ansys_logo $tdv_show_ansys_logo
    set tdv_show_ansys_logo 0
    
    if !$batch_mode {
        # strange bug on windows 64 machines, missing icemcfd title bar icon
        if {$::tcl_platform(platform) == "windows" && [info exists env(ProgramFiles(x86))]} {
            set_env AI_ENV_PLATFORM_WIN64 1
            if [file exists $env(ICEM_ACN)/icemcfd.ico] {
                wm iconbitmap . -default $env(ICEM_ACN)/icemcfd.ico
            }
        }
        InitializeAIEnvGUI
        # Init the help system
        if $aie_guiOpt(withMedModel) {
            InitializeMedGraphics
        }
        SetupHelp
    }
    SetupBatchGlue

    # This sets the files for writing the programmer's guide
    set prog_guide_files {forms exec_cmds geometry_funcs geom_vid_funcs translation_funcs display_funcs \
        boco_funcs cart_funcs file_funcs hex_funcs meshdirect_funcs meshing_funcs \
        misc_funcs output_funcs regression_funcs reports_funcs rmi_funcs struct_funcs \
        unstruct_funcs utility_funcs wb_funcs}

    # Enable the toggle to show/no show dot files in the open and save file dialogs for unix
    namespace eval ::tk::dialog {}
    namespace eval ::tk::dialog::file {}
    set ::tk::dialog::file::showHiddenBtn 1
    set ::tk::dialog::file::showHiddenVar 0

    # Load up the stuff we need for table and graph editing.  On UNIX
    # it's compiled in (maybe windows also for blt)
    if {$is_win && !$batch_mode} {
	    if [file exists $bindir/Tktable.dll] {
	        load $bindir/Tktable.dll
	    }
	    if {([info command blt::graph] == "") && [file exists $bindir/BLT24.dll]} {
	        catch {load $bindir/BLT24.dll}
	    }
    }
    if {!$batch_mode} {
	    # Disable this because for some reason it hangs windows
	    bind all <Key-F10> ""
	    if [file exists $env(ICEM_ACN)/lib/Tktable2.7] {
	        uplevel \#0 source \"$env(ICEM_ACN)/lib/Tktable2.7/tkTable.tcl\"
	    }
    }
    if { [info exists env(ICEM_PROFILE_AI)] } {
	    if { $env(ICEM_PROFILE_AI) == 1 } {
	        profile off AIENVProfileData
	        profrep AIENVProfileData real "F:/AI-Environment/ProfileData/Data${InitializationTime}.dat"
	    }
    }

    # Set the license manager up now
    if {$aie_guiOpt(initLicense)} {
        InitializeLicense
        if {[info exists AIEnvProduct] && $AIEnvProduct != ""} {
	        set pname load[string toupper $AIEnvProduct]
		    if {[info command $pname] == $pname} $pname
        }
    }

    set tdv_show_ansys_logo $reset_show_ansys_logo
    if {[info exists license_is_academic] && $license_is_academic == "1"} {
        set_env ICEM_ACADEMIC 1
    }
    if $current_bg {
        if ![info exist env(ICEM_ACADEMIC)] {
            set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_large_black.ppm]
        } else {
            set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_academic_large_black.ppm]
        }
    } else {
        if ![info exist env(ICEM_ACADEMIC)] {
           set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_large_white.ppm]
        } else {
           set aie_guiOpt(logoImage) [file join $tool_dir2 ANSYS_academic_large_white.ppm]
        }
    }
    if {($tdv_show_ansys_logo || [info exist env(ICEM_ACADEMIC)]) && !$batch_mode} {
        tdv_logo $tdv_current_viewer $aie_guiOpt(logoImage) $aie_guiOpt(logoPos)
    }
    
    # This makes ssish work without a license
    set_env CFD_IGES_ONLY 1
    
    aie_open_journal_file unnamed
    
    # Makes life easier for geometry-creating scripts, etc
    if {!$batch_mode && $aie_guiOpt(withMedModel)} {
	    catch { ic_empty_tetin }
    }
    if !$batch_mode {
	    # Make sure aie_meshTypeVis has reasonable values
	    aie_initial_unsmesh_visibility 0
    }

    if {$script_file != ""} {
	    if $batch_mode {
	        source $script_file
	        exit 0
	    } else {
	        script_interp eval "source {$script_file}"
	    }
    } elseif {[llength $tool_arguments]} {
	    foreach f $tool_arguments { aie_openFile $f }
    }
    if {!$batch_mode} {
        aie_update_icons
        # Avoid delays later by creating the selection toolbars now 
        catch {
            foreach binding "1 1-2 2 3 4 5 6 7 8-2 8-3 8-4 9 10" {
                select_set_bindings $binding 0 0 0 ""
                select_unset_bindings 0
                aie_unset_all_selection_modes
            }
        }
    }
    if {[info command [lindex $aie_guiOpt(initAfterCmd) 0]] != ""} {
        eval $aie_guiOpt(initAfterCmd)
    }

    # For remote process users of med, set an initialized flag
    set_initialized
    # fix for sgi	
    if ![info exists env(HOME)] {
        set h [home_directory]
        puts "env(HOME) set to $h"
    }
    if [aie_wb2_is_running] {
        if $batch_mode {
            set ret 0
            aie_wb2_init_files
            if [info exists wb_command] {
                set ret [aie_wb2_execute_batch_command $wb_command]
            }
            exit $ret
        } else {
            # avoid socket network connection timeout in case of a long project loading time
            after 3000 {
                aie_wb2_init_files 
            }  
            if [info exists wb_comPort] {
                ic_socket_start_icemcfd_server $wb_comPort workbench
            }
        }
    } else {
         global license_not_valid
         if {!$batch_mode && [info exists license_not_valid]} {
            InitLicenseReset
        }
    }
}

proc eval_when_initialized {cmd} {
    global initialized_flag initialized_cmds
    if [info exists initialized_flag] {
        eval $cmd
    } else {
        lappend initialized_cmds $cmd
    }
}

proc set_initialized {} {
    global initialized_flag initialized_cmds
    set initialized_flag 1
    if [info exists initialized_cmds] {
        foreach cmd $initialized_cmds {
            eval $cmd
        }
    }
} 

proc SetupHelp {} {
    global AIEnvHelpRootDir
    global env
    global help_base help_main_topic
    global batch_mode
    
    if {!$batch_mode} {
        bind all <Key-F1> help_book
    }
    return
}

proc help_window_override {x y} { help_book }

proc InitializeLicense {} {
    global env license_not_valid toolBarInfo batch_mode
    
    CheckEnvVar ICEM_ACN

    # Check to see if the user has the license somewhere other than the default location  
    if {[info exists env(ICEM_LICENSE_FILE)] } {
	    set license $env(ICEM_LICENSE_FILE)
    } elseif { [info exists env(LM_LICENSE_FILE)] } {
	    set license $env(LM_LICENSE_FILE)
    } else {
	    # Set the license to point to the default location
	    set license [file join $env(ICEM_ACN) lic license.dat]
    }
    
    # ICEMCFD Licensing is no longer supported
    if {[info exists env(ICEM_LICENSING_FLAGS)] } {
	    set license_flag $env(ICEM_LICENSING_FLAGS)
	    if { $license_flag == "icem" } {
	        InitError "The ICEM CFD Licensing is no longer supported.\nPlease contact your Tech. Support to upgrade to ANSYS Licensing."
	    }
    }

    # Grab the license
    set license_flags ""
    if { [catch {enable_licenses $license $license_flags} status] } {
        set license_not_valid 1
        InitWarning $status
    } else {
        if [info exists license_not_valid] {
            unset license_not_valid
        }
    }
 }

proc CheckEnvVar { EnvVar } {
    global env
    # Find the license file
    if { ![info exists env($EnvVar)] } {
        InitError "The environment variable: \"$EnvVar\" does not exist."
    }
}

proc DeterminePlatform {} {
    global is_win env tcl_platform
    
    if {[info exists tcl_platform(platform)]} {
        if {"$tcl_platform(platform)" == "windows"} {
            set is_win 1
            set_env AI_ENV_IN_WIN 1
        } elseif {[info exists tcl_platform(os)] && $tcl_platform(os) == "Linux"} {
            set is_win 0
            set_env AI_ENV_IN_LINUX 1
        } else {
            set is_win 0
        }
    } else {
        set is_win [expr ![file exists /etc/passwd]]
    }
}

# Dispatch the initialization of med out to a series of subroutines
proc InitializeMed {} {
    global batch_mode
    
    SetupMedBatchInterp 
    
    if !$batch_mode {
	    SourceAIEnvFiles
    }
    
    SourceMedGUIFiles
    SourceUserScripts
    
    if !$batch_mode {
	    InitializeBWidgets
	    InitializeMedFonts
    }
        InitializeMedGlobals
        InitializeGlobalHotKeys
    
    proc geom_get_objects {type how {only_if_dormant 0}} {
	if !$only_if_dormant {
	    return [batch_interp eval geom_get_objects \"$type\" \"$how\"]
	} else {
	    return [batch_interp eval geom_get_objects \"$type\" \"$how\" 0 1]
	}
    }
    batch_interp alias select_families select_families
    
    # One remaining problem is that the ic_param_* calls do not get written to the
    # replay file.  This is a temporary work-a-round (they should be moved to the batch
    # interp)
    # **** not done any more *** replay_patch_gui_calls ic_param_*
}

proc InitializeVisual3p {} {
   global v3p_setup_error

   if ![interp exists v3_batch_interp] { return "" }

   set v3p_setup_error [setup_pvm_env]
  
   if {$v3p_setup_error != ""} { return "" }

   setup_v3p_first_misc
}

# ------------------------------------------------------------------------
# Note: Hot keys moved to scripts/aie_hotkeys.tcl
# ------------------------------------------------------------------------

proc SetupMedBatchInterp {} {
    global tool_dir
    global batch_dir
    global AIEnvDir
    global env
    # Needed to initialize batch
    global tdv_default
    global tdv_library
    global is_win
    
    # Set here to set up aliases; changed in InitMedGraphics
    set tdv_default .v.view
    
    set tdv_library $env(MED_ROOT)/lib/med/tdv
    if ![file exists $tdv_library] {
	    set tdv_library $env(MED_ROOT)/lib/tdv
    }
    if ![file exists $tdv_library] {
	    set tdv_library $env(MED_ROOT)/../tdv/lib
    }
    set vpost_library $env(MED_ROOT)/lib/med/vpost
    if ![file exists $vpost_library] {
	    set vpost_library $env(MED_ROOT)/lib/vpost
    }
    if ![file exists $vpost_library] {
	    set vpost_library $env(MED_ROOT)/../vpost/lib
    }
    
    # Replay_med.tcl contains the code to deal with batch interpreter
    source [file join $tool_dir replay_med.tcl]
    
    setup_batch_interp
    
    lappend BatchFileList [file join $batch_dir med_batch.tcl]
    lappend BatchFileList [file join $batch_dir unstruct_funcs.tcl]
    lappend BatchFileList [file join $AIEnvDir med globals.tcl]
    lappend BatchFileList [file join $tool_dir options_med.tcl]

    foreach BatchFile $BatchFileList {
        b source "$BatchFile"
    }
}

proc InitializeMedFonts {} {
    global bigfont boldfont
    # compute_sizes "" 0
    # override this one
    set bigfont [font create -family "Arial" -size 10]
    set boldfont $bigfont
}

proc SetupMedSourceFileDirectories {} {
    global env
    global tool_dir
    global tool_dir2
    global batch_dir
    global guibase_dir
    global source_dirs
    global bindir
    global is_win
    
    set tool_dir2 $env(MED_ROOT)/lib/med/tdv
    if ![file exists $tool_dir2] {
	    set tool_dir2 $env(MED_ROOT)/lib/tdv
    }
    if ![file exists $tool_dir2] {
	    set tool_dir2 $env(MED_ROOT)/../tdv/lib
    }
    set guibase_dir $env(MED_ROOT)/lib/med/guibase
    if ![file exists $guibase_dir] {
	    set guibase_dir $env(MED_ROOT)/lib/guibase
    }
    if ![file exists $guibase_dir] {
	    set guibase_dir $env(MED_ROOT)/../guibase
    }
    
    global vpost_library vpost_batch_library
    set vpost_batch_library $env(MED_ROOT)/lib/vpost_batch
    if ![file exists $vpost_batch_library] {
        set vpost_batch_library $env(MED_ROOT)/../vpost/lib_batch
    }
    if {![file exists $vpost_batch_library] && [file exists $env(ICEM_ACN)/lib/vpost_batch]} {
        regsub -all {\\} $env(ICEM_ACN) {/} env(ICEM_ACN)
        set vpost_batch_library $env(ICEM_ACN)/lib/vpost_batch
    }
    set vpost_library $vpost_batch_library

    global v3_gui_dir v3_batch_dir v3_readers_dir visual3p_root v3_tool_dir
    
    if {![info exist env(VISUAL3P_ROOT)] || ![file exists $env(VISUAL3P_ROOT)]} {
        set_env VISUAL3P_ROOT $env(MED_ROOT)
        set visual3p_root $env(VISUAL3P_ROOT)
    } elseif ![info exist visual3p_root] {
        set visual3p_root $env(VISUAL3P_ROOT)
    }
    set visual3p_root $env(VISUAL3P_ROOT)
    if [file exists $env(MED_ROOT)/../visual3p] {
        set visual3p_root $env(MED_ROOT)/../visual3p
    } elseif [file exists $env(ICEM_ACN)/lib/visual3p] {
        regsub -all {\\} $env(ICEM_ACN) {/} env(ICEM_ACN)
        set visual3p_root $env(ICEM_ACN)
    }
    set v3_gui_dir $visual3p_root/lib/v3p_gui
    set v3_batch_dir $visual3p_root/lib/v3p_batch
    set v3_tool_dir $v3_gui_dir

    foreach d [list $v3_gui_dir/formats $visual3p_root/icemcfd/result-interfaces backends] {
        if [file exists $d] {
           set pat $d/*_format_aie.ttkrf
           set rr ""
           if $is_win {
              set rr [glob -nocomplain $pat]
           } else {
              if ![catch {exec /bin/ls -a $d} files] {
                 foreach f $files {
                    if [string match *_format_aie.ttkrf $f] {lappend rr $d/$f}
                 }
              } else {
                 set rr [glob -nocomplain $pat]
              }
           }
           if {$rr != ""} {
              set v3_readers_dir $d
              break
           }
        }
    }
    if {![info exist v3_readers_dir] || ![file exists $v3_readers_dir]} {
       set d $visual3p_root/icemcfd/result-interfaces
       if [file exists $d] { set v3_readers_dir $d }
    }
    set tool_dir $env(MED_ROOT)/lib/med_gui
    set batch_dir $env(MED_ROOT)/lib/med_batch
    
    set bindir $env(ICEM_ACN)/bin
    
    lappend source_dirs $batch_dir $guibase_dir $tool_dir2
    SetupAIEnvSourceFileDirectories
}

proc SetupAIEnvSourceFileDirectories {} {
    global env
    global AIEnvDir
    global TechTKDir
    global AIEnvScriptsDirs
    global AIEnvResourceDir
    global is_win
    global source_dirs
    global icon_path
    global AIEnvProduct
    global AIEnvProductDirectory
    
    if {[UseDevelopmentPaths]} {
	    set AIEnvDir [file join $env(MED_ROOT) .. ai_env]
    } else {
	    set AIEnvDir [file join $env(MED_ROOT) lib ai_env]
    }        
    set TechTKDir [file join $AIEnvDir techTK]
    set AIEnvScriptsDirs [list [file join $AIEnvDir scripts]]
    if [info exists AIEnvProductDirectory] {
		lappend AIEnvScriptsDirs [file join $AIEnvProductDirectory scripts]
	} else {
	    lappend AIEnvScriptsDirs [file join $AIEnvDir scripts $AIEnvProduct]
    }
    
    set AIEnvResourceDir [file join $AIEnvDir resource]
    
    set icon_path [list $AIEnvDir/icons $env(MED_ROOT)/lib/icons]
    
    lappend source_dirs $TechTKDir
    eval lappend source_dirs $AIEnvScriptsDirs
    lappend source_dirs [file join $env(MED_ROOT) lib med_gui]
}

proc UseDevelopmentPaths {} {
    # Try and replace the following if statement with its logical equivalent
    # which is independent of the path separator
    #
    # if {$is_win && ($env(MED_ROOT) != $env(ICEM_ACN))}
    # 
    
    global is_win
    global env
    
    if [info exists env(ICEM_DEVELOPMENT_PATHS)] { return 1 }
    
    # First Case
    if { $is_win == 0 } {
	    return 0
    }
    # Here down, is_win = 1
    regsub -all {\\} $env(MED_ROOT) {/} env(MED_ROOT)
    regsub -all {\\} $env(ICEM_ACN) {/} env(ICEM_ACN)
    
    # Compare the paths using spaces instead
    if { $env(MED_ROOT) != $env(ICEM_ACN) } {
	    return 1
    } 
    return 0
}

proc SourceMedGUIFiles {} {
    # tool_dir  is ../lib/med_gui
    # tool_dir2 is ../lib/tdv
    # batch_dir is ../lib/med_gui/med_batch
    # guibase_dir is ../lib/guibase
    
    global tool_dir
    global tool_dir2
    global batch_dir
    global guibase_dir
    global AIEnvDir
    global tcl_version
    global mess_numred
    global MasterFileList
    global auto_path argc argv ai_environment 
    global use_xwindows
    global icon_size1 icon_size2 displ_orient_set
    global env
    global source_dirs
    global vpost_library
    global vpost_batch_library
    global has_blt
    
    set has_blt 0
    
    set source_dirs [list $guibase_dir $tool_dir $tool_dir2 $AIEnvDir/med \
			 $AIEnvDir/icem_application_glue $AIEnvDir/scripts \
			 $AIEnvDir/techTK $batch_dir]
    
    set auto_path ""
    
    foreach file {
	    bocofile boco_solver family_files colormap cursors exec_cmds
	    choose_one dialog interrupt game flexlist family_boco makedoc
	    query replay select_geom select_sub run_application csystem
	    process batch_glue questionbox help toplevel workspace
	    display_sub misc histogram curve forms formutil pathentry fileselect
	    foptionMenu sizes s-table bubble coloredit poll bltemu
	    checkbox busy my-dialog fileselect bltemu readers my-tkerror
	    url_io
    } {
	    lappend GUIInterpFileList [file join $guibase_dir $file.tcl]
    }
    
    #--------------------------------------------------------------------
    
    lappend GUIInterpFileList [file join $tool_dir2 viewer.tcl]
    lappend GUIInterpFileList [file join $tool_dir2 wb_binding.tcl]
    
    foreach file {
        anno_mg anno anno_misc anno3d oned_windows_m oned_windows_vp
	    oned_windows_cmd_v3 vpost_plot vframes dfile_misc utf_misc beamcross
    } {
	   lappend GUIInterpFileList [file join $vpost_batch_library $file.tcl]
    }

    #--------------------------------------------------------------------
    
    foreach file {
	    file_med select_med select_struct select_unstruct geometry_med
	    geodisp_med view_med unsdisp_med med_ezcad disp_med options_med
	    unstruct_med geomodify_med diag_med import_med cad_trans_med
	    hardcopy_med start_v3p disp_hexa select_hexa mesh_hexa meshc_hexa strdisp_med
	    struct_med solution_med prism sparams domselect convex_hull cartfile_med ddn_med
    } {
	    lappend GUIInterpFileList [file join $tool_dir $file.tcl]
    }
    
    if [info exists env(AI_ENV_CFX)] {
	    lappend GUIInterpFileList [file join $tool_dir solution_med.tcl]
	    lappend GUIInterpFileList [file join $tool_dir prism.tcl]
    }
    
    #--------------------------------------------------------------------
    
    lappend GUIInterpFileList [file join $AIEnvDir med globals.tcl]
    
    #--------------------------------------------------------------------
    
    lappend GUIInterpFileList [file join $AIEnvDir icem_application_glue graphics_management.tcl]
    
    #--------------------------------------------------------------------
    
    foreach Script $GUIInterpFileList {
	    if [catch {uplevel \#0 source \"$Script\"} msg] {
	        puts "Warning failed to source file: $Script..."
	    } else {
	        lappend MasterFileList $Script
	    }
    }
}

proc SourceAIEnvFiles {} {
    global TechTKDir
    global MasterFileList
    #set TechTKScripts [glob -directory $TechTKDir -nocomplain *.tcl]
    lappend TechTKScripts [file join $TechTKDir gui_manager.tcl]
    lappend TechTKScripts [file join $TechTKDir builder.tcl]
    lappend TechTKScripts [file join $TechTKDir dez_environment.tcl]
    lappend TechTKScripts [file join $TechTKDir dropdown_button.tcl]
    lappend TechTKScripts [file join $TechTKDir icon_builder.tcl]
    lappend TechTKScripts [file join $TechTKDir layout.tcl]
    lappend TechTKScripts [file join $TechTKDir layout_manager.tcl]
    lappend TechTKScripts [file join $TechTKDir menu_builder.tcl]
    lappend TechTKScripts [file join $TechTKDir object_management.tcl]
    lappend TechTKScripts [file join $TechTKDir parser.tcl]
    lappend TechTKScripts [file join $TechTKDir refresher.tcl]
    lappend TechTKScripts [file join $TechTKDir selection_logic.tcl]
    lappend TechTKScripts [file join $TechTKDir text_editor.tcl]
    lappend TechTKScripts [file join $TechTKDir wizard_builder.tcl]
    lappend TechTKScripts [file join $TechTKDir wizard_environment.tcl]
    lappend TechTKScripts [file join $TechTKDir entity_mover.tcl]
    lappend TechTKScripts [file join $TechTKDir multi_select.tcl]
    lappend TechTKScripts [file join $TechTKDir exclusive_group.tcl]
    lappend TechTKScripts [file join $TechTKDir tokenizer.tcl]
    lappend TechTKScripts [file join $TechTKDir cache.tcl]
    lappend TechTKScripts [file join $TechTKDir column_select.tcl]
    
    foreach Script $TechTKScripts {
        source $Script
        lappend MasterFileList $Script
    }
}

proc InitializeAIEnvGUI {} {
    global AIEnvDir AppName Version aie_guiOpt env
    
    set ResourceFile [file join $AIEnvDir resource $aie_guiOpt(topTTKRF)]
    set DoBuild 0
    
    if { [file exists $ResourceFile] } {
        set DoBuild 1
    } else {
	    set Response [tk_messageBox -type okcancel -title "$AppName $Version Initialization Error" \
			-message "The default resource file: \"$ResourceFile\" does not exist. \
			Press OK to select a particular resource file or Cancel to Abort $AppName $Version" \
			-icon warning]
	    if { $Response == "ok" } {
	        set ResourceFile [tk_getOpenFile -defaultextension .ttkrf -initialdir [file join $AIEnvDir resource] \
				  -title "Open Resource File" -filetypes {{{Tech TK Resource Files} {.ttkrf}}}]
	        if { $ResourceFile == "" } {
		        exit
	        } else {
		        set DoBuild 1
	        }
	    } else {
	        exit
	    }
    }
    if { $DoBuild == 1 } {
	    ::AIEnv::GUIManagement::InNamespaceBuildAIEnv $ResourceFile
    }
}


# This is a kludge. An unknown bug exists in the bwidgets that I think has to
# do with initialization.  The bug causes the interpreter to simply exit with
# no warning/error/stack trace/anything.  However, if you create every widget
# within the BWidget family but do no pack/grid them things get initialized
# as needed.
proc InitializeBWidgets {} {

    set BWidgetList {
	Label
	Entry
	Button
	ArrowButton
	ProgressBar
	ScrollView
	Separator
	MainFrame
	LabelFrame
	TitleFrame
	ScrolledWindow
	ScrollableFrame
	PanedWindow
	ButtonBox
	PagesManager
	NoteBook
	LabelEntry 
	ComboBox 
	SpinBox 
	Tree 
	ListBox
	radiobutton
    }
    
    # Create a representative  bwidget so that the library is initialized. 
    # Why we have to do this I do not know and it worries me.
    set WindowIndex 0
    catch {
        foreach Widget $BWidgetList {
            set win [$Widget .wFooBW${WindowIndex}]
            incr WindowIndex
        }
    }
}

proc SourceUserScripts {} {
    global AIEnvScriptsDirs MasterFileList
    
    foreach Directory $AIEnvScriptsDirs {
        foreach Script [FindUserScripts $Directory] {
            source $Script
            lappend MasterFileList $Script
        }
    }
}

proc ss {} {
    global InitializationTime
    global MasterFileList
    set ThisScript [file join [pwd] [info script]]
    set SourcedFiles 0
    foreach Script $MasterFileList {
	if { [file mtime $Script] > $InitializationTime } {
	    mess "Sourcing script: $Script\n" blue
	    source $Script
	    set SourcedFiles 1
	}
    }
    if { $SourcedFiles == 1 } {
	    set InitializationTime [clock seconds]
    } else {
	    mess "No files sourced.\n" red
    }
}

# Non-recursively find all of the files in the 
# directory Dir, but exclude any called init.tcl because those
# are special and will already have been sourced

proc FindUserScripts {Dir} {
    set ret ""
    foreach Script [glob -directory $Dir -nocomplain *.tcl] {
	    if {[file tail $Script] == "init.tcl"} continue
	    lappend ret $Script
    }
    return $ret
}


proc InitError {Reason} {
    global AppName Version
    global batch_mode
    
    if {![info exists batch_mode] || (!$batch_mode)} {
	    tk_messageBox -title "$AppName $Version Initialization Error" -type ok -message $Reason
    } else {
	    puts "\n$AppName $Version Initialization Error:\n\t$Reason"
    }
    exit
}

proc InitWarning {Reason} {
    global AppName Version
    global batch_mode

    if {![info exists batch_mode] || (!$batch_mode)} {
	    mess "\n$AppName $Version Initialization Error:\n\t$Reason"
	    tk_messageBox -title "$AppName $Version Initialization Error" -type ok \
	        -message "Initialization Error\nFor details please refer to the message box."
    } else {
	    puts "\n$AppName $Version Initialization Error:\n\t$Reason"
    }
}

proc InitLicenseReset {} {
    global AppName Version license_not_valid
    global batch_mode 

    set mess "A valid license for $AppName $Version was not found.\nHow do you wish to proceed?\n\nRetry = Retry License Initialization\nCancel = Exit $AppName $Version"
	set what [tk_messageBox -title "$AppName $Version Initialization" -icon question -type retrycancel -message "$mess"]
	if {$what == "retry"} {
        InitializeLicense
        if [info exists license_not_valid] {
            InitLicenseReset
        }
    } elseif {$what == "cancel"} {
        if [ic_wb2_is_running] {
            ic_wb2_exit_icemcfd 2 1
        } else {
            exitProgram
        }
    }
}

#-------------------------------------------------------------------------------
#        V I S U A L 3    I N I T I A L I Z A T I O N
proc SetupVisual3 {} {
    global tdv_v3default
    global AIEnvDir
    global env
    global is_win
    global V3App
    
    set tdv_v3default [frame .v.v3]
    # Startup visual three
    set script [file join $AIEnvDir visual3 aie_v3_start.tcl]
    set v3exe [file join $env(VISUAL3P_ROOT) bin visual3p]
    if { $is_win == 1} {
	    set v3exe $v3exe.exe
    }
    set WindowPointer [winfo id $tdv_v3default]
    set V3App [open "|$v3exe $script -use $WindowPointer" "w"]
}




#-------------------------------------------------------------------------------
#        S P L A S H    S C R E E N
proc DoSplash {} {
    global AIEnvDir
    global BuildProgressIndicator
    global BuildProgressValue
    global BuildProgressStage
    global CurBuildProgressValue
    global AppName Version
    global env
    global AIEnvSplashIm    
    global aie_guiOpt

    if ![info exists env(AWP_ROOT)] {
        set splashPath "$env(ICEM_ACN)/../../commonfiles/"
    } else {
        set splashPath "$env(AWP_ROOT)/commonfiles/"
    }
    set im [image create photo -file [file join $splashPath "images" $aie_guiOpt(splashImage)]]
    set AIEnvSplashIm $im
    
    set BuildProgressValue 0
    set CurBuildProgressValue 0

    toplevel .splash -borderwidth 1 -relief flat -background black
    wm title .splash "$AppName $Version"
    if {![info exists env(ICEM_NO_MODAL_SPLASH)] || !$env(ICEM_NO_MODAL_SPLASH)} {
	    wm overrideredirect .splash 1
    }
    
    after idle {
	    update idletasks
	    set xmax [winfo screenwidth .splash]
	    set ymax [winfo screenheight .splash]
	    set x0 [expr ($xmax - [winfo reqwidth .splash])/2]
	    set y0 [expr ($ymax - [winfo reqheight .splash])/2]
	    wm geometry .splash "+$x0+$y0"
    }
    
    label .splash.image -image $im -background white
    frame .splash.f -background white
    set BuildProgressIndicator [ProgressBar .splash.f.progress -height 15 -width 300 -relief sunken -variable BuildProgressValue -background white]
    set SplashFont [font create -family Helvetica -size 9]
    set BuildProgressStage [label .splash.f.stage -background white -text "Initializing $AppName $Version" -justify left -font $SplashFont]
    
    grid .splash.f.stage -row 0 -column 0 -padx 3 -pady 2 -sticky w
    grid .splash.f.progress -row 0 -column 2 -pady 2 -padx 3 -sticky ews
    grid columnconfigure .splash.f 0 -weight 0
    grid columnconfigure .splash.f 1 -weight 1
    grid columnconfigure .splash.f 2 -weight 0
    
    grid .splash.image -row 0 -column 0 -columnspan 2 -sticky nsew
    grid .splash.f -row 1 -column 0  -sticky ew 
    
    grid columnconfigure .splash 0 -weight 1
    
    if [winfo ismapped .] {
       wm transient .splash .
    } else {
       wm protocol .splash WM_DELETE_WINDOW {wm withdraw .splash}
    }

    update
}

proc KillSplash {} {
    global aie_guiOpt
    if $aie_guiOpt(delaySplash) {
       wm deiconify .
       raise .

       global tdv_workspace AIEnvSplashIm
       if {[info exist AIEnvSplashIm] && ![catch {image type $AIEnvSplashIm}]} {
          set ih [image height $AIEnvSplashIm]
          set iw [image width $AIEnvSplashIm] 
          set bg [$tdv_workspace cget -background]
          label $tdv_workspace.im -image $AIEnvSplashIm -background $bg
          place  $tdv_workspace.im -in $tdv_workspace -x [expr ([winfo width $tdv_workspace] - $iw)/2] -y [expr ([winfo height $tdv_workspace] - $ih)/2]
          bind . <ButtonPress> "KillEmbedSplash $tdv_workspace.im"
       }
    }
    if [winfo exist .splash] { destroy .splash }
}

proc KillEmbedSplash {imfm} {
   global tdv_workspace AIEnvSplashIm

   if {[lsearch [place slaves $tdv_workspace] $imfm] >= 0} {
      place forget $imfm
   }
   bind . <ButtonPress> {}
}


proc HideBuildProgress {} {
    global BuildProgressIndicator
    grid remove $BuildProgressIndicator
    update
}

proc ShowBuildProgress {} {
   global BuildProgressIndicator

   if {[info exist BuildProgressIndicator] && [winfo exist $BuildProgressIndicator]} {
      grid $BuildProgressIndicator
      update
   }
}

proc InitializeLicenseEnvironments {} {
    global env ansys_license_exists

    set academic 1
    set addon 1
    set ameshextended 1
    set amesh 1
    set acfd 1
    
    set academic_exist 0
    set addon_exist 0
    set ameshextended_exist 0
    set amesh_exist 0
    set acfd_exist 0

    catch {
	     # 175 = aa_a, 178 = aa_r, 185 = aa_t_a, 183 = aa_t_i, 186 = aa_t_me, 187 = aa_t_cfd, 189 = aa_mesh
         # new academic keys: 179 = aa_r_cfd, 171 = aa_r_me, 196 = aa_r_ad, 172 = aa_a_cfd, 150 == a_r_pf
         if {([info exists ansys_license_exists(aa_a)] && $ansys_license_exists(aa_a) == 1)
                          || ([info exists ansys_license_exists(aa_r)] && $ansys_license_exists(aa_r) == 1)
                          || ([info exists ansys_license_exists(aa_t_a)] && $ansys_license_exists(aa_t_a) == 1)
                          || ([info exists ansys_license_exists(aa_t_i)] && $ansys_license_exists(aa_t_i) == 1) 
                          || ([info exists ansys_license_exists(aa_t_me)] && $ansys_license_exists(aa_t_me) == 1)
                          || ([info exists ansys_license_exists(aa_t_cfd)] && $ansys_license_exists(aa_t_cfd) == 1)
                          || ([info exists ansys_license_exists(aa_mesh)] && $ansys_license_exists(aa_mesh) == 1)
                          || ([info exists ansys_license_exists(aa_r_cfd)] && $ansys_license_exists(aa_r_cfd) == 1)
                          || ([info exists ansys_license_exists(aa_r_me)] && $ansys_license_exists(aa_r_me) == 1)
                          || ([info exists ansys_license_exists(aa_r_ad)] && $ansys_license_exists(aa_r_ad) == 1)
                          || ([info exists ansys_license_exists(aa_r_pf)] && $ansys_license_exists(aa_r_pf) == 1)
                          || ([info exists ansys_license_exists(aa_a_cfd)] && $ansys_license_exists(aa_a_cfd) == 1)} {
	         set academic_exist 1
         }
 	     # 263 = amesh_extended
         if {[info exists ansys_license_exists(amesh_extended)] && $ansys_license_exists(amesh_extended) == 1} {
	         set ameshextended_exist 1
         } 
	     # 267 = amesh
         if {[info exists ansys_license_exists(amesh)] && $ansys_license_exists(amesh) == 1} {
	         set amesh_exist 1
         } 
 	     # 289 = aiaddon
         if {[info exists ansys_license_exists(aiaddon)] && $ansys_license_exists(aiaddon) == 1} {
	         set addon_exist 1
         }
 	     # 160 = acfd, 162 = acfd_preppost, acfd_polyflow = 166, acfd_flo = 312, acfd_cfx = 313, acfd_fluent = 345
         if {([info exists ansys_license_exists(acfd)] && $ansys_license_exists(acfd) == 1) || \
             ([info exists ansys_license_exists(acfd_preppost)] && $ansys_license_exists(acfd_preppost) == 1) || \
             ([info exists ansys_license_exists(acfd_polyflow)] && $ansys_license_exists(acfd_polyflow) == 1) || \
             ([info exists ansys_license_exists(acfd_flo)] && $ansys_license_exists(acfd_flo) == 1) || \
             ([info exists ansys_license_exists(acfd_cfx)] && $ansys_license_exists(acfd_cfx) == 1) || \
             ([info exists ansys_license_exists(acfd_fluent)] && $ansys_license_exists(acfd_fluent) == 1)} {
	         set acfd_exist 1
         }
    }

    catch {
       # FORCE Academic Licensing
       if {[info exist env(USE_ANSYS_ACADEMIC_LICENSING)] && ![info exist env(ICEM_USE_ANSYS_CODE)]} {
	     # 175 = aa_a, 178 = aa_r, 185 = aa_t_a, 183 = aa_t_i, 186 = aa_t_me, 187 = aa_t_cfd, 189 = aa_mesh
         # new academic keys: 179 = aa_r_cfd, 171 = aa_r_me, 196 = aa_r_ad, 172 = aa_a_cfd, 150 == a_r_pf
         if {([info exists ansys_license_exists(aa_a)] && $ansys_license_exists(aa_a) == 1)
                          || ([info exists ansys_license_exists(aa_r)] && $ansys_license_exists(aa_r) == 1)
                          || ([info exists ansys_license_exists(aa_t_a)] && $ansys_license_exists(aa_t_a) == 1)
                          || ([info exists ansys_license_exists(aa_t_i)] && $ansys_license_exists(aa_t_i) == 1) 
                          || ([info exists ansys_license_exists(aa_t_me)] && $ansys_license_exists(aa_t_me) == 1)
                          || ([info exists ansys_license_exists(aa_t_cfd)] && $ansys_license_exists(aa_t_cfd) == 1)
                          || ([info exists ansys_license_exists(aa_mesh)] && $ansys_license_exists(aa_mesh) == 1)
                          || ([info exists ansys_license_exists(aa_r_cfd)] && $ansys_license_exists(aa_r_cfd) == 1)
                          || ([info exists ansys_license_exists(aa_r_me)] && $ansys_license_exists(aa_r_me) == 1)
                          || ([info exists ansys_license_exists(aa_r_ad)] && $ansys_license_exists(aa_r_ad) == 1)
                          || ([info exists ansys_license_exists(aa_r_pf)] && $ansys_license_exists(aa_r_pf) == 1)
                          || ([info exists ansys_license_exists(aa_a_cfd)] && $ansys_license_exists(aa_a_cfd) == 1)} {
                if {([info exists ansys_license_exists(aa_a)] && $ansys_license_exists(aa_a) == 1) 
                         || ([info exists ansys_license_exists(aa_a_cfd)] && $ansys_license_exists(aa_a_cfd) == 1)} {
	                set_env AI_ENV_NO_WATERMARK 1
                }
 	            set_env AI_ENV_ACADEMIC_NEW 1
	            set_env AI_ENV_GLOBAL 1
	            set_env AI_ENV_BFCART 1
	            set_env AI_ENV_HEXA 1
	            set_env AI_ENV_TETRA 1
	            set_env AI_ENV_QUAD 1
	            set_env AI_ENV_PRISM 1
	            set_env AI_ENV_POSTPROCESSING 1
            } else {
                InitError "No valid Academic License is available."
            }
            return
       }	
    }

    catch {
        # Workbench Academic Licensing
	    # 175 = aa_a, 178 = aa_r, 185 = aa_t_a, 183 = aa_t_i, 186 = aa_t_me, 187 = aa_t_cfd, 189 = aa_mesh
        # new academic keys: 179 = aa_r_cfd, 171 = aa_r_me, 196 = aa_r_ad, 172 = aa_a_cfd
        if {[info exist env(ICEM_USE_ANSYS_CODE)] && ($env(ICEM_USE_ANSYS_CODE) == 175 || $env(ICEM_USE_ANSYS_CODE) == 178 
            || $env(ICEM_USE_ANSYS_CODE) == 185 || $env(ICEM_USE_ANSYS_CODE) == 183 || $env(ICEM_USE_ANSYS_CODE) == 186 
            || $env(ICEM_USE_ANSYS_CODE) == 187 || $env(ICEM_USE_ANSYS_CODE) == 189 || $env(ICEM_USE_ANSYS_CODE) == 179
            || $env(ICEM_USE_ANSYS_CODE) == 171 || $env(ICEM_USE_ANSYS_CODE) == 196 || $env(ICEM_USE_ANSYS_CODE) == 172)} {
            if {$env(ICEM_USE_ANSYS_CODE) == 175 || $env(ICEM_USE_ANSYS_CODE) == 172} {
	            set_env AI_ENV_NO_WATERMARK 1
            }
	        set_env AI_ENV_ACADEMIC_NEW 1
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
	        set_env AI_ENV_HEXA 1
	        set_env AI_ENV_TETRA 1
	        set_env AI_ENV_QUAD 1
	        set_env AI_ENV_PRISM 1
	        set_env AI_ENV_POSTPROCESSING 1
            return
        }	
    }

    catch {
        # ANSYS Licensing Only
        # 241 = aienv, 278 = aimed
        if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1) 
            || ([info exists ansys_license_exists(aimed)] && $ansys_license_exists(aimed) == 1)} {
	        set academic 0
            set addon 0
            set ameshextended 0
	        set amesh 0
	        set acfd 0
        } 
        # 241 = aienv, 275 = aiglobal
        if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1) 
            || ([info exists ansys_license_exists(aiglobal)] && $ansys_license_exists(aiglobal) == 1)} {
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
        } else {
            if {($academic_exist == 1) || ($ameshextended_exist == 1) || ($addon_exist == 1) || ($amesh_exist == 1) || ($acfd_exist == 1)} {
 	            set_env AI_ENV_GLOBAL 1
	            set_env AI_ENV_BFCART 1
            }
        }
        # 241 = aienv, 287 = aibfcart
        if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1) 
            || ([info exists ansys_license_exists(aibfcart)] && $ansys_license_exists(aibfcart) == 1)} {
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
        } else {
           if {($academic_exist == 1) || ($ameshextended_exist == 1) || ($addon_exist == 1) || ($amesh_exist == 1) || ($acfd_exist == 1)} {
 	            set_env AI_ENV_GLOBAL 1
	            set_env AI_ENV_BFCART 1
            }
        }
	    # 241 = aienv, 276 = aihexa, 373 = aihexct5e
        if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1) 
            || ([info exists env(ICEM_HEXCAT5)] && ([info exists ansys_license_exists(aihexct5e)] && $ansys_license_exists(aihexct5e) == 1)) 
            || ([info exists ansys_license_exists(aihexa)] && $ansys_license_exists(aihexa) == 1)} {
	        set_env AI_ENV_HEXA 1
	        set_env AI_ENV_QUAD 1
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
        }  else {
            if {($academic_exist == 1) || ($ameshextended_exist == 1) || ($addon_exist == 1) || ($amesh_exist == 1) || ($acfd_exist == 1)} {
	            set_env AI_ENV_HEXA 1
	            set_env AI_ENV_QUAD 1
   	            set_env AI_ENV_GLOBAL 1
	            set_env AI_ENV_BFCART 1
            }
        }
	    # 241 = aienv, 284 = aitetra
        if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1)
            || ([info exists ansys_license_exists(aitetra)] && $ansys_license_exists(aitetra) == 1)} {
	        set_env AI_ENV_TETRA 1
	        set_env AI_ENV_PRISM 1
	        set_env AI_ENV_QUAD 1
         }  else {
            if {($academic_exist == 1) || ($ameshextended_exist == 1) || ($addon_exist == 1) || ($amesh_exist == 1) || ($acfd_exist == 1)} {
	            set_env AI_ENV_TETRA 1
	            set_env AI_ENV_PRISM 1
	            set_env AI_ENV_QUAD 1
            }
         }
	     # 241 = aienv, 283 = aiquad
         if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1)
            || ([info exists ansys_license_exists(aiquad)] && $ansys_license_exists(aiquad) == 1)} {
	        set_env AI_ENV_QUAD 1
         }  else {
            if {($academic_exist == 1) || ($ameshextended_exist == 1) || ($addon_exist == 1) || ($amesh_exist == 1) || ($acfd_exist == 1)} {
	            set_env AI_ENV_QUAD 1
            }
         }
	     # 241 = aienv, # 282 = aiprism
	     if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1)
            || ([info exists ansys_license_exists(aiprism)] && $ansys_license_exists(aiprism) == 1)} {
	        set_env AI_ENV_PRISM 1
         }  else {
            if {($academic_exist == 1) || ($ameshextended_exist == 1) || ($addon_exist == 1) || ($amesh_exist == 1) || ($acfd_exist == 1)} {
	            set_env AI_ENV_PRISM 1
            }
         }
 	     # 241 = aienv, 285 = aivis3
         if {([info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1) 
                    || ([info exists ansys_license_exists(aivis3)] && $ansys_license_exists(aivis3) == 1)} {
	        set_env AI_ENV_POSTPROCESSING 1
         } 
 	     # 263 = amesh_extended
	     if {$ameshextended && ([info exists ansys_license_exists(amesh_extended)] && $ansys_license_exists(amesh_extended) == 1) } {
	        set academic 0
	        set_env AI_ENV_TETRA 1
	        set_env AI_ENV_HEXA 1
	        set_env AI_ENV_PRISM 1
	        set_env AI_ENV_QUAD 1
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
 	        set_env AI_ENV_POSTPROCESSING 1
         } 
	     # 267 = amesh
	     if {$amesh && ([info exists ansys_license_exists(amesh)] && $ansys_license_exists(amesh) == 1)} {
	        set academic 0
	        set_env AI_ENV_TETRA 1
	        set_env AI_ENV_HEXA 1
	        set_env AI_ENV_PRISM 1
	        set_env AI_ENV_QUAD 1
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
 	        set_env AI_ENV_POSTPROCESSING 1
         } 
 	     # 289 = aiaddon
         if {$addon && ([info exists ansys_license_exists(aiaddon)] && $ansys_license_exists(aiaddon) == 1)} {
	        set academic 0
	        set_env AI_ENV_TETRA 1
	        set_env AI_ENV_HEXA 1
	        set_env AI_ENV_PRISM 1
	        set_env AI_ENV_QUAD 1
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
         }
	     # 160 = acfd, 162 = acfd_preppost, acfd_polyflow = 166, acfd_flo = 312, acfd_cfx = 313, acfd_fluent = 345
	     if {($acfd && ([info exists ansys_license_exists(acfd)] && $ansys_license_exists(acfd) == 1)) || \
	         ($acfd && ([info exists ansys_license_exists(acfd_preppost)] && $ansys_license_exists(acfd_preppost) == 1)) || \
	         ($acfd && ([info exists ansys_license_exists(acfd_polyflow)] && $ansys_license_exists(acfd_polyflow) == 1)) || \
	         ($acfd && ([info exists ansys_license_exists(acfd_flo)] && $ansys_license_exists(acfd_flo) == 1)) || \
	         ($acfd && ([info exists ansys_license_exists(acfd_cfx)] && $ansys_license_exists(acfd_cfx) == 1)) || \
	         ($acfd && ([info exists ansys_license_exists(acfd_fluent)] && $ansys_license_exists(acfd_fluent) == 1))} {
	        set academic 0
	        set_env AI_ENV_TETRA 1
	        set_env AI_ENV_HEXA 1
	        set_env AI_ENV_PRISM 1
	        set_env AI_ENV_QUAD 1
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
 	        set_env AI_ENV_POSTPROCESSING 1
         } 
         
 	     # 175 = aa_a, 178 = aa_r, 185 = aa_t_a, 183 = aa_t_i, 186 = aa_t_me, 187 = aa_t_cfd, 189 = aa_mesh
         # new academic keys: 179 = aa_r_cfd, 171 = aa_r_me, 196 = aa_r_ad, 172 = aa_a_cfd, 150 = a_r_pf
         if {$academic && (([info exists ansys_license_exists(aa_a)] && $ansys_license_exists(aa_a) == 1)
                          || ([info exists ansys_license_exists(aa_r)] && $ansys_license_exists(aa_r) == 1)
                          || ([info exists ansys_license_exists(aa_t_a)] && $ansys_license_exists(aa_t_a) == 1)
                          || ([info exists ansys_license_exists(aa_t_i)] && $ansys_license_exists(aa_t_i) == 1) 
                          || ([info exists ansys_license_exists(aa_t_me)] && $ansys_license_exists(aa_t_me) == 1)
                          || ([info exists ansys_license_exists(aa_t_cfd)] && $ansys_license_exists(aa_t_cfd) == 1)
                          || ([info exists ansys_license_exists(aa_mesh)] && $ansys_license_exists(aa_mesh) == 1)
                          || ([info exists ansys_license_exists(aa_r_cfd)] && $ansys_license_exists(aa_r_cfd) == 1)
                          || ([info exists ansys_license_exists(aa_r_me)] && $ansys_license_exists(aa_r_me) == 1)
                          || ([info exists ansys_license_exists(aa_r_ad)] && $ansys_license_exists(aa_r_ad) == 1)
                          || ([info exists ansys_license_exists(aa_r_pf)] && $ansys_license_exists(aa_r_pf) == 1)
                          || ([info exists ansys_license_exists(aa_a_cfd)] && $ansys_license_exists(aa_a_cfd) == 1))} {
            if {([info exists ansys_license_exists(aa_a)] && $ansys_license_exists(aa_a) == 1) 
                || ([info exists ansys_license_exists(aa_a_cfd)] && $ansys_license_exists(aa_a_cfd) == 1)} {
	            set_env AI_ENV_NO_WATERMARK 1
            }
	        set_env AI_ENV_ACADEMIC_NEW 1
	        set_env AI_ENV_GLOBAL 1
	        set_env AI_ENV_BFCART 1
	        set_env AI_ENV_HEXA 1
	        set_env AI_ENV_TETRA 1
	        set_env AI_ENV_QUAD 1
	        set_env AI_ENV_PRISM 1
	        set_env AI_ENV_POSTPROCESSING 1
         } 
    }
}

proc InitializeProductFlavor {} {
    global env ansys_license_exists

    set HAS_AIENV 0
    set HAS_AIMED 0
    set HAS_AIOUTCFD 0
    set HAS_AIHEXA 0
    set HAS_AIVIS3 0
    set HAS_AICART3D 0
    set HAS_MED 0
    set HAS_OUTPUT 0
    set HAS_HEXA 0
    set HAS_VIS3 0
    set HAS_CART3D 0
    set HAS_AIADDON 0
    set HAS_AMESHEXTENDED 0
    set HAS_AMESH 0
    set HAS_ACFD 0
    set FLAVOR ""

    catch {
        # Workbench Academic Licensing
	    # 175 = aa_a, 178 = aa_r, 185 = aa_t_a, 183 = aa_t_i, 186 = aa_t_me, 187 = aa_t_cfd, 189 = aa_mesh
        # new academic keys: 179 = aa_r_cfd, 171 = aa_r_me, 196 = aa_r_ad, 172 = aa_a_cfd
        if {[info exist env(ICEM_USE_ANSYS_CODE)] && ($env(ICEM_USE_ANSYS_CODE) == 175 || $env(ICEM_USE_ANSYS_CODE) == 178 
            || $env(ICEM_USE_ANSYS_CODE) == 185 || $env(ICEM_USE_ANSYS_CODE) == 183 || $env(ICEM_USE_ANSYS_CODE) == 186 
            || $env(ICEM_USE_ANSYS_CODE) == 187 || $env(ICEM_USE_ANSYS_CODE) == 189 || $env(ICEM_USE_ANSYS_CODE) == 179
            || $env(ICEM_USE_ANSYS_CODE) == 171 || $env(ICEM_USE_ANSYS_CODE) == 196 || $env(ICEM_USE_ANSYS_CODE) == 172)} {
	        set_env USE_ANSYS_ACADEMIC_LICENSING 1
        }	
    }

    set homedir [lindex [glob -nocomplain ~] 0]
    if {$homedir == ""} {
        set u "user"
        if [info exists env(USERNAME)] {
            set u $env(USERNAME)
        }
        set h "~$u"
        set cwd [pwd]
        catch { cd "$h" }
        set homedir [pwd] 
        cd "$cwd"
    }
    set optf $homedir/.aienv_options
    if [file exists $optf] {
	    set fp [open $optf r]
	    while {![eof $fp]} {
	        set line [gets $fp]
	        if {[string first {product_mode} $line] != -1} {
                set var1 [lindex $line 2] 
                if {$var1 !=""} { set FLAVOR $var1 }   
	        }
	        if {[string first {geom_off_mode} $line] != -1} {
                set var2 [lindex $line 2]    
                if {$var2 !="0"} { set_env AI_NO_GEOM $var2 }
	        }
	        if {[string first {mesh_off_mode} $line] != -1} {
                set var2 [lindex $line 2]    
                if {$var2 !="0"} { set_env AI_NO_MESH $var2 }
	        }
	        if {[string first {meshedit_off_mode} $line] != -1} {
                set var2 [lindex $line 2]    
                if {$var2 !="0"} { set_env AI_NO_MESHEDIT $var2 }
	        }
	        if {[string first {hexa_off_mode} $line] != -1} {
                set var2 [lindex $line 2]    
                if {$var2 !="0"} { set_env AI_NO_BLOCKING $var2 }
	        }
	        if {[string first {preprocessing_off_mode} $line] != -1} {
                set var2 [lindex $line 2]    
                if {$var2 !="0"} { set_env AI_NO_PREPROCESSING $var2 }
	        }
	        if {[string first {output_off_mode} $line] != -1} {
                set var2 [lindex $line 2]    
                if {$var2 !="0"} { set_env AI_NO_OUTPUT $var2 }
	        }
	    }
	    close $fp
    }

    if {($FLAVOR == "") || [info exist env(USE_ANSYS_ACADEMIC_LICENSING)]} {

       catch {
          # ANSYS Licensing Only
            # ansys 241 = aienv
            if {[info exists ansys_license_exists(aienv)] && $ansys_license_exists(aienv) == 1} {
	            set HAS_AIENV 1
            } 
             # ansys 263 = amesh_extended
            if {[info exists ansys_license_exists(amesh_extended)] && $ansys_license_exists(amesh_extended) == 1} {
	            set HAS_AMESHEXTENDED 1
            }
	        # ansys 267 = amesh
            if {[info exists ansys_license_exists(amesh)] && $ansys_license_exists(amesh) == 1} {
	            set HAS_AMESH 1
            } 
	        # ansys 162 = acfd, 162 = acfd_preppost, acfd_polyflow = 166, acfd_flo = 312, acfd_cfx = 313, acfd_fluent = 345
            if {([info exists ansys_license_exists(acfd)] && $ansys_license_exists(acfd) == 1) || \
                ([info exists ansys_license_exists(acfd_preppost)] && $ansys_license_exists(acfd_preppost) == 1) || \
                ([info exists ansys_license_exists(acfd_polyflow)] && $ansys_license_exists(acfd_polyflow) == 1) || \
                ([info exists ansys_license_exists(acfd_flo)] && $ansys_license_exists(acfd_flo) == 1) || \
                ([info exists ansys_license_exists(acfd_cfx)] && $ansys_license_exists(acfd_cfx) == 1) || \
                ([info exists ansys_license_exists(acfd_fluent)] && $ansys_license_exists(acfd_fluent) == 1)} {
	            set HAS_ACFD 1
            } 
            # ansys 289 = aiaddon
            if {[info exists ansys_license_exists(aiaddon)] && $ansys_license_exists(aiaddon) == 1} {
	            set HAS_AIADDON 1
            } 
            # ansys 325 = aioutcfd
            if {[info exists ansys_license_exists(aioutcfd)] && $ansys_license_exists(aioutcfd) == 1} {
	            set HAS_AIOUTCFD 1
            } 
            # ansys 278 = aimed
            if {[info exists ansys_license_exists(aimed)] && $ansys_license_exists(aimed) == 1} {
	            set HAS_AIMED 1
            }             
            # ansys 352 = aiedgeom
            if {[info exists ansys_license_exists(aiedgeom)] && $ansys_license_exists(aiedgeom) == 1} {
	            set HAS_AIMED 1
            } 
            # ansys 276 = aihexa
            if {[info exists ansys_license_exists(aihexa)] && $ansys_license_exists(aihexa) == 1} {
	            set HAS_AIHEXA 1
            } 
            # 175 = aa_a, 178 = aa_r, 185 = aa_t_a, 183 = aa_t_i, 186 = aa_t_me, 187 = aa_t_cfd, 189 = aa_mesh
            # new academic keys: 179 = aa_r_cfd, 171 = aa_a_ad, 196 = aa_r_ad, 172 = aa_a_cfd
            if {(($HAS_AIENV == 0 && $HAS_AIMED == 0) || [info exist env(USE_ANSYS_ACADEMIC_LICENSING)]) && 
               (([info exists ansys_license_exists(aa_a)] && $ansys_license_exists(aa_a) == 1)
               || ([info exists ansys_license_exists(aa_r)] && $ansys_license_exists(aa_r) == 1)
               || ([info exists ansys_license_exists(aa_t_a)] && $ansys_license_exists(aa_t_a) == 1)
               || ([info exists ansys_license_exists(aa_t_i)] && $ansys_license_exists(aa_t_i) == 1) 
               || ([info exists ansys_license_exists(aa_t_me)] && $ansys_license_exists(aa_t_me) == 1)
               || ([info exists ansys_license_exists(aa_t_cfd)] && $ansys_license_exists(aa_t_cfd) == 1)
               || ([info exists ansys_license_exists(aa_mesh)] && $ansys_license_exists(aa_mesh) == 1)
               || ([info exists ansys_license_exists(aa_r_cfd)] && $ansys_license_exists(aa_r_cfd) == 1)
               || ([info exists ansys_license_exists(aa_r_me)] && $ansys_license_exists(aa_r_me) == 1)
               || ([info exists ansys_license_exists(aa_r_ad)] && $ansys_license_exists(aa_r_ad) == 1)
               || ([info exists ansys_license_exists(aa_a_cfd)] && $ansys_license_exists(aa_a_cfd) == 1))} {
                set HAS_AIENV 1
	            set HAS_AIOUTCFD 1
           }
       }
       
       #tk_messageBox -message "HAS_AIENV $HAS_AIENV\nHAS_AIADDON $HAS_AIADDON\nHAS_AMESHEXTENDED $HAS_AMESHEXTENDED\nHAS_AIMED $HAS_AIMED\nHAS_MED $HAS_MED\nHAS_AIOUTCFD $HAS_AIOUTCFD\nHAS_OUTPUT $HAS_OUTPUT" -type ok -icon info
       #tk_messageBox -message "HAS_AIHEXA $HAS_AIHEXA\nHAS_HEXA $HAS_HEXA\nHAS_AIVIS3 $HAS_AIVIS3\nHAS_VIS3 $HAS_VIS3\nHAS_AICART3D $HAS_AICART3D\nHAS_CART3D $HAS_CART3D\nHAS_AMES $HAS_AMESH\nHAS_ACFD $HAS_ACFD" -type ok -icon info


       if {$HAS_AIENV == 1 && $HAS_AIOUTCFD == 1} {
          set FLAVOR "-fsi"
       } elseif {$HAS_AIENV == 1 && $HAS_AIOUTCFD == 0} {
          set FLAVOR "-ai"
       } elseif {$HAS_AIMED  == 1 && ($HAS_AIOUTCFD == 1 || $HAS_ACFD == 1)} {
          set FLAVOR "-cfd"
       } elseif {$HAS_AIMED  == 1 && $HAS_AIOUTCFD == 0} {
          set FLAVOR "-cfx"
       } elseif {$HAS_AMESHEXTENDED  == 1 || $HAS_AMESH == 1} {
          set FLAVOR "-fsi"
       } elseif {$HAS_AIADDON  == 1} {
          set FLAVOR "-addon"
       } elseif {$HAS_MED  == 1 && $HAS_OUTPUT == 1} {
          set FLAVOR "-cfd"
       } elseif {$HAS_MED  == 1 && $HAS_OUTPUT == 0} {
          set FLAVOR "-cfx"
       } else {
          set FLAVOR "-ansys"
       }
       
       #tk_messageBox -message "FLAVOR $FLAVOR" -type ok -icon info

       if [info exist env(AI_ENV_CART3D)] {
            unset env(AI_ENV_CART3D)
       }
    }

    if  {$FLAVOR == "-cfd"} {
       set_env AI_ENV_PRODUCT "cfd"
    } elseif {$FLAVOR == "-addon"} {
       set_env AI_ENV_PRODUCT "addon"
    } elseif {$FLAVOR == "-cfx"} {
       set_env AI_ENV_PRODUCT "cfx"
    } elseif {$FLAVOR == "-ansys"} {
       set_env AI_ENV_PRODUCT "ansys"
    } elseif {$FLAVOR == "-ai"} {
       set_env AI_ENV_PRODUCT "fea2.0"
    } elseif {$FLAVOR == "-fsi"} {
       set_env AI_ENV_PRODUCT "fsi"
    }
    if [info exist env(AI_ENV_PRODUCT)] {
       #tk_messageBox -message "AI_ENV_PRODUCT set to $env(AI_ENV_PRODUCT)" -type ok -icon info
       if {$env(AI_ENV_PRODUCT) == "fea2.0"} {
          set_env AI_ENV_ANSYS 1
          set_env AI_ENV_LSDYNA 1
          set_env AI_ENV_ABAQUS 1
          set_env AI_ENV_AUTODYN 1
       } elseif {$env(AI_ENV_PRODUCT) == "cfd"} {
          set_env AI_ENV_CFD 1
          set_env AI_ENV_CFD_ONLY 1
          set_env AI_ENV_ANSYS 1
          set_env AI_ENV_LSDYNA 1
          set_env AI_ENV_ABAQUS 1
          set_env AI_ENV_AUTODYN 1
       } elseif {$env(AI_ENV_PRODUCT) == "addon"} {
          set_env AI_ENV_CFD 1
          set_env AI_ENV_ANSYS_SOLVERS 1
          set_env AI_ENV_ANSYS 1
          set_env AI_ENV_LSDYNA 1
          set_env AI_ENV_AUTODYN 1
          set_env AI_ENV_PRODUCT "fea2.0"
       } elseif {$env(AI_ENV_PRODUCT) == "cfx"} {
          set_env AI_ENV_CFD 1
          set_env AI_ENV_CFD_ONLY 1
          set_env AI_ENV_CFX 1
          set_env AI_ENV_ANSYS_SOLVERS 1
          set_env AI_ENV_PRODUCT "cfd"
       } elseif {$env(AI_ENV_PRODUCT) == "ansys"} {
          set_env AI_ENV_CFD 1
          #set_env AI_ENV_ANSYS_SOLVERS 1
          set_env AI_ENV_PRODUCT "fea2.0"
          set_env AI_ENV_ANSYS 1
          set_env AI_ENV_LSDYNA 1
          set_env AI_ENV_AUTODYN 1
          set_env AI_ENV_ABAQUS 1
       } elseif {$env(AI_ENV_PRODUCT) == "fsi"} {
          set_env AI_ENV_CFD 1
          set_env AI_ENV_PRODUCT "fea2.0"
          set_env AI_ENV_ANSYS 1
          set_env AI_ENV_LSDYNA 1
          set_env AI_ENV_ABAQUS 1
          set_env AI_ENV_AUTODYN 1
       }
    }
}

proc CheckAnsysLILicensing {} {
    global env ansys_license_exists

    set features "aa_r_pf acfd acfd_preppost acfd_polyflow aa_r_me aa_a_cfd aa_a aa_r aa_r_cfd aa_t_i aa_t_a aa_t_me aa_t_cfd aa_mesh aa_r_ad aienv aiglobal aihexa aimed aiprism aiquad aitetra aivis3 aibfcart aiaddon aioutcfd aiedgeom aicart3d aihexct5e amesh_extended amesh acfd_flo acfd_cfx acfd_fluent"
    set ansys_licensing_features "150\,160\,162\,166\,171\,172\,175\,178\,179\,183\,185\,186\,187\,189\,196\,241\,275\,276\,278\,282\,283\,284\,285\,287\,289\,325\,352\,370\,373\,263\,267\,312\,313\,345"
    set comma "\,"

    catch {

    #tk_messageBox -message "Features $ansys_licensing_features" -type ok -icon info
    set ansys_licensing_check [check_ansysLI_license_exists $ansys_licensing_features]
    #tk_messageBox -message "Checks $ansys_licensing_check" -type ok -icon info

    set N [string toupper $ansys_licensing_check]
    set ln [llength $features]
    for {set i 0} {$i < $ln} {incr i} {
        set feat [lindex $features $i]
        set is [string first $comma $N]
        if {$is > 0} {
           set status [string range $N 0 [expr $is - 1]]
           set N [string range $N [expr $is + 1] end]
        } elseif {$i == [expr $ln - 1]} {
           set status [string range $N 0 end]
        }
        if {$status == "TRUE"} {
           set ansys_license_exists($feat) 1
        } else {
           set ansys_license_exists($feat) 0
        }
   }
   }
}

proc ResetAIEnvGUI {} {
   global AIEnvDir AppName Version aie_guiOpt env

   set ResourceFile [file join $AIEnvDir resource $aie_guiOpt(topTTKRF)]

   if [file exist $ResourceFile] {
      ::AIEnv::GUIManagement::InNamespaceResetGUI $ResourceFile
   }
}

# Get things rolling

AIEnvMain


