# Author:  Jari Spaete, jari.spaete@ansys.com
# file operating callbacks

proc aie_openFile {file} {
    global is_win project_file_header batch_mode

    switch [file extension $file] {
	    .prj - .wbpj { aie_openProject $file }
	    .tin { aie_open_geom 1 [list $file] }
	    .uns { aie_open_Mesh 1 "" "" [list $file] }
	    .jrf - .rpl {
	        script_interp eval [list source $file]
	        if !$batch_mode { aie_afterStuffLoaded }
	    }
	    .blk { aie_open_blocking 1 $file }
	    .dat { aie_import_nastran $file 1 0 1 1 1 }
	    .msh { aie_open_Mesh 1 "" "" "$file" }
	    .scdoc {
	        if [ic_wb_contains_blocking $file] {
	            ic_wb_import_blockings $file
	            if !$batch_mode { ic_gui_update mesh }
	        } else {
	            mess "Importing SpaceClaim file $file\n" blue
	            ic_wb_set_default_properties
	            ic_set_global vid_options 1 wb_import_geom
	            ic_set_global vid_options 0 wb_import_mesh
	            ic_wb_brep_read $file
	            if !$batch_mode { aie_afterStuffLoaded }
	        }
	    }
	    default {
	        # maybe directory selection via "Send to" on windows
	        if {$is_win && [file isdirectory $file]} {
	            set file_search ""
	            foreach {type} {prj tin uns} {
	                set file_search [glob -nocomplain [win_shortname $file]/*.$type]
	                if {$file_search != ""} {
	                    # maybe there is more than 1 prj/tin/uns file
	                    if {[llength $file_search] > 1} {
	                        switch $type {
	                            prj {
	                                aie_openProject [win_shortname $file]
	                            }
	                            tin {
	                                set_project_dir [win_shortname $file]
	                                aie_open_geom 1 ""
	                            }
	                            uns {
	                                set_project_dir [win_shortname $file]
	                                aie_open_Mesh 1 "" "" ""
	                            }
	                        }
	                    } else {
	                        aie_openProject [list $file_search]
	                    }
	                    break
	                }
	            }
	            if {$file_search == ""} {
	                aie_openProject [win_shortname $file]
	            }
	        } else {
	            user_error "Unknown file type $file"
	        }
	    }
    }
    if !$batch_mode { tdv_home current }
}

proc aie_saveProject {{ask 0} {only_if_needed 0} {do_exit 0} {send_to_wb2 0}} {
    global file_name env wb_initProjName wb_curdir options
    global use_workbench batch_mode param_values env

    if {$only_if_needed && ![ic_uns_is_modified] && ![ic_geo_is_modified] && ![ic_boco_is_modified] && ![ic_param_is_modified]} { return 0 }
    set ret 0
    set wb_file_set 0
    if {$file_name(project_dir) == ""} {
        set_project_dir .
    }
    if {([info exists use_workbench] && $use_workbench == 1 && $file_name(project_dir) == ".") || [aie_wb2_is_running]} {
        # Apps in workbench require a full path
        set_project_dir [pwd]
        if {[aie_wb2_is_running] && [info exists wb_initProjName] && $wb_initProjName != ""} {
            set file_name(settings) $wb_initProjName.prj
            aie_wb2_update_upstream_data_filename
            aie_wb2_backup_files $do_exit
            ic_set_global vid_options 1.0 wb_import_transfer_file_scale
            if [ic_geo_is_loaded] {
                set units [ic_geo_get_units 1]
                if {$units != "meters" && $units != ""} {
                    set scale [ic_geo_convert_units $units m]
                    if [string is double -strict $scale] {
                        ic_set_global vid_options $scale wb_import_transfer_file_scale
                    }
                }
            }
        }
    }
    set old_prjdir $file_name(project_dir)
    set prevdir [pwd]
    set old_prj [file root $file_name(settings)]
    if {$ask == 1 || $file_name(project_dir) == "" || $file_name(settings) == ""} {
        set defdir $file_name(project_dir)
        if {$defdir == ""} { set defdir [pwd] }
        if $wb_file_set {
            set init_prj_file $file_name(settings)
        } elseif {$file_name(settings) != ""} {
            set init_prj_file [file tail $file_name(settings)]
        } else {
            set init_prj_file [aie_unused_project_name].prj
        }
	    set prj_file [tk_getSaveFile -filetypes {{{Project Files} {.prj}} {{All Files} *}} \
			-title "Save Project As" -parent . -initialfile $init_prj_file -initialdir $defdir]
        if {$prj_file == ""} { return 0 }
        if {[file extension $prj_file] != ".prj"} {
            set prj_file $prj_file.prj
        }
        set prj_dir [file dirname $prj_file]
        if ![file exists $prj_dir] { ic_mkdir $prj_dir }
        if {([pwd] != $prj_dir) && ($prj_dir != ".")} {
            if [catch {ic_chdir $prj_dir} res] {
                mess "Error in changing project directory to $res\n"
                return 0
            } elseif {$file_name(project_dir) != "."} {
                mess "Project directory changed to $file_name(project_dir)\n"
            }
        }
        set file_name(settings) $prj_file
        set_project_dir .
        if [info exists env(AI_ENV_CFX)] {
            set new_prj [file root $prj_file]
            if {([file exists ${old_prj}.prism_params]) && ($new_prj != $old_prj) } {
                cmd_cp ${old_prj}.prism_params ${new_prj}.prism_params
            }
        }
    }
    aie_delete_empty_parts
    set pref [file tail [file rootname $file_name(settings)]]
    if [ic_geo_is_loaded] {
        if {$file_name(tetin) == "" || $ask == "1" || ![info exists options(keep_existing_file_names)] || $options(keep_existing_file_names) != "1"} {
            set file_name(tetin) $pref.tin
        }
        aie_save_geom
        incr ret 2
    } else {
        if [ic_uns_is_loaded] {
            ic_empty_tetin
            if {[lindex [ic_geo_get_periodic_data] 1] != "none"} {
                # save only the periodic data
                set file_name(tetin) $pref.tin
                mess "Saving empty tetin (contains only the periodic data)\n"
                ic_save_tetin $file_name(tetin)
            } else {
                set file_name(tetin) ""
            }
        } else {
            set file_name(tetin) ""
        }
    }

    if [ic_str_is_loaded] {
        set file_name(domain) $pref.Multiblock
        aie_save_strMesh
        incr ret 4
    }
    if [ic_uns_is_loaded] {
        if {$file_name(domain) == "" || $ask == "1" || ![info exists options(keep_existing_file_names)] || $options(keep_existing_file_names) != "1"} {
	        set file_name(domain) $pref.uns
        }
	    aie_save_Mesh
	    if {[ic_count_elements] != 0} {
	        incr ret 4
	    }
    } else {
        if ![ic_str_is_loaded] {
            set file_name(domain) ""
        }
    }

    if [ic_hex_blocking_loaded] {
        if {$file_name(blocking) == "" || $ask == "1" || ![info exists options(keep_existing_file_names)] || $options(keep_existing_file_names) != "1"} {
	        set file_name(blocking) $pref.blk
        }
        if {([aie_wb2_is_running] || [info exists env(AI_ENV_IN_WB1)]) && ![ic_uns_is_loaded] && [ic_geo_is_loaded]} {
            set dim [string trimright [ic_hex_dim_to_mesh] \n]
            set ptype [aie_get_global project_type]
            if {$ptype == "___NA___" || $ptype == ""} { set ptype 2 }
            set parts [ic_hex_list_block_families_without "VORFN ORFN"]
            if {$parts != ""} {
                set nproc [ic_get_n_processors]
                mess "Creating unstructured domain file $pref.uns from pre-mesh..."
                eval ic_hex_create_mesh $parts proj $ptype dim_to_mesh $dim nproc $nproc
                eval ic_hex_write_file $pref.uns $parts proj $ptype dim_to_mesh $dim no_boco
                mess "done\n"
                ic_uns_load $pref.uns 3 0 {}
                set file_name(domain) $pref.uns
                aie_update_gui mesh
                incr ret 4
            } else {
                mess "Unable to create unstructured domain file from pre-mesh; no block parts found"
            }
        }
	    aie_save_blocking 
    } else {
        set file_name(blocking) ""
    }

    if [ic_boco_is_loaded] {
	    set save 1
	    if !$file_name(family_boco_loaded) {
	        # If the file wasn't loaded, and there are no non-trivial bocos, then don't save it
	        set numbcs 0
	        foreach f [ic_boco_list_families] { incr numbcs [llength [ic_boco_get $f]] }
	        if !$numbcs {
		        set save 0
	        }
	    }
	    if $save {
            if {$ask == "1" || $file_name(family_boco) == "" || $file_name(attributes) == "" || \
                ![info exists options(keep_existing_file_names)] || $options(keep_existing_file_names) != "1"} {
	            set file_name(family_boco) $pref.fbc
	            set file_name(attributes) $pref.atr
            }
	        aie_save_attr
	    }
    } else {
        if {[aie_wb2_is_running] && $batch_mode} {
	       set file_name(family_boco) $pref.fbc
	       set file_name(attributes) $pref.atr
	       aie_save_attr
        } else {
            set file_name(family_boco) ""
	        set file_name(attributes) ""
	    }
    }

    catch {
	    aie_update_materials_to_params
    }
    catch {
	    aie_save_tbls
    }
    catch {
	    aie_save_sol_params
    }
    catch {
	    aie_save_lcs
    }
    if {[ic_param_is_loaded] || [ic_param_is_modified]} {
        if {$file_name(solver_params) == "" || $ask == "1" || ![info exists options(keep_existing_file_names)] || $options(keep_existing_file_names) != "1"} {
	        set file_name(solver_params) $pref.par
        }
	    aie_save_params
    } else {
        set file_name(solver_params) ""
    }
    ic_param_set_modified 0

    if [ic_cart_is_loaded] {
        if {$file_name(cart_file) == "" || $ask == "1" || ![info exists options(keep_existing_file_names)] || $options(keep_existing_file_names) != "1"} {
	        set file_name(cart_file) $pref.crt
        }
	    aie_save_cart
    } else {
        set file_name(cart_file) ""
    }

    if {[file extension $file_name(settings)] != ".prj"} {
         set file_name(settings) $file_name(settings).prj
    }

    if !$batch_mode {
        ::AIEnv::GUIManagement::Tree::SaveTreeStatus
        aie_save_last_view
    }
    set options(user_name) [cmd_whoami]
    set options(host_name) [cmd_uname_n]
    set options(select_mode) all
    #ic_save_project_file $file_name(settings)
    
    project_settings_save $file_name(settings)
    if !$batch_mode {
        aie_save_dez_data $file_name(settings)
    }
    aie_save_user_topo_tolerance $file_name(settings)

    # prism params are saved to the project file
    catch {file delete "$pref.prism_params"}
    aie_set_title [file tail [file rootname $file_name(settings)]]
    if {$ask == 1 && $old_prjdir != ""}  {
	    foreach d [array names file_name] {
	        if [string match *_dir $d] {
		        if [string match $old_prjdir/* $file_name($d)] {
		            set file_name($d) $file_name(project_dir)
		        }
	        }
	    }
    }
    
    # --> try to export bsm stuff
    # (this command will handle whether or not the correct commands exist in the interp)
    trySavingBatchMeshingData

    aie_rename_journal_file [file tail [file rootname $file_name(settings)]] $prevdir

    aie_save_lsdyna_par_file

    if ![aie_wb2_is_running] {
        if {([info exists old_prj] && $old_prj != "") && [file exists "$old_prj.pmdb"]} {
            if {[info exists prj_dir] && ("$old_prj.pmdb" != "$prj_dir/$pref.pmdb")} {
                ic_cp "$old_prj.pmdb" "$prj_dir/$pref.pmdb"
            }
        }
    }
    
    if [aie_wb2_is_running] {
        if [aie_wb2_is_upstream_data_updated] {
            incr ret 1
        }
    }
    if [aie_wb2_is_running] {
        mess "Project $wb_curdir/$file_name(settings) saved\n"
        if {[info exists file_name(upstream_data)] && [file exists $file_name(upstream_data)]} {
            switch [aie_get_global wb_upstream_data_status] {
                1 {
                    set ret 0
                }
            }
        }

        if $send_to_wb2 {
            return [ic_wb2_send_wb_status $ret]
        } else {
            if {[aie_get_global file_name upstream_data] == "___NA___" && $ret == 4} {
                # special case: only mesh exists without any geometry and no upstream data
                incr ret
            }
            switch $ret {
                1 { return 4 }
                2 { return 1 }
                3 { return 5 }
                4 { return 2 }
                5 { return 6 }
                6 { return 3 }
                7 { return 7 }
                default { return 0 }
            }
        }
    } else {
        mess "Project saved\n"
        return 1
    }
}

proc aie_save_lsdyna_par_file {} {
    global env file_name

    if ![info exists env(AI_ENV_LSTC)] return

	set pref [file rootname $file_name(settings)]
	set fp [open $pref.lsdyna.par w]
	puts $fp {
begin control
    begin Control1
        OPT 0
    end Control1
    begin Control10
        OPT 0
    end Control10
    begin Control11
        OPT 0
    end Control11
    begin Control12
        OPT 0
    end Control12
    begin Control13
        OPT 0
    end Control13
    begin Control14
        OPT 0
    end Control14
    begin Control15
        OPT 1
        card1p1 0
    end Control15
    begin Control16
        OPT 0
    end Control16
    begin Control17
        OPT 1
        card1p1 2
        card1p2 2
        card1p3 2
        card1p4 1
    end Control17
    begin Control18
        OPT 1
        card1p1 1
        card1p2 0.1
        choice 0
    end Control18
    begin Control19
        OPT 0
    end Control19
    begin Control2
        OPT 0
    end Control2
    begin Control20
        OPT 0
    end Control20
    begin Control21
        OPT 0
    end Control21
    begin Control22
        OPT 0
    end Control22
    begin Control23
        OPT 0
    end Control23
    begin Control24
        OPT 0
    end Control24
    begin Control25
        OPT 0
    end Control25
    begin Control26
        OPT 0
    end Control26
    begin Control27
        OPT 1
        card1p1 1
        card1p2 3
        card1p3 0
        card1p4 0
        card1p5 0
        card1p6 0
        card1p7 0
        card1p8 0
    end Control27
    begin Control28
        OPT 1
        card1p1 1
        card1p2 0
        card1p3 0
        card1p4 0
    end Control28
    begin Control29
        OPT 0
    end Control29
    begin Control3
        OPT 0
        card1p7 0
    end Control3
    begin Control30
        OPT 0
    end Control30
    begin Control31
        OPT 1
        card1p1 0
        card1p2 1
        card1p3 0
        card1p4 0
        card1p5 2
        card1p6 0
        card1p7 0
        card1p8 0
    end Control31
    begin Control32
        OPT 0
    end Control32
    begin Control33
        OPT 0
    end Control33
    begin Control34
        OPT 0
    end Control34
    begin Control35
        OPT 1
        card1p1 0.2
        card1p2 0
        card1p3 0
        card1p4 0
        card1p5 0
    end Control35
    begin Control36
        OPT 0
    end Control36
    begin Control37
        OPT 0
    end Control37
    begin Control38
        OPT 0
    end Control38
    begin Control39
        OPT 1
        card1p1 0
        card1p2 0.9
        card1p3 0
        card1p4 0
        card1p5 -6.666E-06
        card1p6 0
        card1p7 0
        card1p8 0
    end Control39
    begin Control4
        OPT 0
    end Control4
    begin Control40
        OPT 0
    end Control40
    begin Control5
        OPT 0
    end Control5
    begin Control6
        OPT 0
    end Control6
    begin Control7
        OPT 0
    end Control7
    begin Control8
        OPT 0
    end Control8
    begin Control9
        OPT 0
    end Control9
end control

begin contact_rigid
    DEFINE 0
end contact_rigid

begin def_node
    formul 0
    mass 0.0
    write 1
end def_node

begin brodeload
    DEFINE 0
end brodeload

begin part_set All
    name All
    begin fam fam0
        str GEOM
    end fam fam0
    begin fam fam1
        str CREATED_MATERIAL_4
    end fam fam1
    begin fam fam2
        str CUBE
    end fam fam2
end part_set All

begin def_part
    adpopt 0
    grav 0
    tmid 0
end def_part

begin constraint
    DEFINE 0
end constraint

begin def_shell
    formul 1
    formul2 12
    mat0 1
    mat_def 0
    mat_name {}
    physics 0
    write 1
    begin card1
        f1 -1
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card1
    begin card2
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card2
    begin card3
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card3
    begin card4
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card4
    begin card5
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card5
    begin card6
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card6
    begin hg_shell
        include 0
    end hg_shell
    begin sec_shell
        icomp 0
        id -1
        marea 0.0
        nip 0
        nloc 0
        opt 0
        propt 1
        qr 0
        shrf 0.0
        thk 0.0
    end sec_shell
end def_shell

begin blastload
    DEFINE 0
end blastload

begin initial_cfd
    DEFINE 0
end initial_cfd

begin contact_interior
    DEFINE 0
end contact_interior

begin dbase
    begin database
        begin ABSTAT
            OPT 1
            OUT 1E-03
        end ABSTAT
        begin AVSFLT
            OPT 0
        end AVSFLT
        begin BNDOUT
            OPT 0
        end BNDOUT
        begin DEFGEO
            OPT 0
        end DEFGEO
        begin DEFORC
            OPT 0
        end DEFORC
        begin ELOUT
            OPT 0
        end ELOUT
        begin GCEOUT
            OPT 0
        end GCEOUT
        begin GLSTAT
            OPT 1
            OUT 1E-03
        end GLSTAT
        begin JNTFORC
            OPT 0
        end JNTFORC
        begin MATSUM
            OPT 1
            OUT 1E-03
        end MATSUM
        begin MOVIE
            OPT 0
        end MOVIE
        begin MPGS
            OPT 0
        end MPGS
        begin NCFORC
            OPT 0
        end NCFORC
        begin NODFOR
            OPT 0
        end NODFOR
        begin NODOUT
            OPT 0
        end NODOUT
        begin RBDOUT
            OPT 0
        end RBDOUT
        begin RCFORC
            OPT 0
        end RCFORC
        begin RWFORC
            OPT 1
            OUT 1E-03
        end RWFORC
        begin SBTOUT
            OPT 0
        end SBTOUT
        begin SECFORC
            OPT 0
        end SECFORC
        begin SLEOUT
            OPT 0
        end SLEOUT
        begin SPCFORC
            OPT 0
        end SPCFORC
        begin SPHOUT
            OPT 0
        end SPHOUT
        begin SSSTAT
            OPT 0
        end SSSTAT
        begin SWFORC
            OPT 0
        end SWFORC
        begin TPRINT
            OPT 0
        end TPRINT
        begin TRHIST
            OPT 0
        end TRHIST
    end database
    begin database_binary database_binary0
        BEAM 0
        DT 5E-03
        LCDT 0
        NPLTC 0
        OPTION 5
    end database_binary database_binary0
    begin database_binary database_binary1
        DT 1.0
        LCDT 0
        OPTION 6
    end database_binary database_binary1
    begin database_binary database_binary2
        DT 1.0
        LCDT 0
        OPTION 7
    end database_binary database_binary2
    begin database_extent
        begin AVS
            Opt 0
        end AVS
        begin BINARY
            BEAMIP 0
            CMPFLG 0
            DECOMP 0
            ENGFLG 1
            EPSFLG 1
            IEVERP 1
            MAXINT 0
            N3THDT 0
            NEIPH 0
            NEIPS 0
            Opt 1
            RLTFLG 1
            SHGE 0
            SIGFLG 1
            STRFLG 1
            STSSZ 0
        end BINARY
        begin MOVIE
            Opt 0
        end MOVIE
        begin MPGS
            Opt 0
        end MPGS
    end database_extent
    begin database_format
        DEFINE 0
    end database_format
    begin database_spring
        DEFINE 0
    end database_spring
    begin database_superplastic
        DEFINE 0
    end database_superplastic
    begin database_tracer
        DEFINE 0
    end database_tracer
end dbase

begin def_solid
    formul 0
    mat0 1
    mat_def 0
    mat_name {}
    write 1
    begin EOS_solid
        include 0
    end EOS_solid
    begin card1
        f1 -1
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card1
    begin card2
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card2
    begin card3
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card3
    begin card4
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card4
    begin card5
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card5
    begin card6
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card6
    begin hg_solid
        include 0
    end hg_solid
    begin sec_solid
        aet 4
        formul 1
        id -1
        opt 0
    end sec_solid
end def_solid

begin title
    title {}
end title

begin def_beam
    cs 2
    formul 1
    mat1 1
    mat_def 0
    mat_name {}
    n3 {0.0 0.0 0.0}
    n3opt 0
    rr 0
    rt 0
    write 1
    begin card1
        f1 -1
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card1
    begin card2
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card2
    begin card3
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card3
    begin card4
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card4
    begin card5
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card5
    begin card6
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card6
    begin sec_beam
        cst 0
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
        formul 1
        id -1
        nsm 0.0
        qr 2
        scoor 0
        shrf 1.0
    end sec_beam
end def_beam

begin define
    DEFINE 0
    begin lCurve_feedback
        DEFINE 0
    end lCurve_feedback
    begin lcurv dummy_for_contacts
        id 4
        lopt 0
        name dummy_for_contacts
        offx 0.0
        offy 0.0
        opt 0
        sfx 1.0
        sfy 1.0
        type 0
        begin point point0
            x 0.0
            y 0.0
        end point point0
        begin point point1
            x 0.2
            y 0.0
        end point point1
    end lcurv dummy_for_contacts
    begin lcurv load_curve_null
        id 1
        lopt 0
        name load_curve_null
        offx 0.0
        offy 0.0
        opt 0
        sfx 1.0
        sfy 1.0
        type 0
        begin point point0
            x 0.0
            y 0.0
        end point point0
        begin point point1
            x 0.2
            y 0.0
        end point point1
    end lcurv load_curve_null
    begin lcurv load_curve_ramped_load
        id 3
        lopt 0
        name load_curve_ramped_load
        offx 0.0
        offy 0.0
        opt 0
        sfx 1.0
        sfy 1.0
        type 0
        begin point point0
            x 0.0
            y 0.0
        end point point0
        begin point point1
            x 0.2
            y 1.0
        end point point1
        begin point point2
            x 1.0
            y 1.0
        end point point2
    end lcurv load_curve_ramped_load
    begin lcurv load_curve_unity
        id 2
        lopt 0
        name load_curve_unity
        offx 0.0
        offy 0.0
        opt 0
        sfx 1.0
        sfy 1.0
        type 0
        begin point point0
            x 0.0
            y 1.0
        end point point0
        begin point point1
            x 0.2
            y 1.0
        end point point1
    end lcurv load_curve_unity
end define
	}
	close $fp
	set fp [open $pref.lsdyna.fbc w]
	foreach f [ic_uns_list_families] {
	    puts $fp "\"$f\""
	}
	close $fp
	set cmd [list $env(ICEM_ACN)/icemcfd/output-interfaces/ls_dyna3d -dom $file_name(domain) -par $pref.lsdyna.par -b $pref.lsdyna.fbc $pref.k]
	mess "Running $cmd\n"
	if [catch {eval exec $cmd} res] {
	    mess "Error: $res\n" red
	} else {
	    mess "Done $res\n"
	}
	set file_name(socket_done_file_name) $pref.k
}

proc set_project_dir {dir} {
    global file_name
    foreach d [array names file_name] {
	    if [string match *_dir $d] {
	        set file_name($d) $dir
	    }
    }
}

proc aie_newProject {{prj_file ""} {force_new 0}} {
    global file_name

    if !$force_new {
        if {[ic_geo_is_loaded] || [ic_uns_is_loaded]} {
            if { [aie_closeProject] == 0 } {return}
        }
    }

    if {$prj_file == ""} {
        set prj_file [tk_getSaveFile \
			  -filetypes {{{Project Files} {.prj}} {{All Files} *}} \
			  -initialdir [pwd] -parent . -title "New Project"]
        if {$prj_file == ""} { return }
        if {[file extension $prj_file] != ".prj"} { set prj_file $prj_file.prj }
    }
    set prj_dir [file dirname $prj_file]
    set_project_dir .
    set file_name(settings) $prj_file
    if {([pwd] != $prj_dir) && ($prj_dir != ".")} {
        if [catch {ic_chdir $prj_dir} res] {
            mess "Error in changing project directory to $res\n"
            return
        } elseif {$file_name(project_dir) != "."} {
            mess "Project directory changed to $file_name(project_dir)\n"
        }
    }

    foreach d [array names file_name] {
        if [string match *_dir $d] { set file_name($d) $prj_dir }
    }
    aie_set_title [file tail [file rootname $prj_file]]
    mess "Created new project $prj_file\n"
}

proc aie_openProject {{prj_file ""}} {
    global tdv_default is_win options beta_mode aie_curveShowFlag file_name fam_visible
    global batch_mode env cart3d_started use_xwindows prev_use_xwindows geo_cad 
    global prism_family_on prism_values prism_extras movie saved_views 

    if {$prj_file != ""} {regsub -all \\\\ $prj_file / prj_file}
    if {[ic_geo_is_loaded] || [ic_uns_is_loaded]} {
	    if {[aie_closeProject] == 0} return
    }

    if {$prj_file == "" || [file isdirectory $prj_file]} {
	    if [file isdirectory $prj_file] {
	        set initialdir $prj_file
	    } else {
	        set initialdir [ pwd ]
	    }
	    set prj_file [tk_getOpenFile -filetypes {{{Project Files} {.prj .wbpj}} {{All Files} *}} \
		    -title "Open Project" -parent . -initialdir $initialdir -defaultextension ".prj" \
		    -allow_nonexistent 1]
	    if {$prj_file == ""} { return }
    }
    if {[file extension $prj_file] != ".prj"} {
        if {[file extension $prj_file] == ".tin"} {
            if [file_is_tetin $prj_file] {
                set tetin_file $prj_file
                set prj_dir [file dirname $prj_file]
                set prj_file "$prj_dir/[file rootname [file tail $prj_file]].prj"
            }
        } elseif {[file extension $prj_file] == ".uns"} {
            if [file_is_domain $prj_file] {
                set domain_file $prj_file
                set prj_dir [file dirname $prj_file]
                set prj_file "$prj_dir/[file rootname [file tail $prj_file]].prj"
            }
        } elseif {[file extension $prj_file] == ".wbpj"} {
            aie_openWBProject $prj_file
            return
        } else {
	        set prj_file $prj_file.prj
	    }
    } elseif $is_win {
        # Confirm is already done on Windows
        set no_confirm 1
    }
    if ![file exists $prj_file] {
	    if ![info exists no_confirm] {
	        if {[tk_dialog .createnew "Create new project" "Create a new project?\n$prj_file" "" -1 Yes No] != 0} {
	    	    if [winfo exists .createnew] { top_destroy .createnew }
	            return
	        }
	    }
	    aie_newProject $prj_file
	    if [info exists tetin_file] {
	        set file_name(tetin) $tetin_file
	        aie_open_geom 0
	    }
	    if [info exists domain_file] {
	        set file_name(domain) $domain_file
	        aie_open_Mesh 0
	    }
        if !$batch_mode { aie_afterStuffLoaded 1 }
        if [ic_geo_is_loaded] { aie_viewInfo geometry }
        if [ic_uns_is_loaded] { ic_uns_print_info summary }
	    return
    }

    catch {array unset prism_family_on}

    if [info exists geo_cad(use_toptol_userset)] {
        unset geo_cad(use_toptol_userset)
    }
    
    catch { unset  movie; unset saved_views }
    set prj_dir [file dirname $prj_file]
    mess "Loading project settings file: $prj_file...\n"
    set fp [open $prj_file r]
    set ::project_file_header ""
    while {[gets $fp line] > 0 } {
        if { [ string match "#*" $line ] } {
            lappend ::project_file_header "[string trimleft $line \#]\n"
        }
    }
    close $fp
    
   # save some parameters before
    global options icon_size1 icon_size2 tdv_control_display_lists tdv_use_opengl_feedback import_model_options map_tetin_sizes
    aie_wb_set_import_defaults
    catch { array unset save_my_options; array unset save_my_options2; array unset save_my_options3; unset save_my_icon_size1; unset save_my_icon_size2 }
    array set save_my_options [array get options]
    if [info exists tdv_control_display_lists] { set save_my_options(tdv_control_display_lists) $tdv_control_display_lists }
    if [info exists tdv_use_opengl_feedback] { set save_my_options(tdv_use_opengl_feedback) $tdv_use_opengl_feedback }
    if {[info exists icon_size1] &&  [info exists icon_size2]} { set save_my_icon_size1 $icon_size1; set save_my_icon_size2 $icon_size2 }
    if [array exists import_model_options] {
        array set save_my_options2 [array get import_model_options]
    }
    if [array exists map_tetin_sizes] {
        array set save_my_options3 [array get map_tetin_sizes]
    }
    uplevel \#0 [list source $prj_file]
    if [info exists save_my_options(n_processors)] { set options(n_processors) $save_my_options(n_processors) }
    if [info exists save_my_options(editor)] { set options(editor) $save_my_options(editor) }
    if [info exists save_my_options(icon_size)] { set options(icon_size) $save_my_options(icon_size) }
    if [info exists save_my_options(user_name)] { set options(user_name) $save_my_options(user_name) }
    if [info exists save_my_options(host_name)] { set options(host_name) $save_my_options(host_name) }
    if [info exists save_my_options(tdv_control_display_lists)] { set tdv_control_display_lists $save_my_options(tdv_control_display_lists) }
    if [info exists save_my_options(tdv_use_opengl_feedback)] { set tdv_use_opengl_feedback $save_my_options(tdv_use_opengl_feedback) }
    if {[info exists save_my_icon_size1] &&  [info exists save_my_icon_size2]} { set icon_size1 $save_my_icon_size1; set icon_size2 $save_my_icon_size2 }
    if [array exists save_my_options3] {
        array set map_tetin_sizes [array get save_my_options3]
    }
    if [array exists save_my_options2] {
        array set import_model_options [array get save_my_options2]
    }
    set options(select_mode) all

    # backward compatibility for meshQuadDEZ
    aie_backward_compatibility

    set use_xwindows $prev_use_xwindows
    set file_name(settings) $prj_file
    set_project_dir [pwd]

    if {([pwd] != $prj_dir) && ($prj_dir != ".")} {
	    if [catch {ic_chdir $prj_dir} res] {
	        mess "Error in changing project directory to $res\n"
	        return
	    } else {
	        foreach p [array names file_name] {
		        if [string match *_dir $p] {
		            set file_name($p) $prj_dir
		        }
	        }
	        if {$file_name(project_dir) != "."} {
		        mess "Project directory changed to $file_name(project_dir)\n"
	        }
	        set file_name(settings) [file tail $file_name(settings)]
	    }
    }

    aie_set_title [file tail [file rootname $prj_file]]

    if {$file_name(tetin) != ""} {
        if [aie_wb2_is_running] {
            if ![ic_wb2_skip_loading] {
                aie_open_geom 0
            }
        } else {
	        aie_open_geom 0
	    }
    }
    if {$file_name(domain) != ""} {
        if [aie_wb2_is_running] {
            if ![ic_wb2_skip_loading] {
                aie_open_Mesh 0
            }
        } else {
	        aie_open_Mesh 0
	    }
    }
    if {$file_name(blocking) != ""} {
        if [aie_wb2_is_running] {
            if ![ic_wb2_skip_loading] {
                aie_open_blocking 0
            }
        } else {
	        aie_open_blocking 0
	    }
    }
    if {$file_name(cart_file) != ""} {
	    aie_open_cart 0
    }
    # This is good to have first because it defines the lcs's used by the bc's
    if {![info exists env(AI_ENV_CFX)] && ($file_name(solver_params) != "") && [file exists $file_name(solver_params)]} {
        if [aie_wb2_is_running] {
            if ![ic_wb2_skip_loading] {
                aie_open_params 0
            }
        } else {
	        aie_open_params 0
	    }
    } else {
	    set file_name(solver_params) [file rootname $prj_file].par
	    set file_name(solver_params_loaded) 1
    }
    if {($file_name(family_boco) != "") || ($file_name(attributes) != "")} {
        if [aie_wb2_is_running] {
            if ![ic_wb2_skip_loading] {
                aie_open_attr 0
            }
        } else {
	        aie_open_attr 0
	    }
    } else {
	    set file_name(family_boco) [file rootname $prj_file].fbc
	    set file_name(family_boco_loaded) 1
	    set file_name(attributes) [file rootname $prj_file].atr
	    set file_name(attributes_loaded) 0
    }

    if !$batch_mode { aie_afterStuffLoaded; busy 1 }
    
    if [ic_geo_is_loaded] {
	    aie_viewInfo geometry
        if [ic_geo_is_modified] { ic_geo_set_modified 0 }
    }
    if [ic_uns_is_loaded] {
	    ic_uns_print_info summary
    }
    if [ic_hex_blocking_loaded] {
        mess "\n--- Blocking Info ---"
	    hex_number_of_blocks_info
    }

    if {[info exists options(temporary_directory)] && $options(temporary_directory) != ""} {
        set tmp_dir $options(temporary_directory)
        if {![file exists $tmp_dir] || ![file isdirectory $tmp_dir]} {
            mess "Warning: the Settings->General->Temporary directory \"$tmp_dir\" does not exist\n" red
            set tmp_dir [ic_temp_dir]
            if {$tmp_dir != "" && [file exists $tmp_dir] && [file isdirectory $tmp_dir]} {
                set options(temporary_directory) $tmp_dir
                mess "Resetting Settings->General->Temporary directory to \"$tmp_dir\"\n" red
            } else {
                mess "Warning: unable to reset \"Settings->General->Temporary directory\"\n" red
            }
        }
    }
    
    if [ic_param_is_modified] { ic_param_set_modified 0 }
    aie_load_prism_params 1
    if !$batch_mode { busy reset }
}

proc aie_openWBProject {{wb_prj_file ""}} {
    global is_win options beta_mode file_name batch_mode env 

    if {$wb_prj_file != ""} {regsub -all \\\\ $wb_prj_file / wb_prj_file}
    if {[ic_geo_is_loaded] || [ic_uns_is_loaded]} {
	    if {[aie_closeProject] == 0} return
    }
    if {$wb_prj_file == "" || [file isdirectory $wb_prj_file]} {
        if [file isdirectory $wb_prj_file] {
            set initialdir $wb_prj_file
        } else {
            set initialdir [pwd]
        }
        set wb_prj_file [tk_getOpenFile -filetypes {{{Workbench Project Files} {.wbpj}} {{All Files} *}} \
            -title "Open Workbench Project" -parent . -initialdir $initialdir -defaultextension ".wbpj" \
            -allow_nonexistent 0]
        if {$wb_prj_file == ""} return
    }

    set cur_pwd [pwd]
    set new_pwd [file dir $wb_prj_file]
    if [expr [file exists $new_pwd] && [file isdirectory $new_pwd]] {
        cd $new_pwd
    } else {
        mess "Path to project $new_pwd not found\n" red
        return
    }
    set wb_prj_file_name [file rootname [file tail $wb_prj_file]]
    set wb_prj_file_dir ${wb_prj_file_name}_files
    
    set ii 0
    set nn ""
    set projects ""
    while 1 {
        foreach aa [glob -nocomplain $wb_prj_file_dir/${nn}*.prj] {
            lappend projects $aa
        }
        incr ii
        append nn "*/"
        if {$ii > 5} break
    }
    if {$projects != ""} {
        if {[llength $projects] > 1} {
            set multi_paths ""
            set i 1
            foreach p $projects {
                append multi_paths "Project $i) $p\n"
                incr i
            }
            mess "This Workbench project file has [llength $projects] associated ICEM CFD projects:\n$multi_paths\n"
            mess "Select one of them\n"
	        set prj_file [tk_getOpenFile -filetypes {{{Project Files} {.prj}} {{All Files} *}} -title "Open associated ICEM CFD Project" -parent . \
		        -defaultextension ".prj" -allow_nonexistent 0 -initialdir [pwd]]
            if {$prj_file == ""} {
                cd $cur_pwd
                return
            }
            aie_openProject $prj_file
            return
        } else {
            if $is_win {
                set projects [win_shortname $projects]
            }
            aie_openProject $projects
            return
        }
    }
    mess "This Workbench project file has no associated ICEM CFD project.  To import Workbench files, please try \"File->Workbench Readers\".\n" red
    cd $cur_pwd
}

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

proc aie_open_journal_file {name} {
    global replay_journal_fp replay_journal_name env batch_mode
    global options

    if $batch_mode return
    if {([info exists env(ICEM_NO_JOURNAL)]) || (!$options(record_journal))} return

    aie_close_journal_file

    if {$name == ""} {
	    set i 0
	    while {[file exists unnamed$i.jrf]} { incr i }
	    set name unnamed$i
    }
    set replay_journal_name [pwd]/$name.jrf
    set nbk 0
    foreach s {1 0} {
	    if $s { set f1 $replay_journal_name.$s } else { set f1 $replay_journal_name }
	    set f2 $replay_journal_name.[expr $s + 1]
	    if [file exists $f1] {
	        if [catch {file rename -force $f1 $f2} res] {
		        mess "Can't rename $f1 to $f2: $res\n" red
		        break
	        }
	        incr nbk
	    }
    }
    if [catch {set replay_journal_fp [open $replay_journal_name w]} res] {
	    mess "Can't write commands to journal file $replay_journal_name: $res\n" red
    } else {
	    mess "Writing commands to journal file $replay_journal_name (saved $nbk backup[expr {($nbk == 1) ? "" : "s"}])\n"
    }
}

proc aie_close_journal_file {} {
    global replay_journal_fp replay_journal_name

    if [info exists replay_journal_fp] {
	    mess "Closing journal file $replay_journal_name\n"
	    catch {close $replay_journal_fp}
	    unset replay_journal_fp
	    unset replay_journal_name
    }
}

proc aie_rename_journal_file {newname prevdir} {
    global replay_journal_name replay_journal_fp

    if ![info exists replay_journal_fp] return

    set nn [pwd]/$newname.jrf
    if {$nn != $replay_journal_name} {
	catch {close $replay_journal_fp}
	unset replay_journal_fp
	set on $replay_journal_name
	if {[file pathtype $on] == "relative"} {
	    set on $prevdir/$on
	}
	if [catch {file rename -force $on $nn} res] {
	    mess "Can't rename $on to $nn: $res\n" red
	    return
	}
	set replay_journal_name $nn
	if [catch {set replay_journal_fp [open $replay_journal_name a]} res] {
	    mess "Can't write commands to journal file $replay_journal_name: $res\n" red
	} else {
	    mess "Renamed journal file to $replay_journal_name\n"
	}
    }
}

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

proc aie_afterStuffLoaded {{home 1}} {
    global AIEnvProduct cut_info

    set ss [string tolower [ic_boco_solver]]
    if {($ss == "") && ($AIEnvProduct == "commonstruct")} { set ss nastran }
    if [bcc_can_convert_bcs $ss $AIEnvProduct] {
	    mess "Translating properties and attributes from \"$ss\" flavor to \"$AIEnvProduct\" flavor.\n"
	    bcc_convert_bcs $ss $AIEnvProduct "" ""
	    bcc_convert_params $ss $AIEnvProduct ""
    }
    aie_create_initial_assemblies
    aie_initialize_tree_props_and_icons
    aie_load_lcs
    if {$cut_info(active) && [ic_uns_is_loaded]} {
       aie_cutplane_set active
       cutPlaneDEZ show
    }
    ::AIEnv::GUIManagement::Tree::RestoreTreeStatus
    aie_update_icons
    if $home { tdv_home current}
    aie_load_last_view
}

proc aie_closeProject {{confirm 1} {nquit 0}} {
    global fam_visible file_name thickness_defined
# following are Ansys & LS-Dyna params global data arrays
    global ansys_param_arrays lsdyna_param_arrays
    global material_data material_type material_tbl_data material_tbl_type
    global material_dpnd_data
    global params_data params_type
    global subcase_data
    global lcs_data
    global prism_parts
    global bc_name_list mat_name_list tbl_name_list param_name_list lcs_name_list
    global project_file_header
    global use_workbench
    
    # Close (if any) children of plot window (may be Toolbox, etc.)  
    # Delete all definitions (if any) in Variables/Virtual vectors/curves.../etc. database
    set clear_cmd "aie_clear_plot_window; ic_vsettings -delete all"    
    
    if {![ic_boco_is_loaded] && ![ic_uns_is_loaded] && ![ic_str_is_loaded] &&
	    ![ic_hex_blocking_loaded] && ![ic_boco_is_loaded] && (![ic_geo_is_loaded] &&
	    ![llength [ic_geo_non_empty_families_except_dormant]]) &&
	    ![ic_cart_is_loaded] && ![ic_param_is_loaded] &&
	    ($file_name(project_dir) == "")} {
	    eval $clear_cmd
	    return 1
	}
    if {!$confirm && [file_needs_save any] && (![info exists use_workbench] || $use_workbench==0)} {
        # In the case of med in Workbench, do not save by default if confirm==0.
	    switch -- [tk_dialog .saveold Save "Save current project first?" \
		    "" -1 Yes No Cancel] {
            -1 { if [winfo exists .saveold] { top_destroy .saveold; return 0 } }
	        0 { aie_saveProject }
	        1 { if {$nquit} {eval $clear_cmd; return 1} }
	        2 { return 0 }
	    }
    }

    if $confirm {
        if [file_needs_save any] {
            switch -- [tk_dialog .saveold Save "Project has changed. Save first before closing?" \
                    "" -1 Yes No Cancel] {
               -1 { if [winfo exists .saveold] { top_destroy .saveold; return 0 } }
                0 { aie_saveProject }
                1 { if {$nquit} {eval $clear_cmd; return 1} }
                2 { return 0 }
            }
        } else {
            switch -- [tk_dialog .cclose Confirm "Close the current project?" \
                    "" -1 Yes No Cancel] {
               -1 { if [winfo exists .cclose] { top_destroy .cclose; return 0 } }
                0 { if {$nquit} {eval $clear_cmd; return 1} }
                1 { eval $clear_cmd; return 1 }
                2 { return 0 }
            }
        }
    }
    if [ic_boco_is_loaded] { aie_close_attr 0 1 }
    if {[ic_uns_is_loaded] || [ic_str_is_loaded]} { aie_close_Mesh 0 1 }
    if [ic_hex_blocking_loaded] { aie_close_blocking 0 1 }
    if [ic_cart_is_loaded] { aie_close_cart 0 1 }
    if [ic_geo_is_loaded]  { 
       aie_close_geom 0 1
    } else {
       ic_unload_tetin
       ic_empty_tetin
    }
    # do this last so the families go away
    aie_close_params 0
    # clear thickness if exist
    if {$thickness_defined} {
       catch {ic_uns_thickness clear}
       set thickness_defined 0
    }
    # clear BC list
    catch {unset bc_name_list}
    # clear Ansys & LS-Dyna params data between two projects
	catch {unset ansys_param_arrays}
	catch {unset lsdyna_param_arrays}
    # clear Materials and Tables
    aie_clear_materials_tables
    # clear Parameters
    aie_clear_params
    # clear LCS
    ic_csystem_display all 0
    #aie_set_lcs_current type global
    catch {
        foreach lcname [ic_csystem_list] {
	        ic_csystem_delete $lcname
        }
    }
    catch {
       foreach ch [ic_param_list_children :Local_Coordinates] {
          ic_param_delete_node $ch
       }
    }
    catch {unset lcs_data}
    catch {unset fam_visible}
    catch {close_write_file}

    global tdv_default
    if {[info exist tdv_default] && [winfo exist $tdv_default]} {
       set win $tdv_default
       global anno_data
       if [info exist anno_data(gm,0,$win)] {
          set gm $anno_data(gm,0,$win)
          if {[info command $gm] != ""} {
             foreach a [$gm list] {
                if {[$gm isvalid $a] != ""} {
                   $gm remove $a
                }
             }
          }
          set anno_data($win,2d_annos) ""
          set anno_data(list,0,$win) ""
       }
    }

    foreach p [array names file_name] {
	    if {[string match *_dir $p] && ($file_name($p) == "")} {
	        set file_name($p) .
	    }
    }
    
    set_project_dir ""
    set file_name(settings) ""
    aie_set_title ""
    if [ic_geo_is_modified] { ic_geo_set_modified 0 }
    if [ic_param_is_modified] { ic_param_set_modified 0 }
    aie_wb_set_import_defaults
    aie_clear_dez
    ::AIEnv::GUIManagement::Tree::clear everything

    aie_close_journal_file
    aie_update_lcs

    # clean up the GUI a bit
    catch { form_kill .sel_parts }
    global select_action movie saved_views
    catch { unset  movie; unset saved_views }
    set select_action cancel
    catch { set prism_parts "" }
    catch { set project_file_header "" }
    banner ""
    eval $clear_cmd
    return 1
}

proc aie_save_geom {{ask 0} {ver 0} {wb2 0}} {
    global file_name options batch_mode

    set v4 0
    set v10 0
    set ft $file_name(tetin)
    if {$ft == "" || $ask} {
        switch $ask {
            0 - 1 {
                set title "Save all geometry"
            }
            2 {
                set title "Save only visible geometry"
                set ft ""
            }
            3 {
                set title "Save only some parts"
                set ft ""
            }
        }
        if {$ver == 4} {
            append title " (version 4 mode)"
            set v4 1
        } elseif {$ver == 10} {
            append title " (version 10.0 mode)"
            set v10 100
        } elseif {$ver == 13} {
            append title " (version 13.0 mode)"
            set v10 13
        } elseif {$ver == 14.5} {
            append title " (version 14.5 mode)"
            set v10 145
        } elseif {$ver == 15} {
            append title " (version 15.0 mode)"
            set v10 150
        } elseif {$ver == 16} {
            append title " (version 16.0 mode)"
            set v10 160
        } elseif {$ver == 18} {
            append title " (version 18.0 mode)"
            set v10 180
        }
        set ft [tk_getSaveFile -initialdir $file_name(project_dir) -initialfile $ft -title $title  -parent . -filetypes {{{Geometry Files} {.tin .tin.gz} } {{All Files} *}}]
        if {$ft == ""} {return 1}
        if {[file extension $ft] == ".gz"} {
            set fr [file root $ft]
            if {[file extension $ft] != ".tin"} {
                set ft $fr.tin.gz
            }
        } elseif {[file extension $ft] != ".tin"} {
            set ft $ft.tin
        }
    } else {
        if {$ver == 4} {
            set v4 1
        } elseif {$ver == 10} {
            set v10 100
        } elseif {$ver == 13} {
            set v10 130
        } elseif {$ver == 14.5} {
            set v10 145
        } elseif {$ver == 15} {
            set v10 150
        } elseif {$ver == 16} {
            set v10 160
        } elseif {$ver == 18} {
            set v10 180
        }
    }

    # don't save material points unless attached to a body
    aie_delete_materials
    # don't save empty parts
    aie_delete_empty_parts
    if [info exists options(clear_undo)] {
        set clear_undo $options(clear_undo)
    } else {
        set clear_undo 1
    }
    switch $ask {
        0 - 1 {
            ic_save_tetin $ft 0 $v4 "" "" $v10 0 $clear_undo
        }
        2 {
            ic_save_tetin $ft 1 $v4 "" "" $v10 0 $clear_undo
        }
        3 {
            set fams [select_families 0 1 0]
            if {$fams == ""} { return "" }
            ic_save_tetin $ft 0 $v4 $fams "" $v10 0 $clear_undo
        }
    }
    set file_name(tetin) $ft
    if [aie_wb2_is_running] {
        if {$wb2 && !$batch_mode} {
            ic_socket_send_to_wb2 "wb_status 1"
        }
    }
    return $file_name(tetin)
}

proc aie_saveas_geom {} {
    aie_save_geom 1
}

proc aie_import_parameters {{ask 1} {ft ""}} {
    global file_name map_tetin_sizes is_win env 
    
    if ![file isdirectory $file_name(project_dir)] { set_project_dir . }
    if {$ft == "" || $ask} {
	    set ft $file_name(tetin)
	    if {(![file isfile $file_name(tetin)]) || $ask} {
	        set ft [tk_getOpenFile -initialdir $file_name(project_dir) -filetypes {{{Geometry Files} {.tin}} {{All Files} *}} \
			    -title "Open Parameter Geometry File" -initialfile [file tail $ft] -multiple 1 -parent .]
	        if {$ft == ""} return
	    } else {
	        if {$ft == ""} return
	        set ft [list $ft]
	    }
    }
    set ft2 ""
    set here [pwd]/
    foreach f $ft {
	    if [string match $here* $f] {
	        set f [string range $f [string length $here] end]
	    }
	    lappend ft2 $f
    }
    set ft $ft2
    aie_clear_dez
    
    set what 0
    set what_type ""
    if $map_tetin_sizes(global) { append what_type "Global mesh params "; set what [expr {$what + 1}] }
    if $map_tetin_sizes(family) { append what_type "+ Part mesh params "; set what [expr {$what + 2}] }
    if $map_tetin_sizes(ppoint) { append what_type "+ Point parts "; set what [expr {$what + 4}] }
    if $map_tetin_sizes(pcurves) { append what_type "+ Curve parts "; set what [expr {$what + 8}] }
    if $map_tetin_sizes(mcurves) { append what_type "+ Curve mesh params "; set what [expr {$what + 16}] }
    if $map_tetin_sizes(psurfaces) { append what_type "+ Surface parts "; set what [expr {$what + 32}] }
    if $map_tetin_sizes(msurfaces) { append what_type "+ Surface mesh params "; set what [expr {$what + 64}] }
    if $map_tetin_sizes(thincuts) { append what_type "+ Thincuts "; set what [expr {$what + 128}] }
    if $map_tetin_sizes(densities) { append what_type "+ Densities volume "; set what [expr {$what + 256}] }
    if $map_tetin_sizes(subsets) { append what_type "+ Subsets "; set what [expr {$what + 512}] }
    if $map_tetin_sizes(mpoint) { append what_type "+ Material points"; set what [expr {$what + 1024}] }
    if {$what == 0} {
        mess "Nothing selected in \"Settings->Geometry Options->Import Parameters from Tetin file\"\n" red
        return
    }
    mess "Importing parameters \"$what_type\"\n"
    
    foreach f $ft {
        if [catch {ic_geo_map_tetin_sizes $ft $what} res] {
	        mess "Error: $res\n" red
	    } else {
	        mess "Imported parameters from geometry file $ft\n"
	    }
    }

    aie_afterStuffLoaded 0
    aie_init_geom_subsets
    ic_gui_update
}

proc aie_open_geom {{ask 1} {ft ""} {wb2 0}} {
    global file_name tdv_default is_win env aie_ShowCurveAttachment geo_cad
    global aie_geoTypeVis fam_visible batch_mode units_message wb1_options

    # tetin file selection via "Send to" command
    if {$file_name(project_dir) == "" && $ft != "" && $is_win} {
        set short_ft [win_shortname [lindex $ft 0]]
        if {[file isfile $short_ft] && ![file isdirectory $short_ft]} {
            set short_dir [file dirname $short_ft]
            if [file isdirectory $short_dir] {
                set_project_dir $short_dir
            }
        }
    }
    if ![file isdirectory $file_name(project_dir)] { set_project_dir . }

    if {$ft == ""} {
	set ft $file_name(tetin)

	if {(![file isfile $file_name(tetin)]) || $ask} {
	    set ft [tk_getOpenFile -initialdir $file_name(project_dir) -filetypes {{{Geometry Files} {.tin .tin.gz}} {{All Files} *}} \
			-title "Open Geometry File" -initialfile [file tail [lindex $ft 0]] -multiple 1 -parent .]
	    if {$ft == ""} return
	} else {
	    if {$ft == ""} return
	        set ft [list $ft]
	    }
    }
    if {$file_name(project_dir) == "." && ![ic_geo_is_loaded] && $file_name(settings) == ""} {
        set prj_file_new [win_shortname [lindex $ft 0]]
        if {[file isfile $prj_file_new] && ![file isdirectory $prj_file_new]} {
            set prj_dir [file dirname $prj_file_new]
            if [file isdirectory $prj_dir] {
                set prj_file "$prj_dir/[file rootname [file tail $prj_file_new]].prj"
            }
        }
        if {[info exists prj_file] && ![file exists $prj_file]} {
            switch -- [tk_dialog .createnew "Create new project" "Create a new project?\n$prj_file" "" -1 Yes No] {
               -1 { if [winfo exists .createnew] { top_destroy .createnew; return } }
                0 {
                    set_project_dir $prj_dir
                    set file_name(settings) $prj_file
                    if ![aie_wb2_is_running] {
                        cd [file dir $file_name(settings)]
                    }
                }
            }	    
	    }
    }
    # Filter out the prefix ...
    set ft2 ""
    set here [pwd]/
    foreach f $ft {
	    if [string match $here* $f] {
	        set f [string range $f [string length $here] end]
	        set ft3($f) 1
	    }
	    lappend ft2 $f
    }
    set ft $ft2
    regsub -all \\\\ $ft2 / ft2
    set keep_name 1
    if [ic_geo_is_loaded] {
	    set opt [tk_dialog .tetinOverwrite "Geometry Exists" "Geometry Already Exists" "" 1 "Merge" "Replace" "Cancel"]
	    switch -- $opt {
	        -1 { if [winfo exists .tetinOverwrite] { destroy .tetinOverwrite; return } }
	        0 {
	            set keep_name 0
	            set merge_tetin_files 1
	        }
	        1 {
		        aie_close_geom 0
		        mess "   --- Unloading existing geometry\n"
	        }
	        2 { return }
	    }
    }
    set nfiles [llength $ft]
    if {$nfiles > 1} {
	    set keep_name 0
	    set opt [tk_dialog .tetinMerge "Merge multiple geometry files?" "You have selected $nfiles geometry files.  If you load them all,\
		    they will be concatenated into a single geometry file." "" 0 "Merge files" "Cancel"]
		switch -- $opt {
            1 - -1 {
		        if [winfo exists .tetinMerge] { destroy .tetinMerge }
		        return
		    }
		    default {
		        set merge_tetin_files 1
		    }
        }
    }
    tdv_active 0
    set do_home [expr ![ic_geo_is_loaded] && ![ic_uns_is_loaded]]
    foreach tin $ft {
	    regsub -all \\\\ $tin / tin
	    if ![info exists ft3($tin)] {
	        mess "Loading geometry file \"$tin\"\n"
	    } else {
	        mess "Loading geometry file \"[pwd]/$tin\"\n"
	    }
	    if [catch {ic_load_tetin [list $tin]} res] {
	        busy reset
	        mess "$res\n" red
	        busy reset
	    } elseif $res {
	        set loaded 1
	    }
    }
    
    if [info exists env(AI_ENV_IN_WB1)] {
        if [info exists wb1_options(subset2parts)] {
            mess "Creating parts from subsets...\n" blue
            set deleted_subsets [ic_geo_subset_names_to_parts]
            if !$batch_mode {
                foreach s $deleted_subsets  {       
                    catch { ::AIEnv::GUIManagement::Tree::DeleteGroup geom_subset $s 0 }
                }
            }
        }
    }
    
    if ![info exists loaded] {tdv_active 1; return}
    if $keep_name {
	    set file_name(tetin) [lindex $ft 0]
    	regsub -all \\\\ $file_name(tetin) / file_name(tetin)
    } else {
	    set file_name(tetin) ""
    }
    set file_name(tetin_loaded) 1
    # loops are not handled
    set nloops [llength [ic_geo_get_objects loop]]
    if { $nloops > 0} {
        if [info exists env(QUAD_DEBUG)] {
            mess "Geometry file contains $nloops entities of type \"Loop\".\n" red
        } else {
            set mess "Geometry file contains entities of type Loop which are not supported. Do you want them to be deleted?"
            set no [tk_dialog .delloops "Delete loops" $mess "" -1 "Yes" "No"]
            if [winfo exists .delloops] { destroy .delloops }
            if !$no {
                ic_delete_geometry loop all ""
                mess "Deleted $nloops loops\n"
            }
        }
    }
    # Create Bodies for material points unattached to body
    aie_build_volumes

	# Move points, curves, surfaces from ORFN !!!
	aie_geo_move_from_orfn_non_material
    if $ask {
	    # If we are just loading up a new tetin file make sure that all
	    # the initial families get assigned to assemblies
	    aie_afterStuffLoaded $do_home
	    aie_viewInfo geometry
    }
    # Note: next command is too slow for large models; may be optimized --VG
    aie_initGeoVis
    if [ic_geo_is_modified] { ic_geo_set_modified 0 }
    # To avoid DEZ dependencies
    aie_clear_dez
	# unset or set 0 toptol_userset
	if ![info exists geo_cad(use_toptol_userset)] {
        set ::geo_cad(toptol_userset) 0
    } else {
        set ::geo_cad(toptol_userset) 1
    }
    # Make sure we have at least Global
    if !$ask { aie_load_lcs }
    aie_update_icons geom
    aie_init_geom_subsets
    aie_create_parts_in_tree_if_needed 
    if $do_home { tdv_home $tdv_default }
    if [aie_wb2_is_running] {
        if {$wb2 && !$batch_mode} {
            ic_socket_send_to_wb2 "wb_status 1"
        }
    }
    tdv_active 1
    set units [ic_geo_get_units 1]
    if {$units != ""} {
        set units_message "Units: [ic_geo_get_units 1] "
    } else {
        set units_message ""
    }
    ic_undo_start
}

proc aie_close_geom {{confirm 1} {skip 0}} {
    global file_name fam_visible geo_cad units_message

    if {![ic_geo_is_loaded] && ![llength [ic_geo_non_empty_families_except_dormant]]} {
	    mess "No geometry is loaded\n" red
	    return
    }
    if {([file_needs_save tetin]) && ($confirm)} {
	    switch -- [tk_dialog .savetetin "Save Geometry" "Do you want to save the current Geometry?" "" -1 Yes No] {
		    1 - -1 {
		        if [winfo exists .savetetin] { destroy .savetetin }
		    }
		    0 {
		        set file_name(tetin) [file join $file_name(project_dir) [file tail $file_name(tetin)]]
		        aie_save_geom
		    }
	    }
    }
    # reset to global
    ic_csystem_display all 0
    aie_set_lcs_current type global
    # must do this before unloading tetin, so we can get data from it. --jka
    aie_connectors_unload

    # If blocking loaded save and restore hex families
    if [ic_hex_blocking_loaded] {
        set hex_fams [ic_hex_list_families]
        mess "Warning: geometry closed, but blocking still loaded, the blocking file relies on the geometry file,\
            separating the two may require reassociation, regrouping, etc.\n" red
    }
    ic_unload_tetin
    set file_name(tetin) ""
    ic_empty_tetin ;# we always need a projlib to make stuff work
    # Reset display variables
    set fam_active ""
    foreach f [ic_uns_list_families] {
	    lappend fam_active $f
    }
    foreach f [ic_hex_non_empty_families] {
	    lappend fam_active $f
    }

    if [info exists fam_visible] {
	    foreach f [array names fam_visible] {
	        if {[lsearch -exact $fam_active $f] < 0} {
	            if ![ic_hex_subset_named_selection $f] {
		            unset fam_visible($f)
		        }
	        }
	    }
    }
    ::AIEnv::GUIManagement::Tree::clear geom
    if [ic_geo_is_modified] { ic_geo_set_modified 0 }
    aie_clear_dez
    aie_update_icons geom
    set geo_cad(toptol_userset) 0
    set units_message ""
    # VG:40645
    set ::AIEnv::DEZ::repairGeomDEZ::topotol ""
	set ::AIEnv::DEZ::repairGeomDEZ::topotol_single ""
	if [info exists geo_cad(use_toptol_userset)] {
        unset geo_cad(use_toptol_userset)
    }
    # Recreate hexa families
    if [ic_hex_blocking_loaded] {
	    if [info exists hex_fams] {
	        foreach fam $hex_fams {
                aie_new_part $fam
	        }
	    }
	    aie_create_vorfn 1
    }
    
    # clear empty parts
    if !$skip { aie_delete_empty_parts 0 }
    if !$skip { aie_update_lcs }
    ic_undo_clear
}

proc aie_open_Mesh {{ask 1} {move_from_orfn ""} {opt ""} {fm ""} {wb2 0}} {
    global file_name fam_visible quality_metric_created
    global tdv_default AIEnvProduct options batch_mode

    # VG 60982 07/24/07 : additional control mesh dimension, see main_menus_first.ttkrf 
    set load_uns_dim 3
    if {$opt == "only_surface"} {
        set load_uns_dim 2
        set opt ""
    }

    if ![file isdirectory $file_name(project_dir)] { set_project_dir . }
    if {$fm == ""} {
	    set fm [list $file_name(domain)]
	    set has_multiblock [expr {[glob -nocomplain $file_name(project_dir)/domain.*] != ""}]
	    if {$has_multiblock && ![file exists $file_name(project_dir)/Multiblock]} {
	        set fp [open $file_name(project_dir)/Multiblock w]; close $fp
	        if ![file isfile $file_name(domain)] {
	            set fm Multiblock; set ask 1
	        }
	    }
	    if {(![file isfile $file_name(domain)]) || $ask} {
	        if {$fm != "" && ([llength $fm] != 1 || [lindex $fm 0] != "")} {
		        if {$fm == "Multiblock"} {
		            set fm [tk_getOpenFile -initialdir $file_name(project_dir) -filetypes {{{All files} *} {{Mesh Files} {*.uns *Multiblock}}} \
			            -title "Open Mesh File" -initialfile [file tail [lindex $fm 0]] -multiple 1 -parent .]
		        } else {
		            set fm [tk_getOpenFile -initialdir $file_name(project_dir) -filetypes {{{Mesh Files} {*.uns *Multiblock *.msh}} {{All files} *}} \
			            -title "Open Mesh File" -initialfile [file tail [lindex $fm 0]] -multiple 1 -parent .]
		        }
	        } else {
		        set fm [tk_getOpenFile -initialdir $file_name(project_dir) -filetypes {{{Mesh Files} {*.uns *Multiblock *.msh}} {{All files} *}} \
			        -title "Open Mesh File" -multiple 1 -parent .]
	        }
	    }
        if {$fm == ""} {return 0}
    }
    if [regexp Multiblock [file tail $fm]] {	
        set file_name(domain) [join $fm]
        set do_home [expr ![ic_geo_is_loaded] && ![ic_uns_is_loaded]]
        aie_open_str_mesh 0 $do_home
        return 0
    } elseif {([ic_str_domainfile_dimension $fm] != "-1") && ([file extension $fm] != "uns")} {
        set file_name(domain) [join $fm]
        aie_open_str_superdomain_mesh
        return 0
    }
    set keep_name 1
    set ext [file extension $fm] 
    if [ic_str_is_loaded] {
        if { $opt == "" } {
            set opt [tk_dialog .unsOverwrite "Mesh Exists" "This will unload the existing structured mesh; \
                Do you want to continue loading?" "" 1 "Yes" "No" ]
            switch -- $opt {
                0 { ic_unload_mesh }
                1 - -1 {
                    if [winfo exists .unsOverwrite] { destroy .unsOverwrite }
                    return 0
                }
            }
        }
    }
    if [ic_uns_is_loaded] {
        if { $opt == "" } {
            if {$ext == ".msh"} {
                set opt [tk_dialog .unsOverwrite "Mesh Exists" "Mesh Already Exists" "" 0 "Replace" "Cancel" ]
            } else {
                set opt [tk_dialog .unsOverwrite "Mesh Exists" "Mesh Already Exists" "" 1 "Merge" "Replace" "Cancel" ]
            }
        }
        if {$ext == ".msh"} {
            switch -- $opt {
                -1 {
                    if [winfo exists .unsOverwrite] { destroy .unsOverwrite }
                    return 0
                }
                0 { aie_close_Mesh 0; mess "   --- Unloading existing mesh\n" }
                1 { return 0 }
            }
        } else {
            switch -- $opt {
                -1 {
                    if [winfo exists .unsOverwrite] { destroy .unsOverwrite }
                    return 0
                }
                0 { set keep_name 0 }
                1 { aie_close_Mesh 0; mess "   --- Unloading existing mesh\n" }
                2 { return 0 }
            }
        }
    }

    set nfiles [llength $fm]
    if {$nfiles > 1} {
	    set keep_name 0
	    set opt [tk_dialog .unsMerge "Merge multiple mesh files?" \
		    "You have selected $nfiles mesh files.  If you load them all, they will be concatenated into a single mesh file." \
		    "" 0 "Merge files" "Cancel"]
		    switch -- $opt {
		    1 - -1 {
		        if [winfo exists .unsMerge] { destroy .unsMerge }
		        return 0
		    }
		}
    }

    if {$ext == ".msh"} {
        global backend_info
        set backend_info(fluent) { Fluent readfluent fluentinfo }
        mess "Loading fluent mesh file $fm\n" blue
        if [catch { aie_mesh_import_from_result fluent "Fluent cas" $fm } msg] {
            mess "Failed to load fluent mesh file $fm\n" red
            ic_rfint_re_delete
            ic_unload_mesh 1
            busy reset
            return 0
        }
        ic_gui_update
        set file_name(domain_loaded) 1
        catch { unset file_name(domain_saved) }
        catch { unset quality_metric_created }
        if [aie_wb2_is_running] {
            if {$wb2 && !$batch_mode} {
                ic_socket_send_to_wb2 "wb_status 2"
            }
        }
        return 1
    }
    
    tdv_active 0
    set do_home [expr ![ic_geo_is_loaded] && ![ic_uns_is_loaded]]
    if [info exists options(auto_fix_uncovered_faces)] {
        if $options(auto_fix_uncovered_faces) {  
            set checko 1
        } else {
            set checko 0 
        }
    } else {
        set checko 1
    }
    # maybe we want to disable this?  Don't know.
    if {$AIEnvProduct == "fea2.0" && $checko != 0} { set checko 2 }
    InitUnsMeshDisplaySettings
    ic_undo_start
    
    set fm2 ""
    set here [pwd]/
    foreach f $fm {
        if [string match $here* $f] {
	        set f [string range $f [string length $here] end]
	    }
	    lappend fm2 $f
    }
    regsub -all \\\\ $fm2 / fm2
    if {$fm2 != ""} { set fm $fm2 }
    set is_ok [ic_uns_load $fm $load_uns_dim 0 "" $checko]
    # set tdv_active
    tdv_active 1
    if !$is_ok {
	    mess "Error in opening Mesh file.\n" red
        busy reset
        ic_unload_mesh
        return 0
    }
    if $keep_name {
        set file_name(domain) [lindex $fm 0]
        regsub -all \\\\ $file_name(domain) / file_name(domain)
    } else {
        set file_name(domain) ""
    }
    set file_name(domain_loaded) 1
    catch { unset file_name(domain_saved) }
    if {$move_from_orfn != ""} {
        ic_geo_new_family $move_from_orfn
        ic_uns_move_family_elements ORFN $move_from_orfn
    }
    catch { unset quality_metric_created }
    aie_after_open_mesh $ask $do_home
    if [aie_wb2_is_running] {
        if {$wb2 && !$batch_mode} {
            ic_socket_send_to_wb2 "wb_status 2"
        }
    }
    return 1
}

proc aie_after_open_mesh {ask home} {
    global fam_visible volume_select surface_select
    global last_fvals last_tvals plot_window
    
    catch { unset last_fvals; unset last_tvals }
    aie_initial_unsmesh_visibility $home 0
    aie_update_parts_in_tree_if_needed 1
    aie_init_mesh_subsets
    if $ask {
        # If we are just loading up a new mesh make sure that all
        # the initial families get assigned to assemblies
        aie_afterStuffLoaded $home
        ic_uns_print_info summary
    } else {
        aie_updateMeshVis
    }
    aie_clear_dez
    aie_update_icons mesh
    foreach p [aie_list_parts 0] {
        if ![::AIEnv::GUIManagement::Tree::GroupExists part $p] continue
        if {[info exists fam_visible($p)] && !$fam_visible($p)} {
            ::AIEnv::GUIManagement::Tree::NodeVisibleStatus part $p -1
        }
    }
    if [ic_uns_is_loaded] {
        if {[info exists plot_window] && [winfo exists $plot_window.graph]} {
            aie_delete_histogram 1
        }
    }
    foreach t [array names volume_select] { set volume_select($t) 1 }
    foreach t [array names surface_select] { set surface_select($t) 1 }
    tdv_active 1
}

proc aie_open_str_mesh {{ask 1} {home 1}} {
    global file_name fam_visible tdv_default

    set fm $file_name(domain)
    if [ic_uns_is_loaded] {
        set opt [tk_dialog .strOverwrite "Unstructured Mesh Exists" "This will unload the existing unstructured mesh; \
            Do you want to continue loading?" "" 1 "Yes" "No" ]
        switch -- $opt {
            -1 { 
                if [winfo exists .strOverwrite] { destroy .strOverwrite }
                return
            }
            0 { ic_unload_mesh }
            1 { return }
        }
    }

    if [ic_str_is_loaded] {
        set opt [tk_dialog .strOverwrite "Structured Mesh Exists" "Structured mesh already exists" "" 1 \
            "Merge" "Replace" "Cancel" ]
        switch -- $opt {
            -1 { 
                if [winfo exists .strOverwrite] { destroy .strOverwrite }
                return
            }
            1 { aie_close_Mesh 0 }
            2 { return }
        }
    }

    if ![file isdirectory $file_name(project_dir)] {set_project_dir .}

    if {(![file isfile $fm]) || $ask == 1} {
	set fm [tk_getOpenFile -initialdir $file_name(project_dir) -filetypes {{{Unstructured Mesh Files} {.uns}} \
        {{Structured Mesh Files} {.Multiblock}} {{All files} *}} -initialfile [file tail $fm] -parent .]

    }
    if {$fm == ""} return

    set dir [file dir $fm]
    if {[file tail $fm] == "Multiblock"} {
        set topo_mulcad_out "$dir/topo_mulcad_out.top"
        set family_topo "$dir/family_topo.fto"
        set domain "$dir/domain"
        set subface_proj "$dir/subface_proj"
    } else {
        set prj [file root [file tail $fm]]
        set topo_mulcad_out "$dir/$prj.top"
        set family_topo "$dir/$prj.fto"
        set domain "$dir/$prj.domain"
        set subface_proj "$dir/$prj.spr"
    }
    InitStrMeshDisplaySettings
    ic_undo_start
    if [catch {ic_load_struct $domain $topo_mulcad_out $family_topo $subface_proj} res] {
        mess "Error in opening structured mesh file; $res\n" red
        busy reset
        return
    } else {
        if ![ic_str_is_loaded] {
            mess "Error in opening structured mesh file\n" red
            busy reset
            return
        }
        set file_name(domain_loaded) 1
        set file_name(domain) [file tail $fm]
        set file_name(domains_dir) $dir
        set file_name(mesh_dir) $dir
        set file_name(topo_mulcad_out) $topo_mulcad_out
        set file_name(family_topo) $family_topo
        set file_name(subface_proj) $subface_proj
    }

    if {$ask || ![ic_geo_is_loaded]} {
	    # If we are just loading up a new tetin file make sure that all
	    # the initial families get assigned to assemblies
        aie_afterStuffLoaded
        aie_create_parts_in_tree_if_needed
    }
    aie_initial_strmesh_visibility $home 
}

proc aie_open_str_superdomain_mesh {} {
    global file_name 

    set fm $file_name(domain)
    if {$fm == ""} return

    if [ic_uns_is_loaded] {
        set opt [tk_dialog .strOverwrite "Unstructured Mesh Exists" "This will unload the unstructured existing mesh; \
            Do you want to continue loading?" "" 1 "Yes" "No" ]
        switch -- $opt {
            -1 { 
                if [winfo exists .strOverwrite] { destroy .strOverwrite }
                return
            }
            0 { ic_unload_mesh }
            1 { return }
        }
    }

    if { [ic_str_is_loaded] } {
        set opt [tk_dialog .strOverwrite "Structured Mesh Exists" "Structured mesh already exists" \
            "" 1 "Replace" "Cancel" ]
        switch -- $opt {
            -1 { 
                if [winfo exists .strOverwrite] { destroy .strOverwrite }
                return
            }
            0 { aie_close_Mesh 0 }
            1 { return }
        }
    }

    if ![file isdirectory $file_name(project_dir)] {set_project_dir .}

    InitStrMeshDisplaySettings
    ic_undo_start
    set dir [file dir $fm]
    set super [file rootname [file tail $fm]]
    set domain "$dir/$super"
    if [catch {ic_load_struct $domain "" "" ""} res] {
        mess "Error in opening mesh file; $res\n" red
        busy reset
        return
    } else {
        if ![ic_str_is_loaded] {
            mess "Error in opening mesh file\n" red
            busy reset
            return
        }
        set file_name(domain_loaded) 1
        set file_name(domain) [file tail $fm]
        set file_name(domains_dir) $dir
        set file_name(topo_mulcad_out) ""
        set file_name(family_topo) ""
        set file_name(subface_proj) ""
    }

    foreach t "subface edge vertex" {
        foreach n [ic_str_list_entities $t] {
            set info [ic_str_get_topo_info $t $n 0]
            if {[lindex [lindex $info 0] 2] == ""} {
                ic_str_change_family $t $n DEFAULT_[string toupper $t]
            }  
        }
    }
    aie_afterStuffLoaded
    aie_create_parts_in_tree_if_needed
    aie_initial_strmesh_visibility 1
}

proc aie_initial_unsmesh_visibility {{home 1} {update 1}} {
    global aie_meshTypeVis aie_meshStyle tdv_default beta_mode options draw_too_many_last_count

    set aie_meshTypeVis(shell) 2
    set tots 0
    foreach st {TRI_3 QUAD_4 TRI_6 QUAD_8 QUAD_9} {
	    incr tots [ic_count_elements $st]
    }
    set too_many 0
    if !$tots {
	    set aie_meshTypeVis(line) 2
    } elseif {[info exists options(uns_warn_user_if_display)] && \
               ($options(uns_warn_user_if_display) != 0 && $options(uns_warn_user_if_display) != "" && \
               $tots > $options(uns_warn_user_if_display))} {
        if {![info exists draw_too_many_last_count] || ($tots > $draw_too_many_last_count)} {
	    if ![tk_dialog .toomany_elements "Too many elements" "There are $tots 2-D elements. \
                                          Display them?" "" -1 "Don't display" "Display"] {
                catch { unset draw_too_many_last_count }
	        set aie_meshTypeVis(shell) 0
	        set too_many 1
	    } else {
                if [winfo exists .toomany_elements] { destroy .toomany_elements }
                # Make sure we don't get asked that question too many times
                set draw_too_many_last_count $tots
            }
        }
    }
    set aie_meshStyle(Wire) 1
    
    foreach i {tri quad} { set aie_meshTypeVis($i) $aie_meshTypeVis(shell) }
    foreach i {tetra hexa pyra penta} { set aie_meshTypeVis($i) $aie_meshTypeVis(volume) }
    
    if !$too_many {
        foreach i {node line tri quad hexa pyra penta tetra} {
            set aie_meshTypeVis($i) [aie_get_tree_display_options $i]
        }
    }    
    
    # reset line visibility if no shell mesh is present.
    if !$tots {
	    set aie_meshTypeVis(line) 2
    }    

    if $update {
	    aie_updateMeshVis
    }
    if $home {tdv_home $tdv_default}
}

proc aie_initial_strmesh_visibility {{home 1}} {
    global tdv_default str_option str_type_visible

    foreach type {domain subface edge vertex} {
        set str_type_visible($type) 0
    }
    set str_type_visible(domain) 1
    set str_type_visible(subface) 1
    set str_option(domain,outlines) 1
    set str_option(domain,simplify) 0
    disp_set_option domain
    disp_set_option subface
    disp_change_overall_visible domain
    disp_change_overall_visible subface
    update_struct_visibility
    update_str_visible

    ::AIEnv::GUIManagement::Tree::UpdateStrMeshVisibility
    if $home {tdv_home $tdv_default}

    # To avoid DEZ dependencies
    aie_clear_dez
    aie_create_parts_in_tree_if_needed
    aie_update_parts_in_tree_if_needed
    aie_update_icons mesh
    ::AIEnv::GUIManagement::Tree::Parts show
}

proc aie_save_Mesh {{only_types ""} {only_fams ""} {wb2 0}} {
    global file_name prism_mesh_loaded batch_mode env wb1_options

    if [ic_str_is_loaded] {
        aie_save_strMesh
        return
    }
    set fm $file_name(domain)
    if {$fm == ""} {
        aie_save_Meshas
    } else {
        if {$prism_mesh_loaded && [file exists $fm] && ![aie_wb2_is_running]} {
            switch -- [tk_dialog .overwritedom "Overwrite Mesh" "This will overwrite the previously saved mesh.  Do you want to continue saving?" "" -1 Yes No] {
			    1 - -1 {
			        if [winfo exists .overwritedom] { destroy .overwritedom }
			        return
			    }
			    0 { }
			}
        }
        if ![aie_wb2_is_running] {
            if [file exists $fm] {
                mess "Moving $fm to $fm.bak\n"
                ic_rename $fm $fm.bak
            }
        }
        aie_renumber_if_necessary
        set fm2 ""
        set here [pwd]/
	    if [string match $here* $fm] {
	        set fm2 [string range $fm [string length $here] end]
	        regsub -all \\\\ $fm2 / fm2
        }
        if {$fm2 != ""} { set fm $fm2 }
        if [info exists env(AI_ENV_IN_WB1)] {
            if [info exists wb1_options(lin2quad)] {
                mess "Converting elements from linear to quadratic...\n" blue
                ic_change_linear_quadratic iters 10 project 1 max_dev_half 0.1666666 check_max_dev_half 0 max_dev_nproj 30.0 check_max_dev_nproj 0 \
                    max_dev_chord 35.0 check_max_dev_chord 0 check_tet10_standard 0 check_tet10_strong 0 check_proj 0 max_leap 3.5 midface 0 \
                    create_interf 0 refine 0 smooth_refine 0 calc_projection 1 calc_projection_tol 0.001 all_elem 1 name {}
            }
        }
	    ic_save_unstruct $fm 1 "" $only_types $only_fams
	    set file_name(domain_saved) $fm
        # work-a-round for onyx 54992
        ic_uns_set_modified 1
    }
    set prism_mesh_loaded 0
}

proc aie_save_mesh_some {} {
    global file_save file_name options
    global fam_visible uns_type_visible file_save_type file_save_fam
    global aie_meshTypeVis
    
    set d [form_init .write_domains "Save Some Mesh As" file {accept cancel}]
    if {$d != ""} {
        set file_save(name) $file_name(domain)
        form_frame $d.dom ridge 2 {0 0 -cols 2}
        form_label $d.dom.l "Mesh file" {0 0}
        file_select_entry $d.dom.n file_save(name) 0 1 "Mesh file name" {0 1}
        set act {{file_save(only_subset) 0}}
        form_frame $d.types ridge 2 {1 0}
        form_label $d.types.l "Types:" {0 0} $act
        form_radiobutton $d.types.all All file_save(sel_types) 0 {1 0} $act
        form_radiobutton $d.types.some Select file_save(sel_types) 1 {2 0} $act
        form_frame $d.types.sel ridge 2 {3 0}
        form_frame $d.fams ridge 2 {1 1}
        form_label $d.fams.l "Parts:" {0 0} $act
        form_radiobutton $d.fams.all All file_save(sel_fams) 0 {1 0} $act
		form_radiobutton $d.fams.some Select file_save(sel_fams) 1 {2 0} $act
        form_frame $d.fams.sel ridge 2 {3 0}
        trace variable file_save w "file_save_check_box_active $d; list"
        form_finish +300+300 1 1
    }    
    set fam_opts [lsort -command "family_name_compare 0" [array names fam_visible]]
    foreach f $fam_opts { set file_save_fam($f) $fam_visible($f) }
    set type_opts ""
    foreach t [ic_uns_list_types] {
	    lappend type_opts $t	
	    set aie_type [lindex [split [string tolower $t] _] 0]
        if { [info exists aie_meshTypeVis($aie_type)] } {
	        set file_save_type($t) $aie_meshTypeVis($aie_type)
        }
    }

    set d .write_domains.main
    check_box $d.types.sel $type_opts 6 file_save_type
    check_box $d.fams.sel $fam_opts 6 file_save_fam
    file_save_check_box_active $d
	    
    if ![form_wait .write_domains] return

    set fst ""; set fsf ""; set nvol 0
    if $file_save(sel_types) {
        set fst ""
        foreach t [array names file_save_type] {
	        if $file_save_type($t) { lappend fst $t }
	    }
	    set nvol $file_save(surfs_near_vols)
    }
    if $file_save(sel_fams) {
        set fsf ""
        foreach f [array names file_save_fam] {
            if $file_save_fam($f) { lappend fsf $f }
        }
    }
    
    if {$file_save(name) != ""} {
        if {[file extension $file_save(name)] != ".uns"} {
            set file_save(name) $file_save(name).uns
        }
        set file_name(domain) $file_save(name)
        aie_save_Mesh $fst $fsf
    }
}

proc aie_save_strMesh {} {
    global file_name

    if {$file_name(settings) == "" && ($file_name(project_dir) == "." || \
        $file_name(project_dir) == "")} {
        set mess "Warning: Structured mesh will be saved in current working directory. \
                  Do you want to continue saving?"
        switch -- [tk_dialog .missing_project "Missing project name" "$mess" "" -1 Yes No "Save as project"] {
            0 {
                mess "Structured mesh will be saved in current working directory.\n"
                aie_save_strMeshas 0
                return
            }
            1 - -1 {
                if [winfo exists .missing_project] { destroy .missing_project }
                return
            }
            2 {
               mess "Structured mesh will be saved in a project directory.\n"
               aie_saveProject 1 0
               return
            }
	}
    }
    set fm $file_name(domain)
    if {$fm == ""} {
        aie_save_strMeshas
        return
    }
    set prj [file root [file tail $file_name(settings)]]
    if {$prj == ""} {
        set proj [file root [file tail $fm]]
    }    
    mess "Writing structured mesh to $prj.domain.*, $prj.top, $prj.fto, $prj.spr..."    
    ic_str_save $file_name(project_dir) "$prj.top" "$prj.fto" "$prj.spr" "$prj.domain."
    aie_create_multiblock_file "$prj."
    mess "\nDone\n"
}

proc aie_save_strMeshas {{ask 1}} {
    global file_name

    if $ask {
        set fm [tk_getSaveFile -initialdir $file_name(project_dir) -title "Save Mesh as" \
		    -filetypes {{{Mesh Files} {.Multiblock}} {{All files} *}} -parent .]
        if {$fm == ""} return
        if {[file extension $fm] != ".Multiblock"} {
	        set fm $fm.Multiblock
        }
        if {$fm == ".Multiblock"} {
           set fm Multiblock
        }
        set file_name(domain) $fm
    } else {
        set fm ""
        set file_name(domain) Multiblock
    }     
    set prj [file root [file tail $fm]]
    if {$prj != ""} {
        mess "Writing structured Mesh to $prj.domain.*, $prj.top, $prj.fto..."    
        ic_str_save . "$prj.top" "$prj.fto" "$prj.spr" "$prj.domain."
        set file_name(topo_mulcad_out) ./$prj.top
        set file_name(family_topo) ./$prj.fto
        set file_name(subface_proj) ./$prj.spr
        aie_create_multiblock_file "$prj."
    } else {
        mess "Writing structured Mesh to domain.*, topo_mulcad_out.top, family_topo.fto..."
        ic_str_save . "topo_mulcad_out.top" "family_topo.fto" "subface_proj" "domain."
        set file_name(topo_mulcad_out) ./topo_mulcad_out.top
        set file_name(family_topo) ./family_topo.fto
        set file_name(subface_proj) ./subface_proj
        aie_create_multiblock_file ""
    }
    mess "\nDone\n"
}

proc aie_save_Meshas {{visible 0}} {
    global file_name prism_mesh_loaded wb_initProjName

    if [ic_str_is_loaded] {
        aie_save_strMeshas
        return
    }
    if ![ic_uns_is_loaded] {
        user_error "Sorry, no mesh is loaded"
        return
    }
    switch $visible {
	    1 {
	        set title "Save only visible mesh"
	    }
        0 {
            set title "Save all mesh"
        }
        2 {
            set title "Save some mesh parts"
        }
    }
	if {$file_name(domain) != "" || ([aie_wb2_is_running] && [info exists wb_initProjName] && $file_name(domain) == "")} {
	    if [aie_wb2_is_running] {
	        set file_name(domain) $wb_initProjName.uns
	    }
        set fm [tk_getSaveFile -initialdir $file_name(project_dir) -title $title \
	        -filetypes {{{Mesh Files} {.uns}} {{All files} *}} -parent . \
	        -initialfile $file_name(domain)]
	} else {
        set fm [tk_getSaveFile -initialdir $file_name(project_dir) -title $title \
	        -filetypes {{{Mesh Files} {.uns}} {{All files} *}} -parent .]
	}
    if {$fm == ""} return
    if {[file extension $fm] != ".uns"} {
        set fm $fm.uns
    }
    aie_renumber_if_necessary
    set fm2 ""
    set here [pwd]/
    if [string match $here* $fm] {
        set fm2 [string range $fm [string length $here] end]
        regsub -all \\\\ $fm2 / fm2
    }
    if {$fm2 != ""} { set fm $fm2 }

    switch $visible {
        1 {
	        ic_save_unstruct $fm 1 "" "" "" [ic_uns_map_list 1]
	    }
        0 {
            ic_save_unstruct $fm
        }
        2 {
            set fams [select_families 0 1 0]
            if {$fams == ""} return
            ic_save_unstruct $fm 1 "" "" $fams "" 1
        }
    }
    set file_name(domain) $fm
    set file_name(domain_saved) $fm
    ic_uns_set_modified 1
    set prism_mesh_loaded 0
}

proc aie_renumber_if_necessary {} {
    global renumber_stuff

    set nn [ic_uns_check_duplicate_numbers]
    if {$nn == "0 0"} return

    set renumber_elems [lindex $nn 0]
    set renumber_nodes [lindex $nn 1]
    if $renumber_elems {
        mess "Renumbered all elements (except for 0-numbered elements) starting from 1 since there were duplicate numbers.\n"
        ic_uns_renumber_all_elements 1 1
    }
    if $renumber_nodes {
        mess "Renumbered all nodes (except for 0-numbered nodes) starting from 1 since there were duplicate numbers.\n"
        ic_uns_renumber_all_nodes 1 1
    }

    return

    # Skip this stuff for now

    set renumber_stuff(mess) "In the current mesh there are [lindex $nn 0] elements\nand [lindex $nn 1] nodes with duplicate numbers.\nThis will probably cause problems for your solver\nso you should renumber them."
    set renumber_stuff(elems) [expr [lindex $nn 0] > 0]
    set renumber_stuff(nodes) [expr [lindex $nn 1] > 0]

    set w [form_init .renumber_stuff "Renumber nodes and elements"]
    if {$w != ""} {
	array set renumber_stuff {
	    nodes_num 1 elems_num 1
	}
	form_label_variable $w.mess renumber_stuff(mess) {0 0 -cols 2}

	form_checkbutton $w.nodes "Renumber nodes starting at:" \
	    renumber_stuff(nodes) {1 0}
	form_checkbutton $w.elems "Renumber elements starting at:" \
	    renumber_stuff(elems) {2 0}
	form_entry $w.nodesn renumber_stuff(nodes_num) int {1 1} renumber_stuff(nodes)
	form_entry $w.elemsn renumber_stuff(elems_num) int {2 1} renumber_stuff(elems)
	form_finish +200+200
    }
    if [form_wait .renumber_stuff] {
	if $renumber_stuff(nodes) {
	    ic_uns_renumber_nodes all $renumber_stuff(nodes_num)
	}
	if $renumber_stuff(elems) {
	    ic_uns_renumber_elements all $renumber_stuff(elems_num)
	}
    }
}

proc aie_close_Mesh {{confirm 1} {skip 0}} {
    global file_name fam_visible prism_mesh_loaded quality_metric_created
    global doInsertAllDone volume_select surface_select
    global last_fvals last_tvals plot_window

    if {([file_needs_save domain]) && ($confirm)} {
        switch -- [tk_dialog .savedom "Save Mesh" "Do you want to save the current Mesh?" "" -1 Yes No] {
            1 - -1 { if [winfo exists .savedom] { destroy .savedom } }
            0 {
                set base [file tail $file_name(domain)]
                if {$base == ""} {
                    set base [file rootname [file tail $file_name(tetin)]]
                    if {$base != ""} { append base .uns }
                }
                if {$base == ""} { set base mesh.uns }
                set file_name(domain) [file join $file_name(project_dir) $base]
                aie_save_Mesh
            }
        }
    }
    aie_cutplane_clear 1
    ic_unload_mesh
    foreach t [array names volume_select] { set volume_select($t) 1 }
    foreach t [array names surface_select] { set surface_select($t) 1 }
    set file_name(domain) ""
    # Reset display variables
    set fam_active ""
    foreach f [ic_geo_list_families] {
        lappend fam_active $f
    }
    foreach f [ic_hex_non_empty_families] {
        lappend fam_active $f
    }
    if [info exists fam_visible] {
        foreach f [array names fam_visible] {
            if {[lsearch -exact $fam_active $f] < 0} {
                if ![ic_hex_subset_named_selection $f] {
                    unset fam_visible($f)
                }
            }
        }
    }
    ::AIEnv::GUIManagement::Tree::clear mesh
    if {[info exists plot_window] && [winfo exists $plot_window.graph]} {
        aie_delete_histogram
        aie_delete_colorband 1
    }
    ::AIEnv::GUIManagement::ConfigureConsoleZone 0
    catch { unset quality_metric_created }
    aie_deleteShellDiagnostics 2
    set prism_mesh_loaded 0
    aie_clear_dez
    aie_update_icons mesh
    catch { unset last_fvals; unset last_tvals }
    catch { unset doInsertAllDone }
    # clear empty parts
    if !$skip { aie_delete_empty_parts 0 }
    if !$skip { aie_update_lcs }
    ic_undo_clear
}

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

proc aie_open_attr {{ask 1} {clear 1}} {
    global file_name AIEnvProduct
    global beta_mode options solution

    set ft ""
    set ft1 ""

    if ![file isdirectory $file_name(project_dir)] {set_project_dir .}
    if {$file_name(attributes) != "" && [file isfile $file_name(attributes)]} {
        set ft $file_name(attributes)
    }

    if {$file_name(family_boco) != "" && [file isfile $file_name(family_boco)]} {
        set ft1 $file_name(family_boco)
    }

    if {((![file isfile $ft]) && (![file isfile $ft1])) || $ask == 1} {
        if [aie_wb2_is_running] {
	        set ft [tk_getOpenFile -title "Open Attribute File" -initialdir $file_name(project_dir) -parent . \
		        -filetypes {{{Attribute Files} {*.atr *.fbc}} {{All files} *}}]
                set ft1 $ft
        } else {
	        set ft [tk_getOpenFile -title "Open Attribute File" -initialdir $file_name(project_dir) -parent . \
		        -filetypes {{{Attribute Files} {*.atr *.fbc}} {{All files} *}}]
                set ft1 $ft
        }
    }
    if {$ft == "" && $ft1 == ""} return
        
    if {[file extension $ft] == ".atr"} {
        if [catch {ic_boco_load_atr $ft} res] {
	        mess "Error in opening attribute file; $res.  Trying the fbc file ...\n" red
	        if [catch {ic_boco_load $ft1} res] {
	            mess "Error in opening ICEM CFD boundary condition file; $res\n" red
	            set file_name(family_boco_loaded) 0
	            busy reset
	            return
            } else {
                set file_name(family_boco_loaded) 1
                set file_name(family_boco) $ft1
            }
        } else {
            set file_name(family_boco_loaded) 1
            set file_name(attributes_loaded) 1
    	    set pref [file tail [file rootname $ft]]
            set file_name(attributes) $pref.atr
            set file_name(family_boco) $pref.fbc
        }
    } else {
	    if [catch {ic_boco_load $ft1} res] {
	        mess "Error in opening ICEM CFD boundary condition file; $res\n" red
	        set file_name(family_boco_loaded) 0
	        busy reset
	        return
        } else {
            set file_name(family_boco_loaded) 1
            set file_name(family_boco) $ft1
        }
    }
    if {$AIEnvProduct == "fea2.0" && $ft1 != "" && [file extension $ft1] == ".fbc"} {
        if {[info exists options(default_solver)] && $options(default_solver) == "ANSYS"} {
            if {[info exists solution(solver)] && $solution(solver) == "ANSYS"} {
	            if ![catch {ic_boco_load $ft1} res] {
                    set file_name(family_boco_loaded) 1
                    set file_name(family_boco) $ft1
                } else {
	                mess "Error in opening ICEM CFD boundary condition file; $res\n" red
	                busy reset
	                return
                }
            }
        }
    }
    
    if {[info exists solution(solver)] && $solution(solver) == "Fluent_V6"} {
        solution_set_solver $solution(solver)
    }

    foreach ee [ic_boco_list_families ET*] { set used($ee) 1 }
    foreach ff [ic_boco_list_families OR*] {
	    set f1 [split $ff :]
	    if {([llength $f1] == 2) && [string match OR* [lindex $f1 1]]} {
	        set bcs [ic_boco_get $ff]
	        for {set i 1} {[info exists used(ET$i)]} {incr i} {}
	        set nf ET$i
	        ic_uns_rename_family $ff $nf
	        ic_geo_new_family $nf
	        ic_boco_set $ff ""
	        ic_boco_set [lindex $f1 0] ""
	        ic_boco_set [lindex $f1 1] ""
	        ic_boco_set $nf $bcs
	        set used($nf) 1
	    }
    }

    aie_get_bc_names

    if $clear {aie_clear_dez}
    # Load up the tree with the materials, etc we found
    if $ask {
        aie_afterStuffLoaded 0
    }
}

proc aie_initialize_tree_props_and_icons {} {
    global env aie_bctypes_used aie_bcclass_is_part fam_visible
    global aie_tree_param_nodes

    busy 1
    ic_boco_clear_icons

    set allfams [ic_boco_list_families !:]

    array set bc_usage [ic_boco_bctypes_used_by_families]

    foreach type [array names aie_bctypes_used] {
	if {[info proc aie_apply_icons_$type] == ""} continue
	foreach b $aie_bctypes_used($type) {
	    if [info exists bc_usage($b)] {
		foreach fam $bc_usage($b) {
		    if [string match *:* $fam] continue
		    if [info exists aie_bcclass_is_part($type)] {
			set do_partbc([list $type $fam]) 1
		    } else {
			set do_group([list $type $fam]) 1
		    }
		}
	    }
	}
    }

    foreach pair [array names do_group] {
	set type [lindex $pair 0]
	set fam [lindex $pair 1]
	set vis [aie_is_group_type_visible $type]
	set nn [aie_apply_icons_$type $fam geometry_or_mesh $vis $vis]
	if {$nn && ![string match *:* $fam] && ![info exists seen($type,$fam)]} {
	    if {![::AIEnv::GUIManagement::Tree::GroupExists $type $fam]} {
		::AIEnv::GUIManagement::Tree::AddGroup $type $fam $vis
	    }
	    set seen($type,$fam) 1
	}
    }

    foreach pair [array names do_partbc] {
	set type [lindex $pair 0]
	set fam [lindex $pair 1]
	set vis [aie_is_group_type_visible $type]
	if ![::AIEnv::GUIManagement::Tree::GroupExists part $fam] {
	    ic_geo_new_family $fam
	    ::AIEnv::GUIManagement::Tree::AddGroup part $fam $vis
	    set fam_visible($fam) 1
	}
	set nn [aie_apply_icons_$type $fam geometry_or_mesh $vis $vis]
	if {$nn && ![string match *:* $fam] && ![info exists seen($type,$fam)]} {
	    if {![::AIEnv::GUIManagement::Tree::PartBCExists $type $fam]} {
		::AIEnv::GUIManagement::Tree::AddPartBC $type $fam $vis
	    }
	    set seen($type,$fam) 1
	}
    }

    aie_connectors_load

    foreach tn [lsort [array names aie_tree_param_nodes]] {
	foreach child [ic_param_list_children $tn] {
	    set spl [split $child /]
	    if {[llength $spl] > 1} {
		::AIEnv::GUIManagement::Tree::addMultipleParam [lindex $spl 0] \
		    [lindex $spl 1] $aie_tree_param_nodes($tn)
	    }
	}
    }

    # Do the contact stuff
    aie_init_contact

    busy reset
}

proc aie_saveas_attr {{ask 1}} {
    global file_name beta_mode options solution batch_mode

    if {[info exists solution(solver)] && $solution(solver) == "Fluent_V6"} {
        solution_set_solver $solution(solver)
    }
    set solverinfo [ic_boco_solver]
    if {$solverinfo == ""} {
        if {[info exists options(default_solver)] && $options(default_solver) != ""} {
            set solverinfo $options(default_solver) 
        }
        if {[info exists solution(solver)] && $solution(solver) != ""} {
            set solverinfo $solution(solver)  
        }
        if {$solverinfo != ""} {
            ic_boco_solver $solverinfo
            ic_solution_set_solver $solverinfo 1
        }
    } else {
        ic_boco_solver $solverinfo
        ic_solution_set_solver $solverinfo 1
    }
    if {$solverinfo == ""} {
       ic_boco_solver "ANSYS Fluent"
       ic_solution_set_solver "ANSYS Fluent" 1
    }
    set defdir [file dirname $file_name(family_boco)]
    if {$defdir == ""} { set defdir $file_name(project_dir) }
    if {$defdir == ""} { set defdir . }
    set deffile [file tail $file_name(family_boco)]
    if {$deffile == ""} {
         set deffile ansys.fbc
    }
    if $ask {
        set ft [tk_getSaveFile -initialdir $defdir -initialfile $deffile -parent . -filetypes {{{Attribute Files} {*.fbc *.atr}} {{All files} *}}]
    } else {
        set ft $file_name(family_boco)
    }
    if {$ft == ""} { return 1 }
    set atr [file rootname $ft].atr
    set ft [file rootname $ft].fbc
    ic_boco_save $ft
    if [catch {ic_boco_save_atr $atr} res] {
        mess "Warning: attribute file $atr not saved; $res\n"
        busy reset
    } else {
        set file_name(attributes) $atr
    }
    set file_name(family_boco) $ft
}

proc aie_save_attr {} {
    aie_saveas_attr 0
}

proc aie_close_attr {{confirm 1} {skip 0}} {
    global file_name
    global bc_name_list
    if {([file_needs_save boco]) && ($confirm)} {
	    switch -- [tk_dialog .saveatt "Save Attributes" "Do you want to Save the current Attributes?" "" -1 Yes No] {
		    1 - -1 { if [winfo exists .saveatt] { destroy .saveatt } }
		    0 {
		        set file_name(family_boco) [file join $file_name(project_dir) [file tail $file_name(family_boco)]]
		        aie_save_attr
		    }
	    }
    }
    ic_boco_unload
    set file_name(family_boco) ""
    set file_name(attributes) ""
    catch {unset bc_name_list}
    ::AIEnv::GUIManagement::Tree::clear attr
    # clear empty parts
    if !$skip { aie_delete_empty_parts 0 }
    if !$skip { aie_update_lcs }
}

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

proc aie_open_params {{ask 1} {clear 1}} {
    global file_name
    
    if ![file isdirectory $file_name(project_dir)] { set_project_dir .}
    set par $file_name(solver_params)
    if {(![file isfile $par]) || $ask == 1} {
        set par [tk_getOpenFile -initialdir $file_name(project_dir) -parent . -filetypes {{{Parameter files} *.par} {{All files} *}}]
    }
    if {$par == ""} return 
    set ret [aie_load_params_file $par $clear]
    if $ask {
        aie_afterStuffLoaded 0
    }
    return $ret
}

proc aie_load_params_file {par clear} {
    global AIEnvProduct

    ic_param_load $par $clear
    set file_name(solver_params_loaded) 1
    set file_name(solver_params) $par
    if { $AIEnvProduct != "fea2.0" } return
    aie_after_load_params
    if $clear { aie_clear_dez }
}

# Load up the tree with the materials, etc we found

proc aie_after_load_params {} {
    global batch_mode
    if $batch_mode return

    aie_load_tbls 1
    aie_tree_load_materials 1
    aie_tree_load_params 1
    if {[ic_csystem_list] != "" || [ic_geo_is_loaded]} aie_load_lcs
    aie_load_subcase
}

proc aie_saveas_params {{ask 1}} {
    global file_name
    
    set defdir [file dirname $file_name(solver_params)]
    if {$defdir == ""} { set defdir $file_name(project_dir) }
    if {$defdir == ""} { set defdir . }
    set deffile [file tail $file_name(solver_params)]
    if {$deffile == ""} { set deffile nastran.par }
    if $ask {
        set par [tk_getSaveFile -initialdir $defdir -initialfile $deffile -filetypes {{{Parameter files} *.par} {{All files} *}} -parent .]
    } else {
        set par $file_name(solver_params)
    }
    if {$par == ""} { return 1 }
    if {([file extension $par] != ".par") && ([file extension $par] != ".mpar")} {
        set par $par.par
    }
    foreach func {
        aie_update_materials_to_params
        aie_save_tbls
        aie_save_sol_params
        aie_save_lcs
    } {
        if {[info command $func] != ""} {
            $func
        }
    }
    ic_param_save $par
    set file_name(solver_params) $par
}

proc aie_save_params {} {
    aie_saveas_params 0
}

proc aie_close_params {{confirm 1}} {
    global file_name

    if {$confirm && [ic_param_is_modified]} {
	    switch -- [tk_dialog .savepar "Save Parameters" "Do you want to save the current Parameters?" "" -1 Yes No] {
		    1 - -1 { if [winfo exists .savepar] { destroy .savepar } }
		    0 {
		        set file_name(solver_params) [file join $file_name(project_dir) [file tail $file_name(solver_params)]]
		        aie_save_params
		    }
	    }
    }
    set file_name(solver_params) ""
    ::AIEnv::GUIManagement::Tree::clear params
}

proc aie_cart3d_load_mesh {} {
    set dir [pwd]
    set fm [tk_getOpenFile -initialdir $dir -title "Select Cart3d Mesh File" \
        -filetypes {{{Mesh Files} {.tri .triq .mesh}} {{All files} *}}]
    if {$fm == ""} return
    set tmpdomain ${fm}_temp[pid].dom
    catch { cmd_rm $tmpdomain }
    if {[file extension $fm] == ".tri"} {
        set status [ic_run_c3dtri2df $fm $tmpdomain]
    } elseif {[file extension $fm] == ".triq"} {
        set status [ic_run_c3dtri2df $fm $tmpdomain 1]
    } else {
        set status [ic_run_cart3d2df $fm $tmpdomain]
    }
    if [file exists $tmpdomain] {
        if !$status {
            set opt 1
            if { [ic_uns_is_loaded] } {
                set opt [tk_dialog .unsOverwrite "Mesh Exists" \
                    "Mesh Already Exists in this File, how do you wish to proceed?" \
                    "" 1 "Merge" "Replace" "Cancel" ]
                switch -- $opt {
                    -1 {
                        if [winfo exists .unsOverwrite] { destroy .unsOverwrite }
                        cmd_rm $tmpdomain
                        return
                    } 
                    0 { }
                    1 { ic_unload_mesh }
                    default { cmd_rm $tmpdomain; return }
                }
            }
            ic_load_unstruct $tmpdomain
            aie_after_open_mesh 1 $opt
       }
       cmd_rm $tmpdomain
    }
}

proc aie_unused_project_name {{prefix project}} {
    for {set i 1} {[file exists $prefix$i.prj] || [file exists $prefix$i.dat] || [file exists $prefix$i.uns] || [file exists $prefix$i.fbc] || [file exists $prefix$i.par] || [file exists $prefix$i.mpar] || [file exists $prefix$i.tin]} {incr i} {}
    return $prefix$i
}

proc aie_save_last_view {} {
    global tdv_center tdv_rot tdv_scale tdv_pos tdv_current_viewer
    global last_view
    
    catch {unset last_view}
    if ![info exists last_view] {
	    set last_view ""
	    set w $tdv_current_viewer
	    foreach n {rot scale center pos} {
	        set v [set tdv_${n}($w)]
            lappend last_view $n $v
	    }
    }
    if [info exists last_view] {
        return $last_view
    } else {
        return ""
    }
}

proc aie_load_last_view {} {
    global last_view

    if {[info exists last_view] && $last_view != ""} {
	    set cmd "ic_current_view"
	    foreach {n v} $last_view {
           append cmd " -$n {$v}"
	    }
	    eval $cmd
        unset last_view
    }
    return
}

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

proc aie_import_nastran {{file ""} {do_load 1} {is_mat 0} {rbe3 0} {bars 0} {shell 0} {include 0}} {
    global file_name env bindir tcl_platform
    global solver_setup 
    
    if ![file isdirectory $file_name(project_dir)] {
        set_project_dir .
    }
    
    if {$file == ""} {
        set types {{{Nastran files} {*.dat *.nas *.dbf}} {{All files} *}}
        if $is_mat {
            set types [concat {{{Nastran material files} *.mat}} $types]
        }
        set file [tk_getOpenFile -initialdir $file_name(project_dir) \
		      -filetypes $types -parent .]
        if {$file == ""} { return "" }
    }
    
    set conv $env(ICEM_ACN)/icemcfd/output-interfaces/IcedNastran
    if {![file exists $conv] && ![file exists $conv.exe]} {
        set conv $bindir/IcedNastran
    }
    
    if {$file_name(settings) != "" && !$is_mat && !$include} {
        set pname [file rootname $file_name(settings)]
    } else {
        set pname [aie_unused_project_name]
        if $is_mat {
            file copy $file $pname.dat
            set file $pname.dat
        }
    }
    
    mess "\"$conv\" -i \"$file\" -rbe3 $rbe3 -bar $bars -shell $shell -p \"$pname\"\n"
    busy 1
    set data [ic_import_nastran $conv $file $rbe3 $bars $shell $pname]
    mess $data blue
    
    if $do_load {
        set solver_setup 0
        ic_boco_solver Nastran
        set file_name(domain) [file rootname $pname].uns
        aie_open_Mesh 0
        set file_name(solver_params) [file rootname $pname].par
        set file_name(solver_params_loaded) 1
        aie_open_params 0
        set file_name(family_boco) [file rootname $pname].fbc
        set file_name(family_boco_loaded) 1
        set file_name(attributes) [file rootname $pname].atr
        set file_name(attributes_loaded) 0
        aie_open_attr 0
        if {$file_name(settings) == ""} {
            set file_name(settings) [file rootname $pname].prj
        }
        aie_afterStuffLoaded
        aie_initial_unsmesh_visibility	
    }
    
    busy 0
    
    if {[regexp "fea2.0" $env(AI_ENV_PRODUCT)]} aie_element_summary
    
    set error_file [file rootname $pname]Messages.sect
    
    if {[file exists $error_file]} {
        set size [file size $error_file]
        if {$size == "0" } {
            mess "\nNastran file conversion completed successfully.\n" blue
        } else {
            mess "\nNastran file conversion completed with some errors.\nPlease check the file $error_file for details.\n" red
            edit_file $error_file 1
        }
    }
    
    return $pname
}

#  the below is a duplicate of med_batch/output_funcs.tcl, plus thickness
proc aie_export_nastran { nas_file domain family_boco solver_params large_format vol_v shell_v bar_v thick_v cont_flag} {
    global env bindir tcl_platform

    set nas_args [list -dom $domain -vol $vol_v -shell $shell_v -bar $bar_v -thickness $thick_v -continuation $cont_flag]
    
    if {$family_boco != ""} {
	    lappend nas_args -b $family_boco
    }
    if {$solver_params != ""} {
	    lappend nas_args -param $solver_params
    }
    if !$large_format { lappend nas_args -small_field }
        lappend nas_args $nas_file
    
    ic_run_application_batch . icemcfd/output-interfaces nasn "" $nas_args
    return 1
}

proc aie_export_nastran_materials {nas_file solver_params} {
    global env bindir tcl_platform
    
    set nas_exec $env(ICEM_ACN)/icemcfd/output-interfaces/nasn
    if {$tcl_platform(platform) == "windows"} {
	    append nas_exec .exe
    }
    
    regsub -all \\\\ $nas_exec / nas_exec
    
    if ![file executable $nas_exec] {
	    error "Can't find Nastran Converter executable $nas_exec"
	    return 0
    }
    
    set nas_cmd [list $nas_exec -matlib -param $solver_params $nas_file.tmp]
    mess $nas_cmd\n
    
    if {![catch {eval ic_exec $nas_cmd} out]} {
	    mess "$out\n"
	    set fp [open $nas_file.tmp r]
	    set mats [read $fp]
	    close $fp
	    file delete $nas_file.tmp
	    set fp [open $nas_file w]
	    puts $fp "CEND\nBEGIN BULK\n$mats\nENDDATA\n"
	    close $fp
	    return 1
    } else {
	    mess "Error \n $out\n" red
	    return 0
    }
}

proc aie_open_blocking {{ask 1} {blk_file ""} {wb2 0}} {
    global file_name tdv_default str_option aie_CurveComposite hex_option display_flag batch_mode
    global cut_info_backup wb1_options env 
    
    if {$blk_file != ""} {
        regsub -all \\\\ $blk_file / blk_file
    }
    
    if {$ask && (![ic_geo_is_loaded])} {
        if ![aie_hex_sketching_mode] {
	        set opt [tk_dialog .blockfirst "No geometry" "No geometry loaded.\
		        This will lead to problems in hexa mesh generation.\
		        Do you want to continue loading blocking file?" \
		        "" -1 "Yes" "No" ]
	        switch -- $opt {
	            1 - -1 {
	                if [winfo exists .blockfirst] { destroy .blockfirst }
	                return
	            }
	        }
	    }
    }

    if ![file isdirectory $file_name(project_dir)] {set_project_dir .}
    if {$blk_file != ""} {
	    set ft $blk_file
    } else {
	    set ft $file_name(blocking)    
	    if {(![file isfile $file_name(blocking)]) || $ask == 1} {
	        set ft [tk_getOpenFile -initialdir $file_name(project_dir) -filetypes {{{Blocking Files} {.blk}} {{All Files} *}} \
			    -title "Open Blocking File" -initialfile [file tail $ft] -parent .]
	    }
    }

    if {$ft == ""} return
    
    if [ic_hex_blocking_loaded] {
	    set opt [tk_dialog .blockOverwrite "Blocking Exists" \
		     "Blocking Already Exists" "" -1 "Merge" "Replace" "Cancel" ]
	    switch -- $opt {
	        0 {
		        aie_merge_blocking $ft
		        return
	        }
	        1 {
		        mess "   --- Unloading existing blocking\n"
		        aie_close_blocking
	        }
	        2 - -1 {
	            if [winfo exists .blockOverwrite] { destroy .blockOverwrite }
	            return
	        }
	    }
    }
    aie_clear_dez
    ic_undo_start
    set display_flag(block_worst) 0
    catch { array unset cut_info_backup }
    mess "Loading blocking file \"$ft\"\n"
    if [info exists env(AI_ENV_IN_WB1)] {
        if [catch {ic_hex_restore_blocking $ft -skip_read_surface_params} res] {
	        mess "Error in opening Blocking file; $res\n" red
	        busy reset
	        return
        } else {
            if [info exists wb1_options(updatebunching)] {
                mess "Updating blocking sizes from geometry...\n" blue
                ic_hex_set_mesh_params -version 110
            }
        }
    } else {
        if [catch {ic_hex_restore_blocking $ft} res] {
	        mess "Error in opening Blocking file; $res\n" red
	        busy reset
	        return
        }
    }
    set file_name(blocking) $ft
    if $ask {
        hex_mesh_size
        mess "Blocking topologies:\n"
        set topos [ic_hex_print_topo_tree]
        foreach topo $topos { mess "\t$topo\n" }
    }
    set do_home [expr ![ic_geo_is_loaded] && ![ic_uns_is_loaded]]
    if $do_home { tdv_home $tdv_default }
    if [info exists aie_CurveComposite] {
        set aie_CurveComposite 1
    }
    if [aie_wb2_is_running] {
        if {$wb2 && !$batch_mode} {
            ic_socket_send_to_wb2 "wb_status 2"
        }
    }
    if $hex_option(hexa_verbose_mode) {
        ic_hex_error_messages on_minor
    } else {
        ic_hex_error_messages off_minor
    }
}

proc aie_merge_blocking {filename} {
    global top_visible top_current

    if {$filename == ""} return
    set nname [aie_select_unused_topo]  
    if {$nname == ""} return
    if [catch {ic_hex_restore_blocking $filename $nname} res] {
        mess "Error in opening Blocking file; $res\n" red
        busy reset
        return
    }    
    aie_hex_check_families
    switch_topology $nname
    ::AIEnv::GUIManagement::Tree::AddTopo $nname
    ::AIEnv::GUIManagement::Tree::ToggleTopoVisibility topo $nname 1
}

proc aie_close_blocking {{confirm 1} {skip 0}} {
    global file_name str_option

    if ![ic_hex_blocking_loaded] return
    
    set blocking_modified [file_needs_save blocking]
    if {($blocking_modified) && ($confirm)} {
        set opt [tk_dialog .saveblocking "Save Blocking" "Do you want to Save the current Blocking?" "" -1 Yes No Cancel]
        switch -- $opt {
            0 {
                aie_save_blocking
            }
            1 { }
            2 - -1 {
                if [winfo exists .saveblocking] { destroy .saveblocking }
                return
            }
        }
    }
    aie_after_close_blocking
    # clear empty parts
    if !$skip { aie_delete_empty_parts 0 }
    if !$skip { aie_update_lcs }
    ic_undo_clear
}

proc aie_after_close_blocking {} {
    global file_name str_option hexa_select cut_info_backup
    global saved_index_controls aie_CurveComposite 
 
    # close the histogram form
    aie_hex_clear_histogram 1
    aie_unload_blocking
    # close the scan/index form
    scan_form_done
    index_form_done
    catch { unset saved_index_controls }
    aie_hex_cut_plane_clear
    catch { array unset cut_info_backup }
    set file_name(blocking) ""
    ::AIEnv::GUIManagement::Tree::clear blocking
    aie_clear_dez
    aie_delete_vorfn
    set str_option(curve,show_composite) 0
    set aie_CurveComposite 0
    update_geom_visible curve p
    ic_hex_is_modified 0
    aie_update_icons block
}

proc aie_save_blocking {{ask 0} {format40 ""} {wb2 0}} {
    global file_name hex_option batch_mode

    if {([info exists file_name(blocking)]) && $file_name(blocking) != ""} { 
        set infile $file_name(blocking)
    } else {
        set pref [file tail [file rootname $file_name(settings)]]
        set infile $pref.blk
    }
    if {$ask || $infile == ""} {
        set fm [tk_getSaveFile -initialdir [pwd] -initialfile $infile -parent . \
		    -filetypes {{{Blocking Files} {.blk}} {{All files} *}}]
        if {$fm == ""} return
        if {[file extension $fm] != ".blk"} {
	        set fm $fm.blk
	    }
	    set file_name(blocking) $fm
    } elseif {$file_name(blocking) == ""} {
	    set file_name(blocking) [file join . $pref.blk]
    }
    if $hex_option(check_inv) {
       aie_hex_check_fix_inverted
    }
    if ![aie_wb2_is_running] {
        if [file exists $file_name(blocking)] {
            set bak_file [file tail $file_name(blocking)]
            for {set i 0} {[file exists [set bak_file_name $bak_file$i]]} {incr i} {}
            cmd_cp $file_name(blocking) $bak_file_name
            mess "Previous blocking file saved as file $bak_file_name\n"
        }
    }
    hex_command "save_blocking \"$file_name(blocking)\" $format40"
    ic_hex_is_modified 0
    if [aie_wb2_is_running] {
        if {$wb2 && !$batch_mode} {
            ic_socket_send_to_wb2 "wb_status 2"
        }
    }
}

proc aie_save_multiblock_mesh {} {
    if ![ic_hex_blocking_loaded] {
        msg ERROR "No blocking loaded"
    } else {
        aie_convert_hex2_multiblock
    }
}

proc aie_save_unstruct_mesh {} {
    global file_name
    if ![ic_hex_blocking_loaded] {
        msg ERROR "No blocking loaded"
    } else {
	    set file [tk_getSaveFile -initialdir $file_name(project_dir) -title "Save Mesh as" \
	        -filetypes {{{Mesh Files} {.uns}} {{All files} *}} -parent .]

	if {$file == ""} return

	if {[file extension $file] != ".uns"} {
	    set file $file.uns
	}
	aie_convert_hex2_uns	$file
	    mess "Wrote file $file\n"
    }
}

proc aie_import_geo {type} {
    global file_name
    aie_clear_dez
    trans_${type}_tetin
    if {$file_name(tetin) != ""} {
        aie_afterStuffLoaded
    }
}

set ::ansys_null_params {
# empty solver params file
# solver: Ansys

begin ansys_product
    coupled 0
    exit_opt 0
    save_opt 0
    proc_n 1
    type1 ST
    type2 TH
    begin ST
        NLGEOM OFF
        NSUBST 1
        anal_type None
        freq 0.0
        freq2 1.0E+08
        mod_ce 0
        mod_expec 0
        mod_n 1
        mod_norm 0
        mod_solv LANB
        solv_mult 1.0
        solv_tol 1.0E-08
        solv_type SPARSE
    end ST
end ansys_product

begin def_0_ST_3
    type 0
end def_0_ST_3

begin def_1_ST_1
    type 0
end def_1_ST_1

begin def_1_ST_2
    type 0
end def_1_ST_2

begin def_2_ST_1
    type 0
end def_2_ST_1

begin def_2_ST_2
    type 0
end def_2_ST_2

begin def_3_ST_1
    type 0
end def_3_ST_1

begin def_3_ST_2
    type 0
end def_3_ST_2

begin global
    ACEL 0
    ACEL_XYZ {0 0 0}
    DOMEGA 0
    OMEGA 0
end global
}

set ::ansys_default_params {
# default solver params file for AI*Environment 11.0 Export Mesh menu
# solver: Ansys

begin ansys_product
    coupled 0
    exit_opt 0
	save_opt 0
    proc_n 1
    type1 ST
    type2 TH

    begin ST
        anal_type None
    end ST
end ansys_product

begin def_0_ST_3
    inopr 0
    real None
    type 0
end def_0_ST_3

begin def_1_ST_1
    inopr 0
    real None
    type 200
end def_1_ST_1

begin def_1_ST_2
    inopr 0
    real None
    type 200
end def_1_ST_2

begin def_2_ST_1
    inopr 0
    real None
    type 200
end def_2_ST_1

begin def_2_ST_2
    inopr 0
    real None
    type 200
end def_2_ST_2

begin def_3_ST_1
    inopr 0
    real None
    type 200
end def_3_ST_1

begin def_3_ST_2
    inopr 0
    real None
    type 200
end def_3_ST_2

begin global
    ACEL 0
    DOMEGA 0
    OMEGA 0
end global
}

set ::lsdyna_default_params {
# default solver params file for AI*Environment 1.0 Export Mesh menu
# solver: LS-Dyna

begin title
    title {LS-Dyna exported mesh from AI*Environment 5.2}
end title

begin control
    begin Control1
        OPT 0
    end Control1
    begin Control10
        OPT 0
    end Control10
    begin Control11
        OPT 0
    end Control11
    begin Control12
        OPT 0
    end Control12
    begin Control13
        OPT 0
    end Control13
    begin Control14
        OPT 0
    end Control14
    begin Control15
        OPT 0
    end Control15
    begin Control16
        OPT 0
    end Control16
    begin Control17
        OPT 0
    end Control17
    begin Control18
        OPT 0
        choice 0
    end Control18
    begin Control19
        OPT 0
    end Control19
    begin Control2
        OPT 0
    end Control2
    begin Control20
        OPT 0
    end Control20
    begin Control21
        OPT 0
    end Control21
    begin Control22
        OPT 0
    end Control22
    begin Control23
        OPT 0
    end Control23
    begin Control24
        OPT 0
    end Control24
    begin Control25
        OPT 0
    end Control25
    begin Control26
        OPT 0
    end Control26
    begin Control27
        OPT 0
    end Control27
    begin Control28
        OPT 0
    end Control28
    begin Control29
        OPT 0
    end Control29
    begin Control3
        OPT 0
        card1p7 0
    end Control3
    begin Control30
        OPT 0
    end Control30
    begin Control31
        OPT 0
    end Control31
    begin Control32
        OPT 0
    end Control32
    begin Control33
        OPT 0
    end Control33
    begin Control34
        OPT 0
    end Control34
    begin Control35
        OPT 0
    end Control35
    begin Control36
        OPT 0
    end Control36
    begin Control37
        OPT 0
    end Control37
    begin Control38
        OPT 0
    end Control38
    begin Control39
        OPT 0
    end Control39
    begin Control4
        OPT 0
    end Control4
    begin Control40
        OPT 0
    end Control40
    begin Control5
        OPT 0
    end Control5
    begin Control6
        OPT 0
    end Control6
    begin Control7
        OPT 0
    end Control7
    begin Control8
        OPT 0
    end Control8
    begin Control9
        OPT 0
    end Control9
end control

begin dbase
    begin database
        begin ABSTAT
            OPT 0
        end ABSTAT
        begin AVSFLT
            OPT 0
        end AVSFLT
        begin BNDOUT
            OPT 0
        end BNDOUT
        begin DEFGEO
            OPT 0
        end DEFGEO
        begin DEFORC
            OPT 0
        end DEFORC
        begin ELOUT
            OPT 0
        end ELOUT
        begin GCEOUT
            OPT 0
        end GCEOUT
        begin GLSTAT
            OPT 0
        end GLSTAT
        begin JNTFORC
            OPT 0
        end JNTFORC
        begin MATSUM
            OPT 0
        end MATSUM
        begin MOVIE
            OPT 0
        end MOVIE
        begin MPGS
            OPT 0
        end MPGS
        begin NCFORC
            OPT 0
        end NCFORC
        begin NODFOR
            OPT 0
        end NODFOR
        begin NODOUT
            OPT 0
        end NODOUT
        begin RBDOUT
            OPT 0
        end RBDOUT
        begin RCFORC
            OPT 0
        end RCFORC
        begin RWFORC
            OPT 0
        end RWFORC
        begin SBTOUT
            OPT 0
        end SBTOUT
        begin SECFORC
            OPT 0
        end SECFORC
        begin SLEOUT
            OPT 0
        end SLEOUT
        begin SPCFORC
            OPT 0
        end SPCFORC
        begin SPHOUT
            OPT 0
        end SPHOUT
        begin SSSTAT
            OPT 0
        end SSSTAT
        begin SWFORC
            OPT 0
        end SWFORC
        begin TPRINT
            OPT 0
        end TPRINT
        begin TRHIST
            OPT 0
        end TRHIST
    end database
    begin database_extent
        begin AVS
            Opt 0
        end AVS
        begin BINARY
            Opt 0
        end BINARY
        begin MOVIE
            Opt 0
        end MOVIE
        begin MPGS
            Opt 0
        end MPGS
    end database_extent
    begin database_format
        DEFINE 0
    end database_format
    begin database_spring
        DEFINE 0
    end database_spring
    begin database_superplastic
        DEFINE 0
    end database_superplastic
    begin database_tracer
        DEFINE 0
    end database_tracer
end dbase

begin def_node
    csid 0
    formul 0
    ixx 0.0
    ixy 0.0
    ixz 0.0
    iyy 0.0
    iyz 0.0
    izz 0.0
    mass 0.0
    write 1
end def_node

begin def_beam
    cs 2
    formul 1
    mat1 1
    of 0.0
    pf 0
    rr 0
    rt 0
    sf 1.0
    slen 0.0
    write 1
    begin card1
        f1 -1
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card1

    begin sec_beam
        cst 0
        f1 0.0
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
        formul 1
        id -1
        qr 2
        scoor 0
        shrf 1.0
    end sec_beam
end def_beam

begin def_shell
    formul 0
    mat0 1
    write 1
    begin card1
        f1 -1
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card1

    begin hg_shell
        include 0
    end hg_shell

    begin sec_shell
        formul 0
        icomp 0
        id -1
        marea 0.0
        nip 0
        nloc 0
        opt 0
        propt 1
        qr 0
        setype 1
        shrf 1.0
        thk 0.0
    end sec_shell
end def_shell

begin def_solid
    formul 0
    mat0 1
    write 1
    begin card1
        f1 -1
        f2 0.0
        f3 0.0
        f4 0.0
        f5 0.0
        f6 0.0
        f7 0.0
        f8 0.0
    end card1

    begin EOS_solid
        include 0
    end EOS_solid

    begin hg_solid
        include 0
    end hg_solid

    begin sec_solid
        aet 4
        formul 0
        id -1
        opt 0
    end sec_solid
end def_solid

begin def_part
    adpopt 0
    grav 0
    tmid 0
end def_part

begin define
    DEFINE 0
    begin lCurve_feedback
        DEFINE 0
    end lCurve_feedback
end define

begin blastload
    DEFINE 0
end blastload

begin brodeload
    DEFINE 0
end brodeload

begin constraint
    DEFINE 0
end constraint

begin contact_interior
    DEFINE 0
end contact_interior

begin contact_rigid
    DEFINE 0
end contact_rigid

begin initial_cfd
    DEFINE 0
end initial_cfd
}

proc aie_mesh_export {format fname {domain_file ""}} {
    global file_name env ansys_default_params lsdyna_default_params
    global cfx5_export patran_export solution use_workbench wb_gtmfile
    global wb_advanced_cfd_app_location
    global env tcl_platform is_win

    aie_clear_dez
    aie_saveProject 0 1

    if {($format == "cfx5") && [info exists use_workbench] && $use_workbench} {
        if {[info exists wb_advanced_cfd_app_location] && $wb_advanced_cfd_app_location != ""} {
            set path $wb_advanced_cfd_app_location
        } else {
            catch {load $env(ICEM_ACN)/bin/tclreg83.dll registry}
            catch {registry get "HKEY_LOCAL_MACHINE\\SOFTWARE\\ANSYS, Inc.\\v110\\APFramework\\Addins\\AdvancedCFD" "InstallDir"} path
        }
	    set exe [file join $path bin cfx5gtmconv]
	
    	if {$tcl_platform(platform) == "windows" } {
	        append exe .exe
	    }
	    if {![file exists $exe]} {
	        mess "Can't find CFX5 installation:  Conversion to CFX5 only, not to GTM.\n" orange
	    } else {
	        set format gtm
	    }
    }

    if {$format == "cfx5"} {
        set initfile "[file tail [file root $file_name(settings)]].msh"
    } elseif {$format == "gtm"} {
        set initfile "[file tail [file root $file_name(settings)]].gtm"
    } elseif {$format == "ls_dyna3d"} {
        set initfile "[file tail [file root $file_name(settings)]].k"
    } else {
    	set initfile "mesh.$format"
    }
    
    switch $format {
	    wpatran - radioss - exodus - ideas - stl - fluent - fluent6 { }
	    default {
	        set file [tk_getSaveFile -initialdir $file_name(project_dir) -initialfile $initfile -parent . \
                -title "Name for $fname file"]
	        if {$file == ""} return
	    }
    }
    
    set opts ""
    set bcfile ""
    set parfile ""
    set gtm_file ""
    set atrfile ""
    set topofile ""
    set ftofile ""

    if [info exists file_name(topo_mulcad_out)] {
	    set topofile $file_name(topo_mulcad_out) 
    }	
    if [info exists file_name(family_topo)] {
	    set ftofile $file_name(family_topo)
    }	
    switch $format {
	ansys {
	    global ansys_export_ignore_bar ansys_export_ignore_shell
	    global ansys_export_use_blocks ansys_export_make_comp ansys_export_precision
	    set opts ""
	    if ![info exists ansys_export_ignore_bar] { set ansys_export_ignore_bar 0 }
	    if ![info exists ansys_export_ignore_shell] { set ansys_export_ignore_shell 0 }
	    if ![info exists ansys_export_use_blocks] { set ansys_export_use_blocks 1 }
	    if ![info exists ansys_export_make_comp] { set ansys_export_make_comp 1 }
	    if ![info exists ansys_export_precision] { set ansys_export_precision 0 }
	    if {![dialog .ansys_export "ANSYS" \
		      "Please edit the following Ansys options." {
			  {ansys_export_ignore_bar -opt {{No 0} {Yes 1}} 
			      -title "Ignore BAR elements"}
			  {ansys_export_ignore_shell -opt {{No 0} {Yes 1}} 
			      -title "Ignore TRI & QUAD elements"}
			  {ansys_export_use_blocks -opt {{"blocked" 1} {"unblocked" 0}} 
			      -title "Blocked output"}
			  {ansys_export_make_comp -opt {{"yes" 1} {"no" 0}} 
			      -title "Write components"}
			  {ansys_export_precision -type string \
			      -title "Increased number of digits for node data"}
		      }]} return
	    
	    ##  THIS IS BOGUS but the cfx version needs it
	    batch_interp eval [list set ansys_default_params $ansys_default_params]
	    
	    if $ansys_export_ignore_bar {set opts "$opts -no_bar"}
	    if $ansys_export_ignore_shell {set opts "$opts -no_shell"}
	    if $ansys_export_use_blocks {set opts "$opts -use_blocks"}
	    if $ansys_export_make_comp {set opts "$opts -make_comp"}
	    if $ansys_export_precision {set opts "$opts -node_precision_up $ansys_export_precision"}
	    set atrfile $file_name(attributes)
	}
	ls_dyna3d {
	    global lsdyna_export_ignore_node lsdyna_export_ignore_bar lsdyna_export_ignore_shell
	    if ![info exists lsdyna_export_ignore_node] { set lsdyna_export_ignore_node 0 }
	    if ![info exists lsdyna_export_ignore_bar] { set lsdyna_export_ignore_bar 0 }
	    if ![info exists lsdyna_export_ignore_shell] { set lsdyna_export_ignore_shell 0 }
	    if {![dialog .lsdyna_export "LS-DYNA" \
		      "Please edit the following LS-Dyna options." {
			  {lsdyna_export_ignore_node -opt {{No 0} {Yes 1}} 
			      -title "Ignore NODE elements"}
			  {lsdyna_export_ignore_bar -opt {{No 0} {Yes 1}} 
			      -title "Ignore BAR elements"}
			  {lsdyna_export_ignore_shell -opt {{No 0} {Yes 1}} 
			      -title "Ignore TRI & QUAD elements"}
		      }]} return
	    if $lsdyna_export_ignore_node {set opts "$opts -ignore_node"}
	    if $lsdyna_export_ignore_bar {set opts "$opts -ignore_bar"}
	    if $lsdyna_export_ignore_shell {set opts "$opts -ignore_shell"}
	    set bcfile $file_name(family_boco)
	    set parfile ls_dyna3d.par
	    ic_param_save $parfile
	}
	cfx5 - cfx4 - tascflow - gtm {
	    global cfx_binary_output
	    if ![info exists cfx_binary_output] { set cfx_binary_output 0 }
	    if {$format == "tascflow" && !$is_win} {
            mess "Error: solver CFX-TASCflow is not available for this platform\n" red
		    return
	    }
	    if {$format == "cfx4"} {
            solution_set_solver CFX-4 1
            geo_famboco_edit
		    aie_save_attr
		    set bcfile $file_name(family_boco)
        }
	    if {$format == "cfx5" || $format == "tascflow"} {
	      if {![dialog .cfx5_export "CFX" \
		      "Please edit the following options." {
			  {cfx_binary_output -opt {{ASCII 0} {Binary 1}} 
			      -title "Output type"}
		      }]} return
	      if {$format == "cfx5" && !$cfx_binary_output} {set opts "$opts -ascii"}
	      if {$format == "tascflow" && $cfx_binary_output} {set opts "$opts -u"}
	    }
	    set d [form_init .cfx5opts "Scale factor" "" {done}]
	    if {$d != ""} {
		set cfx5_export(scale) "1.0,1.0,1.0"
		form_label $d.sfl "Scale factor" "0 0"
		form_entry $d.sfe cfx5_export(scale) string "0 1"
		form_finish +300+300
	    }
	    if [form_wait .cfx5opts] {
		if {$cfx5_export(scale) != "1.0,1.0,1.0"} {
		    set opts "$opts -scale $cfx5_export(scale)"
		}
	    }
	    if {$format == "gtm"} {
		set gtm_file $file
		set wb_gtmfile $file
		set file [file root $file].msh
	    }
	}
	abaqus {
	}
	radioss {
	    set osol $solution(solver)
	    solution_set_solver RADIOSS 1   
	    solution_input
	    solution_set_solver $osol 1
	    return
	}
	wpatran {	 
	    set osol $solution(solver)
	    solution_set_solver Patran 1   
	    solution_input
	    solution_set_solver $osol 1
	    return
#	    set d [form_init .patranopts "Patran options" "" {done}]
#	    if {$d != ""} {
#		set patran_export(pid) 0
#		form_checkbutton $d.pid "Create regions" patran_export(pid) {0 0}
#		form_finish +300+300
#	    }
#	    if ![form_wait .patranopts] return
#	    if $patran_export(pid) {
#		set opts "-pid"
#	    }
#	    set bcfile $file_name(family_boco)
	}
	exodus {
	    set osol $solution(solver)
	    solution_set_solver EXODUS-II 1
	    solution_input
	    solution_set_solver $osol 1
	    return
	}
	ideas {
#	    set bcfile $file_name(family_boco)
#	    set opts "-shell"
	    set osol $solution(solver)
	    solution_set_solver IDEAS 1
	    solution_input
	    solution_set_solver $osol 1
	    return
	}
	stl {
	    set osol $solution(solver)
	    solution_set_solver STL 1
	    solution_input
	    solution_set_solver $osol 1
	    return
	}
	fluent - fluent6 {
	    if {$format == "fluent"} {
           solution_set_solver Fluent_V4 1
           geo_famboco_edit
	       aie_save_attr
	       set bcfile $file_name(family_boco)
	       solution_input
	       return
        }
	    if {$format == "fluent6"} {
           #solution_set_solver Fluent_V6 1
           solution_set_solver "ANSYS Fluent" 1
           geo_famboco_edit
	       aie_save_attr
	       set bcfile $file_name(family_boco)
	       solution_input
	       return
	    }
	}
    }
    
    if {$domain_file != ""} {
	set dom $domain_file
    } else {
	set dom $file_name(domain)
    }
    if {$dom == ""} {
	user_error "No domain file is available - please load one\n"
	return
    }
    busy 1
    if [catch {ic_export_mesh format $format domfile $dom file $file bcfile $bcfile parfile $parfile gtm_file $gtm_file atrfile $atrfile topofile $topofile ftofile $ftofile opts $opts} res] {
	busy reset
    	mess "Error: $res\n" red
	busy reset
    } else {
    	mess "$res\n"
    }    
    busy 0
}

proc aie_show_legal_notice {} {
    global env AppName Version

  if 0 {    
    if [file exists $env(ICEM_ACN)/lic/legal_notice.txt] {
	set file [file join $env(ICEM_ACN) lic "legal_notice.txt"]
	set Editor [::AIEnv::GUIManagement::Widgets::TextEditor::TextEditor]
	$Editor create "readonly"  "$AppName $Version Legal Notice"
	::AIEnv::GUIManagement::Widgets::TextEditor::Open $Editor $file
    }
  }

  legalnotice_book

}

proc aie_mesh_to_facets { {ask 1} {sharp_feature 1} } {
    if ![ic_uns_is_loaded] {
	    user_error "No mesh is currently loaded"
	    return
    }
    if [ic_geo_is_loaded] {
	    set opt [tk_dialog .tetinOverwrite "Geometry Exists" \
		    "Geometry Already Exists" "" 1 "Merge" "Replace" "Cancel"]
	    switch -- $opt {
	        0 { }
	        1 { ic_unload_tetin  
	        mess "   --- Unloading existing geometry" }
	        2 - -1 {
	            if [winfo exists .tetinOverwrite] { destroy .tetinOverwrite }
	            return
	        }
	    }
    }
    switch $ask {
	    0 {
	        if $sharp_feature {ic_uns_build_mesh_topo All -angle 150 -smart}
	        set do_merge 1
	    }
	    1 {
	        if {[ tk_dialog .build_mesh_topo "Create sharp features?"  "Do you want to build in sharp features?" "" -1 Yes No ]}  {

	        } else {
	            if [winfo exists .build_mesh_topo] { destroy .build_mesh_topo }
		        ic_uns_build_mesh_topo All -angle 150 -smart
		    }
	        set do_merge [expr ![tk_dialog .merge_cl Merge "Merge close nodes in the surfaces?" "" -1 Yes No]]
	        if [winfo exists .merge_cl] { destroy .merge_cl }
	    }
    }
    ic_geo_import_mesh {} 1 1 $do_merge

    global file_name tdv_default
    global aie_ShowCurveAttachment
    global aie_geoTypeVis
    set file_name(tetin_loaded) 1
 
    
    # Create Bodies for material points unattached to body
    #aie_build_volumes
    
    aie_initGeoVis
    ic_geo_set_modified 1

    # To avoid DEZ dependencies
    aie_clear_dez
    
    # Make sure we have at least Global
    aie_load_lcs
    aie_update_icons geom
}

proc aie_facets_to_mesh {} {
    if [ic_uns_is_loaded] {
	    set opt [tk_dialog .meshx "Mesh Exists" "A mesh already exists: how do you wish to proceed?" \
		    "" 1 "Replace" "Cancel" ]
	    switch -- $opt {
	        0 {
		        aie_close_Mesh
	        }
	        1 - -1 {
	            if [winfo exists .meshx] { destroy .meshx }
		        return
	        }
	    }
    }
    
    ic_geo_export_to_mesh 1
    aie_after_open_mesh 1 0
}

proc aie_str_mesh_to_cad {} {
    global tdv_default file_name

    if {![ic_str_is_loaded]} {
	set domains [tk_getOpenFile -title "Select structured domains" -filetypes {{{Structured domains} domain.*} {{All files} *}} \
		-multiple 1 -parent .]
	if {$domains == ""} return
    } else {
	if {[ic_str_domain_dimension 1] != 2} {
	    mess "You must use a surface only mesh.\n" red
	    mess "Use \"Blocking->Create Block->3D to 2D.\" Then \"Save Multiblock Mesh.\"\n" red
	    return
	}
	for {set i 0} {[file exists [set temp temp$i]]} {incr i} {}
	file mkdir $temp
	mess "Writing temporary mesh.\n"
	ic_str_save $temp $temp/topo.top $temp/ftopo.fto $temp/subf_proj domain.
	foreach d [ic_str_list_entities domain] { lappend domains $temp/domain.$d }
    }
    tdv_active 0
	set err [catch {ic_geo_import_str_to_cad $domains} res]
	if [info exists temp] {file delete -force -- $temp}
    tdv_active 1
    if {$err || ![llength $res]} {
	busy reset
	mess "$res\n" red
	return
    }
    set file_name(tetin_loaded) 1
    aie_afterStuffLoaded
    aie_viewInfo geometry
    aie_initGeoVis
    ic_geo_set_modified 1
    aie_clear_dez
    aie_init_geom_subsets
    tdv_scale_to_fit $tdv_default
}

proc aie_str_mesh_to_superdomain {} {
    if ![ic_str_is_loaded] {
        msg ERROR "No structured mesh loaded"
        return
    }
    output_super ;# in lib/med_gui/solution_med.tcl
}

proc aie_str_mesh_to_uns {} {
    if ![ic_str_is_loaded] {
        msg ERROR "No structured mesh loaded"
        return
    }
    output_s2u
    aie_afterStuffLoaded
}

proc aie_export_mesh_lspre {} {
    if ![ic_hex_blocking_loaded] {
        msg ERROR "No blocking loaded"
        return
    }
    aie_convert_hexa_mesh uns
    ic_param_set_values :def_solid {write 1}
    ic_param_set_values :def_shell {write 1}
    ic_param_set_values :def_beam {write 1}
    ic_param_set_values :def_node {write 1}

    aie_mesh_export ls_dyna3d LS-DYNA3D hex.uns
}


# save the dez data along with the project settings
proc aie_save_dez_data {file} {
    set fp [open $file a]
    ::AIEnv::GUIManagement::WriteDEZData $fp
    close $fp
}

# save topo tolerance if set by user along with the project settings
proc aie_save_user_topo_tolerance {file} {
    global geo_cad
    if {[info exists geo_cad(toptol_userset)] && $geo_cad(toptol_userset) == "1"} {
        set fp [open $file a]
        puts $fp "set geo_cad(use_toptol_userset) 1"
        puts $fp "set geo_cad(toler) $geo_cad(toler)"
        close $fp
    }
}

proc aie_backward_compatibility {} {
    global env mesh_option hex_option
    
    if [info exists mesh_option(project_bspline)] {
        if [string is integer -strict $mesh_option(project_bspline)] {
            set hex_option(project_bspline) $mesh_option(project_bspline)
        }
        unset mesh_option(project_bspline)
    }
    if ![info exists env(AI_ENV_QUAD)] return
    # the Quad Parameters moved to Shell Meshing Parameters
    set data [namespace eval ::AIEnv::GUIManagement::DEZ "array get meshQuadDEZ_data"]
    if {$data != ""} {
        foreach {n v} $data {
            if {$n == "remove_old"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {remove_old $v}"
            } elseif {$n == "simple_offset"} {
                set simple_offset "Standard"
                switch $v {
                    1 { set simple_offset "Simple" }
                    2 { set simple_offset "Forced simple" }
                }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {simple_offset2 $simple_offset}"
            } elseif {$n == "bunch"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {bunch_respect $v}"
            } elseif {$n == "protect"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {protect_line $v}"
            } elseif {$n == "b_smooth"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {bound_smooth $v}"
            } elseif {$n == "block"} {
                if {$v == ""} { set v 0.2 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {block_mapping $v}"
            } elseif {$n == "adjust_nodes_max"} {
                if {$v == ""} { set v 0.0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {adjust_nodes_max $v}"
            } elseif {$n == "projection"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {proj_surf $v}"
            } elseif {$n == "use_surface_sizes"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {surf_size $v}"
            } elseif {$n == "MaxDev"} {
                if {$v == ""} { set v 0.0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {max_dev $v}"
            } elseif {$n == "ignore"} {
                if {$v == ""} { set v 0.01 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {ign_size $v}"
            } elseif {$n == "try_harder"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {try_harder $v}"
            } elseif {$n == "improvement"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {impr_level $v}"
            } elseif {$n == "dormant"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {mesh_dormant $v}"
            } elseif {$n == "smoothdormant"} {
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {smooth_dormant $v}"
            } elseif {$n == "max_area"} {
                if {$v == ""} { set v 0.0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {max_area \"$v\"}"
            } elseif {$n == "max_length"} {
                if {$v == ""} { set v 0.0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {max_length \"$v\"}"
            } elseif {$n == "min_angle"} {
                if {$v == ""} { set v 0.0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {min_angle \"$v\"}"
            } elseif {$n == "max_nodes"} {
                if {$v == ""} { set v 0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {max_nodes \"$v\"}"
            } elseif {$n == "max_elements"} {
                if {$v == ""} { set v 0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {max_elements \"$v\"}"
            } elseif {$n == "elType"} {
                if {$v != "All Quad" && $v != "Quad w/one Tri" && \
                    $v != "Quad Dominant" && $v != "All Tri"} {
                    set type "All Tri"
                } else {
                    set type $v
                }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {mesh_type2 \"$type\"}"
            } elseif {$n == "iterations"} {
                if {$v == ""} { set v 20 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {iters_tet $v}"
            } elseif {$n == "MinEdge"} {
                if {$v == ""} { set v 0.0 }
                namespace eval ::AIEnv::GUIManagement::DEZ \
                    "array set mszGlobalDEZ_data {min_edge \"$v\"}"
            }
        }
        namespace eval ::AIEnv::GUIManagement::DEZ "array unset meshQuadDEZ_data"
    }
    set data [namespace eval ::AIEnv::GUIManagement::DEZ "array get repairMeshDEZ_data"]
    if {$data != ""} {
        foreach {n v} $data {
            if {$n == "offsetSimpleFlag"} {
                switch $v {
                    0 {
                        namespace eval ::AIEnv::GUIManagement::DEZ \
                            "array set repairMeshDEZ_data {offsetSimpleFlag Standard}"
                    }
                    1 {
                        namespace eval ::AIEnv::GUIManagement::DEZ \
                            "array set repairMeshDEZ_data {offsetSimpleFlag Simple}"
                    }
                }
            }
        }
    }
}

proc aie_open_cart {{ask 1} {crt_file ""}} {
    global file_name tdv_default
    global cartfile_visible

    if ![file isdirectory $file_name(project_dir)] {set_project_dir .}
    if {$crt_file != ""} {
        set ft $crt_file
    } else {
        set ft $file_name(cart_file)
        if {(![file isfile $file_name(cart_file)]) || $ask == 1} {
            set ft [tk_getOpenFile -initialdir $file_name(project_dir) \
                -filetypes {{{Cartesian Files} {.crt}} {{All Files} *}} \
                -initialfile [file tail $ft] -parent .]
       }
    }
    if {$ft == ""} return
    if [ic_cart_is_loaded] {
        set opt [tk_dialog .blockOverwrite "Cartesian grid Exists" \
		     "Cartesian Grid Already Exists in this File, how do you wish to proceed?" \
		     "" -1 "Replace" "Cancel" ]
	    switch -- $opt {
	        0 {aie_close_cart}
	        1 - -1 {
	            if [winfo exists .blockOverwrite] { destroy .blockOverwrite }
	            return
	        }
	    }
    }
    aie_clear_dez
    if [catch {ic_cart_load $ft} res] {
        mess "Error in opening Cartesian file; $res\n" red
        busy reset
        return
    }

    set file_name(cart_file) $ft
    set file_name(cart_file_loaded) 1
    ic_cart_visible 1
    set cartfile_visible 1

    tdv_home $tdv_default
}

proc aie_close_cart {{confirm 1} {skip 0}} {
    global file_name

    if ![ic_cart_is_loaded] return
    set cart_modified [file_needs_save cart_file]
    if {($cart_modified) && ($confirm)} {
        set opt [tk_dialog .savecart "Save Cartesian Grid" "Do you want to Save the current cartesian grid?" \
		     "" -1 Yes No Cancel]
        switch -- $opt {
            0 {
		        aie_save_cart
		    }
            1 { }
            2 {
                if [winfo exists .savecart] { destroy .savecart }
                return
            }
        }
    }
    ic_cart_unload
    set file_name(cart_file) ""
    set file_name(cart_file_loaded) 0
    aie_clear_dez
    ic_cart_is_modified 0
    if !$skip { aie_delete_empty_parts 0 }
    aie_update_lcs
}

proc aie_saveas_cart {} {
    aie_save_cart 1
}

proc aie_save_cart {{ask 0}} {
    global file_name

    if {$file_name(cart_file) != "" && $ask} {
        set pref [file tail [file rootname $file_name(cart_file)]]
    } else {
        set pref [file tail [file rootname $file_name(settings)]]
    }
    if {$ask || ($pref == "" && $file_name(cart_file) == "")} {
        set fm [tk_getSaveFile -initialdir [pwd] -initialfile $pref.crt -parent . \
		    -filetypes {{{Cartesian Files} {.crt}} {{All files} *}}]
        if {$fm == ""} return ""
        if {[file extension $fm] != ".crt"} {
            set fm $fm.crt
        }
        set file_name(cart_file) $fm
    } elseif {$file_name(cart_file) == ""} {
        set file_name(cart_file) [file join . $pref.crt]
    }
    ic_cart_save $file_name(cart_file)
    ic_cart_is_modified 0
    if [info exists file_name(cart_meshfile)] {
        set cart_meshfile "[file root [file tail $file_name(cart_file)]].cartmesh"
        if  {$file_name(cart_meshfile) != $cart_meshfile} {
            cmd_mv $file_name(cart_meshfile) $cart_meshfile
            mess "Moved cartesian material data to $cart_meshfile\n"
            set file_name(cart_meshfile) $cart_meshfile
        }
    }
    return $file_name(cart_file)
}


proc onexportSpectralElementsDEZLoad {} {
    set specelDiag_list [list "Gauss-Lobatto-Legendre" "Chebyshev-Lobatto" "Legendre"]
    set specelDiag_val "Gauss-Lobatto-Legendre"
    set exportSpectralElementsVal 0
    set order 2
}

proc onexportSpectralElementsDEZOK {} {
    global spectral
    if ![ic_uns_is_loaded] {
      user_error "No mesh is currently loaded"
      return
    }
    if {![file isdirectory $file_name(project_dir)] || $file_name(project_dir) == ""} {
      set_project_dir .
    }
    set file $file_name(project_dir)/spectral_elem_file
    if {[file exists $file]} {
        set tmess "File $file exists - overwrite?"
        if [tk_dialog .overwrite Overwrite $tmess "" -1 Yes No] { 
            set file [med_file_select default 1 $file]
        } else {
            if [winfo exists .overwrite] { destroy .overwrite }
        }
    }
    if {$file != ""} {
      if ![info exists spectral(bunch_law)] {
        set spectral(bunch_law) 8
      }
      if ![info exists spectral(order)] {
        set spectral(order) 2
      }

      set spectral(order) $order
      switch $specelDiag_val {
          "Gauss-Lobatto-Legendre" {
            set spectral(bunch_law) 8
          }
          "Chebyshev-Lobatto" {
            set spectral(bunch_law) 10
          }
          "Legendre" {
            set spectral(bunch_law) 9
          }
      }
      busy 1
      if { $exportSpectralElementsVal} {
          if {$elemListSpectralElem == ""} {
              mess "Warning: No Elements Selected for \"Spectral elements\".\n" red
              return
          } else {
              ic_uns_spectral_elements $elemListSpectralElem $file $spectral(order) $spectral(bunch_law)
          }
      } else {
          ic_uns_spectral_elements all $file $spectral(order) $spectral(bunch_law)
      }
      busy 0
    }
}


proc aie_print_project_info {} {
    global project_file_header file_name

    if {([info exists project_file_header]) && $project_file_header != ""} {
        mess "[join $project_file_header]" blue
        if {[ic_geo_is_loaded] && $file_name(tetin) != ""} {
            mess "  Geometry file is loaded\n" blue
        }
        if {([ic_uns_is_loaded] || [ic_str_is_loaded]) && $file_name(domain) != ""} {
            mess "  Mesh file is loaded\n" blue
        }
        if {[ic_hex_blocking_loaded] && $file_name(blocking) != ""} {
            mess "  Blocking file is loaded\n" blue
        }
        if {[ic_boco_is_loaded] && ($file_name(family_boco) != "" || $file_name(attributes) != "")} {
            mess "  Attributes file is loaded\n" blue
        }
        if {[ic_param_is_loaded] && $file_name(solver_params) != ""} {
            mess "  Parameter File is loaded\n" blue
        }
        if {[ic_cart_is_loaded] && $file_name(cart_file) != ""} {
            mess "  Cartesian file is loaded\n" blue
        }
    }
}

proc aie_clear_materials_tables {} {
    global material_data material_type material_tbl_data material_tbl_type
    global material_dpnd_data
    global mat_name_list tbl_name_list

    catch {unset material_data}
    catch {unset material_type}
    catch {unset material_tbl_data}
    catch {unset material_tbl_type}
    catch {unset material_dpnd_data}
    catch {unset mat_name_list }
    catch {unset tbl_name_list}

    catch {
       foreach mat [ic_param_list_children :Isotropic_Material] {
          ic_param_delete_node $mat
       }
    }
    catch {
      foreach mat [ic_param_list_children :Anisotropic_Shell_Material] {
          ic_param_delete_node $mat
       }
    }
    catch {
       foreach mat [ic_param_list_children :Anisotropic_Solid_Material] {
           ic_param_delete_node $mat
       }
    }
    catch {
       foreach mat [ic_param_list_children :Orthotropic_Shell_Material] {
          ic_param_delete_node $mat
       }
    }
    catch {
       foreach mat [ic_param_list_children :Isotropic_Thermal_Material] {
          ic_param_delete_node $mat
       }
    }
    catch {
       foreach mat [ic_param_list_children :Anisotropic_Thermal_Material] {
          ic_param_delete_node $mat
       }
    }

    catch {
       foreach mat_tbl [ic_param_list_children :Material_Property_Table] {
          ic_param_delete_node $mat_tbl
       }
    }
    catch {
       foreach mat_tbl [ic_param_list_children :Stress_Dependent_Material_Property_Table] {
          ic_param_delete_node $mat_tbl
       }
    }
    catch {
       foreach mat_tbl [ic_param_list_children :Nonlinear_Material_Temp_Dependence_Tables] {
          ic_param_delete_node $mat_tbl
       }
    }
    catch {
       foreach mat_tbl [ic_param_list_children :Dynamic_Load_Table] {
          ic_param_delete_node $mat_tbl
       }
    }
    catch {
       foreach mat_tbl [ic_param_list_children :Modal_Damping_Table] {
          ic_param_delete_node $mat_tbl
       }
    }
    
}

proc aie_clear_params {} {
    global params_data params_type
    global subcase_data
    global param_name_list

    catch {unset params_data}
    catch {unset params_type}
    catch {unset param_name_list}
    
    catch {
       foreach ch [ic_param_list_children :EXEC] {
          ic_param_delete_node $ch
       }
    }
    catch {
       foreach ch [ic_param_list_children :Output_Selection] {
          ic_param_delete_node $ch
       }
    }
    catch {
       foreach ch [ic_param_list_children :Parameter] {
          ic_param_delete_node $ch
       }
    }
    
# clear Subcases
    catch {unset subcase_data}
    catch {
       foreach ch [ic_param_list_children :Subcase] {
          ic_param_delete_node $ch
       }
    }

# clear prams
    foreach type {EIGRL EIGB NLPARM TSTEP FREQ FREQ1 FREQ2 DAREA DELAY DPHASE TLOAD1 TLOAD2 RLOAD1 RLOAD2 \
                          DLOAD LOAD EIGR SPCADD MPCADD TEMPD Gravity_Load INCLUDE} {
       catch {
          foreach ch [ic_param_list_children :$type] {
             ic_param_delete_node $ch
          }
       }
    }
    
}

proc aie_update_lcs {} {
    global lcs_name_list

    if ![info exists lcs_name_list] { set lcs_name_list "" }

    # clean up LCS(s) and reset if needed
    if {[llength $lcs_name_list] > 0} {
       set non_empty {}
       set non_empty [concat $non_empty [::AIEnv::GUIManagement::Tree::GetChildren partNode]]
       if {[llength $non_empty] <= 0} {
          foreach n  {matNode partbcNode connectorNode constrainednodesNode contactNode displacementNode impdispNode mpcdispNode \
                            loadNode rigidwallNode singlecontactNode temperatureNode velocityNode} {
             set non_empty [concat $non_empty [::AIEnv::GUIManagement::Tree::GetChildren $n]]
          }
       }

       if {[llength $non_empty] > 0} {
          aie_load_lcs
       } else {
          foreach lcname $lcs_name_list {
             aie_delete_lcs lcs $lcname
          }
          catch {unset lcs_name_list}
       }
    }
}




