proc aie_wb_update_project {{opt 0} {do_update 1} } {
    aie_wb_brep_load $opt $do_update
    if { $opt == 0 } {
        # opt for mesh is opposite from geometry.
        set opt 1
    } else {
        set opt 0
    }

    catch { [aie_wb_update_blocking] } err
    if { [ic_hex_blocking_loaded] == 0 } {
        #always do a mesh update.
        aie_wb_dsmesh_load $opt 1 
    }
}

proc aie_wb_brep_attach {} {
    after 500 aie_wb_brep_attach_start
    return 1
}

proc aie_wb_brep_attach_start {} {
    global wb_geometry_file 

    busy 1
    set load_file ""
    if { [info exists wb_geometry_file] && \
         [file extension $wb_geometry_file] != ".prj" } {
        set load_file $wb_geometry_file
    }
    if [catch {ic_wb_brep_attach} res] {
        mess "Error: $res\n" red
        busy 0
    	return 1
    }
    busy 0
    return 1
}

proc aie_wb_brep_load {{opt 0} {do_update 0} {gui_init 0}} {
    after 500 aie_wb_brep_load_start $opt $do_update $gui_init
    return 1
}
 
proc aie_wb_brep_load_start {{opt 0} {do_update 0} {gui_init 0} } {
    global wb_geometry_file file_name geo_cad wb_primary_file wb_initProjName wb_tetin_file 
    global prompt_for_bld_topo prompt_for_bld_topo_opts named_selections_as_parts
    global wb_module_name wb_pm_assem_id wb_tetin_file_is_new

   # this should be done inside inside the brep translation - Ganesan
    set block_fams [ic_hex_list_block_families]
    if {[info exists wb_primary_file] && $wb_primary_file != ""} {
        set wb_tetin_file [file root $wb_primary_file].tin
    } elseif {[info exists wb_initProjName] && $wb_initProjName != ""} {
        set wb_tetin_file ${wb_initProjName}.tin
    } else {
        set wb_tetin_file ./foo.tin
        mess $file_name(tetin)
    }
    if { [ic_geo_is_loaded] } {
        switch -- $opt {
            0 {
                #save existing geometry
                if [catch {ic_save_tetin $wb_tetin_file}] {
                    mess "Warning -- unable to save old data in $wb_tetin_file\n"
                }
                #replace geometry
                aie_close_geom 0
                mess "   --- Unloading existing geometry\n"
            }
            1 { set merge 1 }
            2 { return 1 }
        }
    } 

    ic_undo_suspend
    busy 1
    mess "Loading Geometry\n"
    set load_file ""
    if { [info exists wb_geometry_file] && \
         [file extension $wb_geometry_file] != ".prj" } {
        set load_file $wb_geometry_file
    }


    if { ![info exists wb_module_name] || $wb_module_name == 0 || $wb_module_name == "NULL" } {set wb_module_name ""}
    if { ![info exists wb_pm_assem_id] } { set wb_pm_assem_id 0xFFFFFFFF }

    if { $load_file == "" && $wb_module_name == "" && $wb_pm_assem_id != 0xFFFFFFFF } {
        # assembly id parameter will only work for an update.
        set do_update 1
    }

    set result 0
    if [catch {ic_wb_brep_load $load_file $wb_module_name $do_update 
            $wb_pm_assem_id $named_selections_as_parts} result ] {
        mess "Error: $result\n" red
        busy 0
    	return 1
    } else {
        if {[info exists result] && $result} {
            mess "Model requires repair using build topology\n"
            set doit yes
            set topo_mess "Run build topology?"
            if { [info exists prompt_for_bld_topo] && $prompt_for_bld_topo } {
                set doit [tk_messageBox -type yesno -message $topo_mess]
            }
            if {$doit == "yes"} {
                set geo_cad(toler)        [aie_default_topo_tolerance]
                set geo_cad(filter_points) 0
                set geo_cad(filter_curves) 0
                set geo_cad(reg_surfs)     0
                set geo_cad(concat_crvs)   0
                set geo_cad(quiet)         1
                if { [ info exists geo_cad(all_fams) ] == 0 } {
                    set geo_cad(all_fams) 1
                }
                if { [ info exists geo_cad(create_interior) ] == 0 } {
                    set geo_cad(create_interior) 1
                }
                if $prompt_for_bld_topo_opts {
                    geo_build_topo
                }
                mess "    building topology with tolerance $geo_cad(toler)\n"
                if [catch {geo_clean_apply} result] {
                    mess "Error: $res\n"
                }
            }
        }
    }
    #
    #  Map old parameters to new
    if {[file exists $wb_tetin_file] && [info exists wb_tetin_file_is_new] && 
            $wb_tetin_file_is_new != 1 } {
        set foundit "Found existing tetin file, $wb_tetin_file.  Transfer mesh parameters?"
        set doit yes
        if !$do_update {
            set doit [tk_messageBox -type yesno -message $foundit]
        }
        if {$doit == "yes"} {
            mess "Transferring meshing parameters from old tetin db at $wb_tetin_file\n"
            if [catch {ic_geo_map_tetin_sizes $wb_tetin_file} res] {
                mess "Warning: $res\n"
            }
        }
    } else {
        mess "Old meshing data unavailable at $wb_tetin_file\n"
    }

    foreach fam $block_fams {
	if {$fam != "VORFN"} {
		aie_new_part $fam
    	}
     }

    if {!$do_update || $gui_init} {
        aie_afterStuffLoaded
        aie_initGeoVis
    } else {
        aie_afterStuffLoaded 0
    }
    aie_build_volumes
    update

    mess "Geometry Load Done\n"
    busy 0
    ic_undo_resume
    return 1
}

proc aie_wb_tetin_load {{opt 0} {do_update 0} {gui_init 0} {suppress_dialogs 0} } {
    after 500 aie_wb_tetin_load_start $opt $do_update $gui_init $suppress_dialogs
    return 1
}
 
#
#  wb_geometry_file -- the name of the original geometry, "" if created in DM but not yet saved.
#  wb_geom_load_file -- the name of the tetin file to be loaded
#  wb_initProjName -- the initial project name
#  wb_tetin_file -- the current tetin file name (?)
#  wb_module_name -- name of the module to be loaded (may be "")
#  wb_pm_assem_id -- id of the assembly to be loaded (may be "" or 0)
#  wb_ic_load_result -- the result which the applet got from the ic library upon translation.
#

proc aie_wb_tetin_load_start {{opt 0} {do_update 0} {gui_init 0} {suppress_dialogs 0}} {
    global wb_geometry_file file_name geo_cad wb_primary_file 
    global wb_initProjName wb_tetin_file 
    global prompt_for_bld_topo prompt_for_bld_topo_opts named_selections_as_parts
    global wb_module_name wb_pm_assem_id wb_geom_load_file
    global wb_ic_load_result wb_tetin_load_busy wb_tetin_file_is_new

   # this should be done inside inside the brep translation - Ganesan
    set wb_tetin_load_busy 1
    set block_fams [ic_hex_list_block_families]
    if {[info exists wb_primary_file] && $wb_primary_file != ""} {
        set wb_tetin_file [file root $wb_primary_file].tin
    } elseif {[info exists wb_initProjName] && $wb_initProjName != ""} {
        set wb_tetin_file ${wb_initProjName}.tin
    } else {
        set wb_tetin_file ./foo.tin
        mess $file_name(tetin)
    }
	# make sure that wb_tetin_file is different than wb_geom_load_file
	# (see Onyx 53015) - Ulrike
    if { $wb_tetin_file == $wb_geom_load_file } {
        set wb_tetin_file [file root $wb_geom_load_file].1.tin
    }
    
    if { [ic_geo_is_loaded] } {
        switch -- $opt {
            0 {
                #save existing geometry
                if [catch {ic_save_tetin $wb_tetin_file}] {
                    mess "Warning -- unable to save old data in $wb_tetin_file\n"
                }
                #replace geometry
                aie_close_geom 0
                mess "   --- Unloading existing geometry\n"
            }
            1 { set merge 1 }
            2 { 
    		set wb_tetin_load_busy 0
		return 1 
	    }
        }
    } 

    #  Map old parameters to new
    set load_file ""
    set should_delete 1
    if { [info exists wb_geom_load_file] && \
         [file extension $wb_geom_load_file] != ".prj" } {
        if { $wb_geom_load_file == "" } {
            set wb_geom_load_file "[pwd]/icwbgeom.tin"
        }
        if { $wb_geom_load_file == $wb_geometry_file } {
            #output file is same as input, don't delete.
            set should_delete 0
        }
        set load_file $wb_geom_load_file
        global is_win
        if { $is_win } {
            set load_file [win_shortname $load_file]
        }
    } else {
	set wb_tetin_load_busy 0
        return 0;
    }
    if { $load_file == "" || ![file exists $load_file]} {
	set wb_tetin_load_busy 0
        return 0;
    }

    ic_undo_suspend
    busy 1
    mess "Loading Geometry\n"
    #
    if {$do_update} {
        mess "requesting geometry update...\n"
        set is_new 1
        if {[file exists $load_file] && $should_delete} {
            set is_new 0
            file delete $load_file
        }
        if { $wb_geom_load_file != $wb_geometry_file } {
            #output file is not same as input, needs to be translated.
            if [catch { AIEWBSendToWBScript "AIEUpdatePMToTetin" } err ] {
                mess "err = $err\n"
            }
        }
        mess "request for geometry update done...\n"
        if {![file exists $load_file]} {
            busy 0
            ic_undo_resume
            set wb_tetin_load_busy 0
            return 0
        }
        set wb_tetin_file_is_new $is_new
    }

    # Open the file!
    aie_open_geom 0 $load_file

    if {[info exists wb_ic_load_result] && $wb_ic_load_result} {
        if { $wb_ic_load_result == -100} {
            mess "Null assembly encountered\n"
            busy 0
            ic_undo_resume
            set wb_tetin_load_busy 0
            return 0
        }
        mess "Model requires repair using build topology\n"
        set doit yes
        set topo_mess "Run build topology?"
        if { [info exists prompt_for_bld_topo] && $prompt_for_bld_topo && $suppress_dialogs==0 } {
                set doit [tk_messageBox -type yesno -message $topo_mess]
        }
        if {$doit == "yes"} {
            set geo_cad(toler)        [aie_default_topo_tolerance]
            set geo_cad(filter_points) 0
            set geo_cad(filter_curves) 0
            set geo_cad(reg_surfs)     0
            set geo_cad(concat_crvs)   0
            set geo_cad(quiet)         1
            if { [ info exists geo_cad(all_fams) ] == 0 } {
                set geo_cad(all_fams) 1
            }
            if { [ info exists geo_cad(create_interior) ] == 0 } {
                set geo_cad(create_interior) 1
            }
            if $prompt_for_bld_topo_opts {
                geo_build_topo
            }
            mess "    building topology with tolerance $geo_cad(toler)\n"
            if [catch {geo_clean_apply} result] {
                mess "Error: $res\n"
            }

        }
    }

    if {[file exists $wb_tetin_file] && [info exists wb_tetin_file_is_new] && 
            $wb_tetin_file_is_new != 1 } {
        set foundit "Found existing tetin file, $wb_tetin_file.  Transfer mesh parameters?"
        set doit yes
        if {!$do_update && $suppress_dialogs==0} {
            set doit [tk_messageBox -type yesno -message $foundit]
        }
        if {$doit == "yes"} {
            mess "Transferring meshing parameters from old tetin db at $wb_tetin_file\n"
            if [catch {ic_geo_map_tetin_sizes $wb_tetin_file} res] {
                mess "Warning: $res\n"
            }
        }
    } else {
        mess "Old meshing data unavailable at $wb_tetin_file\n"
    }

    foreach fam $block_fams {
	if {$fam != "VORFN"} {
		aie_new_part $fam
    	}
     }

    if {!$do_update || $gui_init} {
        aie_afterStuffLoaded
        aie_initGeoVis
    } else {
        aie_afterStuffLoaded 0
    }
    aie_build_volumes
    update

    mess "Geometry Load Done\n"
    busy 0
    ic_undo_resume
    set wb_tetin_load_busy 0
    return 1
}
proc aie_wb_dsmesh_load {{opt 0} {do_update 0}} {
    after 500 aie_wb_dsmesh_load_start $opt $do_update
    return 1
}
 
proc aie_wb_dsmesh_load_start {{opt 0} {do_update 0}} {
    global wb_dsMeshFile file_name
    global wb_tetin_load_busy

    if {![info exists wb_dsMeshFile] || $wb_dsMeshFile == ""} {
        return 0
    }

    if {![file exists $wb_dsMeshFile] && $do_update == 0} {
        return 0
    }

    if {[info exists wb_tetin_load_busy] && $wb_tetin_load_busy == 1} {
    	after 500 aie_wb_dsmesh_load_start $opt $do_update
	return 0
    }

    ic_undo_suspend

    if {$do_update} {
        mess "requesting mesh update...\n"
    	busy 1
        if [catch { AIEWBSendToWBScript "AIEWriteDomainFile" } err ] {
            mess "err = $err\n"
        }
	busy 0
        mess "request for mesh update done...\n"
        if {![file exists $wb_dsMeshFile]} {
            return 0
        }
    }

    mess "Loading Simulation Mesh\n"
    set file_name(domain) $wb_dsMeshFile
    aie_open_Mesh 0 "" $opt
    aie_afterStuffLoaded 
    aie_thickness create 
    mess "Simulation Mesh Load Done\n"
    ic_undo_resume

    return 1
}

proc aie_wb_saveProject {{ask 0} {only_if_needed 0}} {
    aie_saveProject $ask $only_if_needed
    return 1
}

proc aie_wb_updateProject { {context ""} {do_update 0} } {
    after 500 aie_wb_updateProject_start $context $do_update
    return 1
}

proc aie_wb_updateProject_start { {context ""} {do_update 0} } {
    global file_name wb_curdir wb_dsMeshFile lastInitProjName wb_initProjName
    #Always ask to save project
    switch -- [tk_dialog .saveold Save "The currently selected link in the Project Page has changed.  Update geometry and/or mesh?" \
                "" -1 "Yes and Save Project" Yes Cancel] {
        -1 {
            if [winfo exists .saveold] { destroy .saveold }
            return 0
        }
        0 { 
            set tmpProjName ""
            if {[info exists lastInitProjName] && $lastInitProjName != ""} {
                set tmpProjName $wb_initProjName
                set wb_initProjName $lastInitProjName
            }
            aie_saveProject 1 
            if {[info exists lastInitProjName] && $lastInitProjName != ""} {
                set wb_initProjName $tmpProjName
            }
        }
        1 { }
        2 { return 0 }
    }
    aie_closeProject 0
    set tmpMeshName ""
    if {$context == "DM" && [info exists wb_dsMeshFile] && 
        $wb_dsMeshFile != "" && [file exists $wb_dsMeshFile]} {
        set tmpMeshName [file rootname $wb_dsMeshFile]
        set tmpMeshName "${tmpMeshName}.tmp"
        file rename -force $wb_dsMeshFile $tmpMeshName
    }
    aie_wb_update_project 0 $do_update 
    if {$context == "DM" && [info exists wb_dsMeshFile] && 
        $wb_dsMeshFile != "" && $tmpMeshName != "" } { 
        if {[file exists $wb_dsMeshFile]} {
            # A new file was created, delete old one
            file delete -force $tmpMeshName
        } else {
            # Move old file back
            file rename -force $tmpMeshName $wb_dsMeshFile 
        }
    }
    return 1
}

proc aie_wb_get_full_projectname {} {
    global file_name
    if {[info exists file_name] && $file_name(settings) != "" } {
        return [file join $file_name(project_dir) $file_name(settings)]
    }
    return 0
}

proc aie_wb_get_projectname {} {
    global file_name
    if {[info exists file_name] && $file_name(settings) != "" } {
        return $file_name(settings)
    }
    return 0
}

proc aie_wb_update_blocking {} {
    if {[ic_hex_blocking_loaded] == 1} {
        ic_hex_update_node_locations
        aie_hex_update_display
    }
    return 1
}
proc aie_wb_cleanup {} {
    global wb_tetin_file mess_frame

    if { ([info exists wb_tetin_file] && [file exists $wb_tetin_file]) &&
         ([file tail $wb_tetin_file] == "Unnamed.tin" ||
          [file tail $wb_tetin_file] == "icwbgeom.tin") } {
        file remove $wb_tetin_file
    }
    aie_closeProject 0
    $mess_frame.text delete 0.0 end
    return 1
}

proc aie_wb_copy_mousebindings {} {
   global tdv_binding tdv_mouse_bindings tdv_current_viewer
   global use_workbench wb_comPort wb_tcomPort

   if {![info exists use_workbench] || ![info exists wb_comPort] \
               || ![info exists wb_tcomPort] } {
      return ""
   }

   array set wbOpts {
      0 rot 1 trans 2 scale 3 zoomin 4 ""
   }

   if ![info exist tdv_binding(windows)] {
      set tdv_binding(windows) ""
   }

   if {[lsearch $tdv_binding(windows) $tdv_current_viewer] < 0} {
      lappend tdv_binding(windows) $tdv_current_viewer
   }

   foreach w $tdv_binding(windows) {
      foreach {ent b q} {<ButtonPress-2> 2 MiddleBtn \
                         <ButtonPress-3> 3 RightBtn \
                         <Shift-ButtonPress-1> 1 ShiftLeftBtn \
                         <Shift-ButtonPress-2> 2 ShiftMiddleBtn \
                         <Shift-ButtonPress-3> 3 ShiftRightBtn \
                         <Control-ButtonPress-2> 2 ControlMiddleBtn \
                         <Control-ButtonPress-3> 3 ControlRightBtn} {
         set k [AIEWBGetFromWBScript GetPreferenceSetting("Mouse${q}Action")]
         if ![info exist wbOpts($k)] {
            # an error
            continue
         }

         set d $wbOpts($k) 
         set tdv_binding($ent) [lindex {Rotate Pan Zoom "Box Zoom" None} $k]

         if [info exist tdv_binding($w,$ent)] {
            if {$tdv_binding($w,$ent) != $d} {
                tdv_set_mouse_press_binding $w $ent $b $d
            }
         } else {
            tdv_set_mouse_press_binding $w $ent $b $d
         }

         set tdv_mouse_bindings($ent) $d
      }
   }

   aie_set_options
}
proc aie_wb_cd {} {
    global wb_curdir

    if { [info exists wb_curdir] && $wb_curdir != "" } {
        cd $wb_curdir
        return 1;
    } else {
        return 0;
    }
}
proc aie_wb_get_pwd {} {
    set p [pwd]
    if { [info exists p] && $p != "" } {
        return $p
    }
    return 0;
}

array set wb_named_selections {
}

proc aie_create_named_selections {} {
    after 500 aie_create_named_selections_start
    return 1
}

proc aie_create_named_selections_start {} {
    global wb_named_selections named_sels_as_parts

    if { (![ic_geo_is_loaded] || ![ic_uns_is_loaded])} {
        after 500 aie_create_named_selections_start
        return 1
    }

    if { ![info exists wb_named_selections] } { return 0; }

    set ns [array names wb_named_selections]  

    if { $ns == "" } {
        return 0
    }

    foreach n $ns {
        set subset $wb_named_selections($n)
        set point_list ""
        set curve_list ""
        set surface_list ""
        set material_list ""

        if { [info exists named_selections_as_parts] && $named_selections_as_parts == 1} {
            foreach {type name} $subset {
                switch -- $type {
                    point {
                        lappend point_list $name
                    }
                    curve {
                        lappend curve_list $name
                    }
                    surface {
                        lappend surface_list $name
                    }
                    body {
                        lappend material_list $name
                    }
                }
            }
            set tlist {point curve surface material}
            foreach t $tlist {
                set tn "${t}_list"
                if {$tn != ""} {
                    ic_geo_set_family $t $n names $tn
                }
            }
        } else {
            #put in subset
#            ic_geo_subset_add_items $n [list $subset]
#            aie_init_geom_subsets 
        }
    }
    foreach n $ns {
        if {$wb_named_selections($n) == "" } continue
        if { ![info exists named_sels_as_parts] || $named_sels_as_parts == 0} {
		    set sub [ic_uns_subset_create $n]
            foreach {type name} $wb_named_selections($n) {
                if [ catch { 
                    set sub1 [ic_uns_get_attached_elements $type $name]
    		        ic_uns_subset_add_from $sub $sub1
         		    ic_uns_subset_delete $sub1
                } err ] {
                    mess "Error: $err\n" red
                }
            }
            ::AIEnv::GUIManagement::Tree::AddGroup mesh_subset $n 0
            ::AIEnv::GUIManagement::Tree::ToggleGroupVisibility mesh_subset $n same
        } else {
            foreach {type name} $wb_named_selections($n) {
                if [catch { 
                    set elms [ic_uns_get_attached_elements $type $name]
                    ic_uns_change_family $elms $n
                } err ] {
                    mess "Error: $err\n" red
                }
            }
        }
    }
    return 1
}

proc aie_wb_mess { str {color ""} } {
    if {[info exists color] && $color != ""} {
        mess "$str\n" $color
    } else {
        mess "$str\n"
    }
}

#######################################################
#
# aie_wb2_* commands for the ICEM CFD Workbench Addin
#
#######################################################
#
# Author: jari.spaete@ansys.com
#

proc aie_wb2_init_files {} {
    global env file_name wb_initProjName wb_curdir batch_mode is_win wb_init_files_done
    global wb_parameter_input wb_parameter_output wb_parameter_user_defined wb_parameter_options
    global vid_options options toolBarInfo license_not_valid import_model_options map_tetin_sizes

    if {!$batch_mode && [info exists license_not_valid]} {
        set wb_init_files_done 1
        InitLicenseReset
    }
    if ![info exists wb_initProjName] {
        set wb_init_files_done 1
        return
    }
    if ![file exists $wb_initProjName.prj] {
         if {[info exists wb_curdir] && $wb_curdir != "" && [file exists $wb_curdir]} {
            set file_name(project_dir) $wb_curdir
            set file_name(settings) $wb_initProjName.prj
        }
        set wb_init_files_done 1
        return
    }
    
    if [array exists save_import_model_options] { array unset save_import_model_options }
    if [array exists save_map_tetin_sizes] { array unset save_map_tetin_sizes }
    if [array exists import_model_options] {
        array set save_import_model_options [array get import_model_options]
    }
    if [array exists map_tetin_sizes] {
        array set save_map_tetin_sizes [array get map_tetin_sizes]
    }
    
    if [file exists $wb_initProjName.prj] {
        source $wb_initProjName.prj
    }
    if {[info exists wb_curdir] && $wb_curdir != "" && [file exists $wb_curdir]} {
        set file_name(project_dir) $wb_curdir
    } else {
        set file_name(project_dir) [pwd]
        set wb_curdir $file_name(project_dir)
    }
    regsub -all \\\\ $file_name(project_dir) / file_name(project_dir)
    if $batch_mode {
        set skip 0
        set command [aie_get_global wb_command]
        if {$command != "___NA___" && $command != ""} {
            set command [lindex $command 0]
            if {[lindex $command 0] == "duplicate"} {
                set skip 1
            }
        }
        if !$skip { ic_load_project_file $wb_initProjName.prj }
    } else {
        busy 1
        aie_openProject $wb_initProjName.prj
        busy reset
    }
    if [array exists save_import_model_options] {
        array set import_model_options [array get save_import_model_options]
    }
    if [array exists save_map_tetin_sizes] {
        array set map_tetin_sizes [array get save_map_tetin_sizes]
    }
    if !$batch_mode { busy 1 }
    ic_set_project_names $wb_curdir/$wb_initProjName.prj
    aie_wb2_update_upstream_data_filename
    aie_wb2_set_default_properties
    if !$batch_mode {
        set command [aie_get_global wb_command]
        if {$command != "___NA___" && $command != ""} {
            aie_wb2_execute_batch_command $command
        }
        aie_view fitWindow
        busy reset
        if ![ic_wb2_is_mesh_data_updated] {
            mess "Warning: mesh is out-of-date; please run \"Update Project\"\n" red
        }
        if {[info exists options(default_solver)] && $options(default_solver) != ""} {
            set sol $options(default_solver)
            if {$sol == "ANSYS Fluent" || $sol == "Polyflow" || $sol == "ANSYS" || $sol == "ANSYS CFX" || $sol == "FENSAP"} {
                switch -- $sol {
                    "ANSYS Fluent" {
                        set but $toolBarInfo(dropButton,"Output mesh to ANSYS FLUENT")
                        ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 0 1
                    }
                    "ANSYS CFX" {
                        set but $toolBarInfo(dropButton,"Output mesh to ANSYS CFX")
                        ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 1 1
                    }
                    "Polyflow" {
                        set but $toolBarInfo(dropButton,"Output mesh to Polyflow")
                        ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 2 1
                    }
                    "ANSYS" {
                        set but $toolBarInfo(dropButton,"Output mesh to ANSYS")
                        ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 3 1
                    }
                    "FENSAP" {
                        set but $toolBarInfo(dropButton,"Output mesh to FENSAP")
                        ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 4 1
                    }
                }
            }
        }
        set wb_init_files_done 1
    }
    mess "Current project directory: $file_name(project_dir)\n"
}

proc aie_wb2_exit_icemcfd {} {
    global batch_mode wb_update_data_status 
    
    if $batch_mode return

    if ![ic_wb2_init_files_done] {
        mess "Please wait until the network connection to workbench is ready before closing ICEM CFD\n" red
        return
    }
    
    set exit 1
    set wb 1
    set wb_update_data_status 1
    set error [ic_socket_send_to_wb2 wb_update_status]
    if !$error {
        tkwait variable wb_update_data_status
        if {$wb_update_data_status == 0} {
            set ret [aie_saveProject 0 0 $exit $wb]
            if ![string match "*unsaved_project_files*" [aie_get_global file_name project_dir]]  {
                ic_socket_send_to_wb2 "wb_save $ret"
            }
            set exit 2
        }
    } else {
        mess "Warning: saving project; socket connection lost\n" red
        after 3000
    }
    
    ic_wb2_exit_icemcfd $exit $wb
}

proc aie_wb2_refresh_upstream_data {} {
    global file_name batch_mode wb_upstream_data_status

    if $batch_mode return
    if {[aie_get_global import_model_options from_source] == "1"} {
        ic_wb2_refresh
        set wb_upstream_data_status 0
    } else {
        ic_socket_send_to_wb2 wb_refresh_get
        ic_socket_send_to_wb2 wb_refresh_status
        tkwait variable wb_upstream_data_status
    }
    aie_clear_dez
}

proc aie_wb2_save_project {} {
    global file_name wb_update_data_status

    if ![ic_wb2_init_files_done] {
        mess "Please wait until the network connection to workbench is ready before saving the ICEM CFD project\n" red
        return
    }

    set wb_update_data_status 1
    ic_socket_send_to_wb2 wb_update_status
    tkwait variable wb_update_data_status
    if {$wb_update_data_status == 1} {
        if [ic_wb2_exists_output_parameter] {
            busy 1
            mess "Updating workbench output parameters...\n"
            ic_wb2_update_parameters output
            busy reset
        }
    }
    set ret [ic_save_project $file_name(project_dir)/$file_name(settings)]
    ic_socket_send_to_wb2 "wb_save $ret"
}

proc aie_wb2_update_upstream_data_filename {{file ""}} {
    global file_name
    
    set ret 0
    if {$file != ""} {
        if [file exists $file] {
            set file_name(upstream_data) $file
            set ret 1
        } else {
            set ret 0
        }
    }
    if {[info exists file_name(upstream_data)] && $file_name(upstream_data) != ""} {
        if [file exists $file_name(upstream_data)] {
            set ret 1
        }
        if !$ret {
            set data [file tail $file_name(upstream_data)]
            set name1 [file rootname $data]
            set name2 [file tail [file dir $file_name(upstream_data)]]
            set mdir [file dir [file dir $file_name(project_dir)]]
            set path $mdir/$name1/$name2
            set file $path/$data
            if [file exists $file] {
                set file_name(upstream_data) $file
            }
        }
    } else {
        set ret 0
    }
    return $ret
}

proc aie_wb2_update_file_names {} {
    global file_name 

    foreach p [array names file_name] {    
        set n [aie_get_global file_name $p]
        if {$n != "___NA___"} {
            set file_name($p) $n
        }
    }
}

proc aie_wb2_is_upstream_data_updated {} {
    return [ic_wb2_is_upstream_data_updated]
}

proc aie_wb2_backup_files {from_exit} {
    global env file_name wb_backup wb_initProjName

    if {![info exists wb_backup] || ![file exists $wb_backup]} {
        return 0
    }
    set dir [file tail [file dir [file dir $file_name(project_dir)]]]
    if $from_exit {
        if {![info exists wb_initProjName] || ![file exists $wb_initProjName.prj]} return
        if ![file exists $wb_backup/$dir] { file mkdir $wb_backup/$dir }
        if ![file exists $wb_backup/$dir/$wb_initProjName] { file mkdir $wb_backup/$dir/$wb_initProjName }
        if ![file exists $wb_backup/$dir/$wb_initProjName/ICEMCFD] { file mkdir $wb_backup/$dir/$wb_initProjName/ICEMCFD }
        set files [glob -nocomplain $file_name(project_dir)/$wb_initProjName.*]
    } else {
        return 0
    }
    set ret 0
    if {[glob -nocomplain $wb_backup/$dir/$wb_initProjName/ICEMCFD/*] == ""} {
        foreach file $files {
            if ![file exists $wb_backup/$dir/$wb_initProjName/ICEMCFD/[file tail $file]] {
                file copy -force $file $wb_backup/$dir/$wb_initProjName/ICEMCFD
                set ret 1
            }
        } 
    } else {
        foreach file $files {
            if ![file exists $wb_backup/$dir/$wb_initProjName/ICEMCFD/[file tail $file]] {
                set ret 1
            }
        }     
    }
    return $ret
}

proc aie_wb2_replece_geometry {} {
    global file_name 
      
    if {![ic_geo_is_loaded] && ![ic_uns_is_loaded]} { return 0 }
    set ext [file extension $file_name(upstream_data)]
    if {$ext != ".cmdb"} {
        set mess "Geometry already exists.  Do you want to replace the geometry?"
        aie_set_global vid_options 1 wb_import_geom
        aie_set_global vid_options 0 wb_import_mesh
    } else {
        set mess "Geometry/Mesh already exists.  Do you want to replace the geometry/mesh?"
        aie_set_global vid_options 1 wb_import_geom
        aie_set_global vid_options 1 wb_import_mesh
    }
    if {[tk_dialog .replace "Replace" "$mess" "" -1 Yes No] == 0} {
        if {$ext != ".cmdb"} {
            mess "Updating geometry from \"$file_name(upstream_data)\" ...\n"
        } else {
            mess "Updating geometry/mesh from \"$file_name(upstream_data)\" ...\n"
        }
        if [ic_geo_is_loaded] { ic_unload_tetin }
        if [ic_uns_is_loaded] { ic_unload_mesh }
        ic_wb_brep_read $file_name(upstream_data)
        ic_gui_update
        return 1
    } else {
        return 0
    }
}

proc aie_wb2_update {{file ""}} {
    global file_name wb_initProjName options wb_upstream_data_status wb_solver_names
    
    mess "Updating ICEM CFD...\n"
    set wb_upstream_data_status 0
    if {[aie_get_global import_model_options from_source] == "1"} {
        ic_wb2_refresh
    } else {
        set wb_upstream_data_status 0
    }
    
    ic_socket_send_to_wb2 wb_parameter_get
    ic_socket_send_to_wb2 wb_refresh_status
    tkwait variable wb_upstream_data_status
    if {$wb_upstream_data_status == 1} {
        if [info exists file_name(upstream_data)] {
            if [file exists $file_name(upstream_data)] {
                set file $file_name(upstream_data)
            } else {
                set ext [file extension $file_name(upstream_data)]
                if {$ext == ".cmdb"} {
                    set root [file rootname $file_name(upstream_data)]
                    if {[string index $root end] == "1"} {
                        if [file exists [string range $root 0 end-1]$ext] {
                            set file [string range $root 0 end-1]$ext
                        }
                    } else {
                        if [file exists ${root}1${ext}] {
                            set file ${root}1${ext}
                        }
                    }
                }
            }
        }
    }
    
    if {$file != "" && $wb_upstream_data_status == 1} {
        if {[ic_wb2 $file] == 0} {
            ic_wb2_send_wb_status 0
            return 0
        }
    }
    
    if {$wb_upstream_data_status == 0} {
        set status 1
    } else {
        set status 0
    }
    set replay $wb_initProjName.rpl
    if ![file exists $replay] {
        if [ic_geo_is_loaded] {
            if [ic_hex_blocking_loaded] {
                mess "Missing replay file $replay; using \"Hexa\" as mesher to generate mesh\n" blue
                set mesher hexa
            } else {
                set mesher tetra
                mess "Missing replay file $replay; using \"Tetra\" as mesher to generate mesh\n" blue
            }
            if ![ic_wb2_run_mesher $mesher] {
                ic_wb2_send_wb_status 0
                return 0
            }
            if {$mesher == "tetra" && [ic_wb2_exists_prism_input_parameter]} {
                mess "Using \"Prism\" as mesher to generate mesh from $mesher mesh\n" blue
                if ![ic_wb2_run_mesher prism] {
                    ic_wb2_send_wb_status 0
                    return 0
                }
            }
        } else {
            mess "Missing replay file $replay; no geometry loaded\n" blue
        }
    } else {
        if {[file size $replay] == 0} {
            mess "Warning: replay file $replay is empty\n" red
        } else {
            aie_set_global wb_input_parameter_mode 1
            mess "Running replay file $replay\n" blue
            if [ic_replay $replay] {
                mess "Done running replay file $replay\n" blue
            } else {
               aie_unset_global wb_input_parameter_mode
               ic_wb2_send_wb_status 0
               return 0  
            }
            aie_unset_global wb_input_parameter_mode
            if {[ic_hex_blocking_loaded] && [ic_wb2_exists_blocking_input_parameter]} {
                if ![ic_wb2_run_hexa] {
                    ic_wb2_send_wb_status 0
                    return 0
                }
            }
        }
    }
    if [ic_geo_is_loaded] {
        incr status 2
    }
    if [ic_uns_is_loaded] {
        incr status 4
    }
    
    set wb_solver_names "___NA___"
    ic_socket_send_to_wb2 wb_solver_status
    tkwait variable wb_solver_names
    foreach sol $wb_solver_names {
        if {$sol == "ANSYS Fluent" || $sol == "Fluent_V6"} {
            ic_wb2_run_solution FLUENT
        } elseif {$sol == "Polyflow"} {
            ic_wb2_run_solution POLYFLOW
        } elseif {$sol == "ANSYS"} {
            ic_wb2_run_solution ANSYS
        } elseif {$sol == "ANSYS CFX"} {
            ic_wb2_run_solution CFX-5
        } elseif {$sol == "FENSAP"} {
            ic_wb2_run_solution FENSAP
        }
    }

    ic_wb2_update_parameters input
    if [ic_wb2_exists_output_parameter] {
        busy 1
        mess "Updating workbench output parameters...\n"
        ic_wb2_update_parameters output
        busy reset
    }
    
    ic_gui_update
    ic_wb2_cleanup
    aie_wb2_save_project
}

proc aie_wb2_set_default_properties {} {
    ic_wb2_set_default_properties
}

proc aie_wb2_update_properties {properties} {
    mess "Updating properties...\n"
    return [eval ic_wb2_update_properties $properties]
}

proc aie_wb2_update_global_properties {properties} {
    mess "Updating input parameters...\n"
    return [eval ic_wb2_update_global_properties $properties]
}

proc aie_wb2_record_replay {what} {
    global env file_name wb_initProjName replay_recording replay_file replay_dir replay_ignore_errors
    global command_hook after_command_hook replay_pause toolBarInfo replay_current replay_count replay_commands
    global AppName Version beta_mode
    
    if {[aie_get_global replay_icem_mode] != "___NA___"} {
        mess "Close the \"Replay Control\" gui before\n" red
        return
    }
    
    set replay_dir $file_name(project_dir)
    set replay_file $wb_initProjName.rpl
    
    switch -- $what {
        0 {
            if {[aie_get_global replay_wb_mode] != "___NA___" && [winfo exists .replay_ops]} {
                mess "\"Replay Control\" already opened to recording replay file.  Use \"Replay Control\" to stop recording replay\n" red
                wm deiconify .replay_ops
                return
            }
            if {![info exists command_hook] || ![info exists after_command_hook]} {
                mess "Recording not started: press \"Start Replay Recording\" to start recording\n" red
                set but $toolBarInfo(dropButton,"Start Replay Recording")
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 0 1
                return
            }
            if [info exists replay_pause] {
                unset replay_pause
            }
            replay_stop_recording
            if {$replay_count == 0} {
                mess "No commands recorded; skip saving of replay file\n" red
                set but $toolBarInfo(dropButton,"Start Replay Recording")
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 0 1
                return
            }
            if [file exists $replay_file] {
                set mess "Replace existing replay file?"
                if {[tk_dialog .replace "" "$mess" "" -1 Yes No] == 1} {
                    mess "Warning: replay file not saved\n" red
                    return
                }
            }
            set replay_recording 0
            replay_save $replay_file 1
            set but $toolBarInfo(dropButton,"Run Replay File")
            ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 3 1
        }
        1 {
            if {[aie_get_global replay_wb_mode] != "___NA___" && [winfo exists .replay_ops]} {
                mess "\"Replay Control\" already opened to recording replay file.  Use \"Replay Control\" to recording replay\n" red
                wm deiconify .replay_ops
                return
            }
            set but $toolBarInfo(dropButton,"Start Replay Recording")
            if {([info exists command_hook] || [info exists after_command_hook]) && ![info exists replay_pause]} {
                mess "Already started to recording replay file\n" red
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 2 1
                return
            } else {
                if ![info exists replay_pause] {
                    if [file exists $replay_file] {
                        catch { unset skip_it }
                        set mess "A replay file exists. Create new replay file or append to existing replay file?"
                        set n [tk_dialog .replay "Replay" "$mess" "" -1 New Append Cancel]
                        switch -- $n {
                            0 {
                                if {[info exists replay_count] && $replay_count} {
                                    if [info exists replay_commands] { unset replay_commands }
                                    set replay_count 0
                                    set replay_current 0
                                    replay_list_reset
                                }
                            }
                            1 {
                                replay_load $replay_file
                                set replay_current $replay_count
                                set skip_it 1
                            }
                            2 {
                                return
                            }
                        }
                    }
                    replay_start_recording
                    if ![info exists skip_it] {
                        replay_record_command "# Replay file $AppName $Version in Workbench 2.0 Framework"
                    }
                    if {![ic_geo_is_loaded] && ![info exists skip_it]} {
                        replay_record_command "# unloading geometry"
                        replay_record_command "ic_unload_tetin"
                        replay_record_command "ic_empty_tetin"
                    }
                    if {![ic_uns_is_loaded] && ![info exists skip_it]} {
                        replay_record_command "# unloading mesh"
                        replay_record_command "ic_unload_mesh"
                    }
                    if {![ic_hex_blocking_loaded] && ![info exists skip_it]} {
                        replay_record_command "# unloading blocking"
                        replay_record_command "ic_hex_unload_blocking"
                    }
                    if ![info exists skip_it] {
                        replay_record_command "# delete empty parts"
                        replay_record_command "ic_delete_empty_parts"
                    }
                } else {
                    unset replay_pause
                    set replay_recording 1
                    mess "Resume to recording replay file\n" blue
                }
            }
            set replay_recording 1
            mess "Press \"Pause Replay Recording\" to pause recording or \"Stop Replay Recording\" to end recording\n" blue
            ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 2 1
        }
        2 {
            if {[aie_get_global replay_wb_mode] != "___NA___" && [winfo exists .replay_ops]} {
                mess "\"Replay Control\" already opened to recording replay file.  Use \"Replay Control\" to run replay file\n" red
                wm deiconify .replay_ops
                return
            }
            if {[info exists command_hook] || [info exists after_command_hook] || [info exists replay_pause]} {
                mess "Recording already started: press \"Stop Replay Recording\" to end recording\n" red
                set but $toolBarInfo(dropButton,"Stop Replay Recording")
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 2 1
                return
            }
            if ![file exists $replay_file] {
                mess "Missing replay file $replay_file\n" red
                return
            }
            mess "Start running replay file\n" blue
            aie_set_global wb_input_parameter_mode 1
            if [ic_replay $replay_file] {
                mess "Done running replay file\n" blue
            }
            aie_unset_global wb_input_parameter_mode
        }
        3 {
            if {[aie_get_global replay_wb_mode] != "___NA___" && [winfo exists .replay_ops]} {
                mess "\"Replay Control\" already opened to recording replay file.  Use \"Replay Control\" to pause recording replay\n" red
                wm deiconify .replay_ops
                return
            }
            if {[info exists command_hook] && [info exists after_command_hook]} {
                set replay_recording 0
                set replay_pause 1
                mess "Pause to recording replay; press \"Start Replay Recording\" to resume recording\n" blue
                set but $toolBarInfo(dropButton,"Start Replay Recording")
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 0 1
            } else {
                mess "Recording not started: press \"Start Replay Recording\" to start recording\n" red
                set but $toolBarInfo(dropButton,"Start Replay Recording")
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 0 1
            }
        }
        4 {
            if {[aie_get_global replay_wb_mode] != "___NA___" && [winfo exists .replay_ops]} {
                mess "\"Replay Control\" already opened to recording replay file.  Close \"Replay Control\" before deleting replay file\n" red
                wm deiconify .replay_ops
                return
            }
            if {([info exists command_hook] || [info exists after_command_hook]) && ![info exists replay_pause]} {
                mess "Still recording replay file; press \"Stop Replay Recording\" to end recording\n" red
                set but $toolBarInfo(dropButton,"Stop Replay Recording")
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 2 1
                return
            }
            if ![file exists $replay_file] {
                mess "Replay file $replay_file doesn't exist\n"
            } else {
                set mess "Delete replay file ${replay_file}?"
                if {[tk_dialog .replay "Replay" "$mess" "" -1 Yes No] == 0} {
                    cmd_rm $replay_file
                    if [info exists replay_commands] {
                        unset replay_commands
                    }
                    set replay_count 0
                    set replay_current 0
                    replay_list_reset
                }
            }
            set but $toolBarInfo(dropButton,"Start Replay Recording")
            ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 0 1
        }
        5 {
            if {[aie_get_global replay_wb_mode] != "___NA___" && [winfo exists .replay_ops]} {
                wm deiconify .replay_ops
                return
            }
            if {([info exists command_hook] || [info exists after_command_hook])} {
                mess "Already started to recording replay file; press \"Stop Replay Recording\" to end recording\n" red
                set but $toolBarInfo(dropButton,"Stop Replay Recording")
                ::AIEnv::GUIManagement::Widgets::DropdownButton::OnSelectButton $but 2 1
                return
            }
            #if [winfo exists .replay_ops] { destroy .replay_ops }
            replay_form "" 1 1
            if [file exists $replay_file] {
                replay_load $replay_file
            } else {
                if {[info exists replay_count] && $replay_count == 0} {
                    replay_record_command "# Replay file $AppName $Version in Workbench 2.0 Framework"
                    if ![ic_geo_is_loaded] {
                        replay_record_command "# unloading geometry"
                        replay_record_command "ic_unload_tetin"
                        replay_record_command "ic_empty_tetin"
                    }
                    if ![ic_uns_is_loaded] {
                        replay_record_command "# unloading mesh"
                        replay_record_command "ic_unload_mesh"
                    }
                    if ![ic_hex_blocking_loaded] {
                        replay_record_command "# unloading blocking"
                        replay_record_command "ic_hex_unload_blocking"
                    }
                    replay_record_command "# delete empty parts"
                    replay_record_command "ic_delete_empty_parts"
                }
            }
            if {[info exists replay_count] && $replay_count} {
                set replay_current $replay_count
                replay_list_select
            }
        }
    }
}

proc aie_wb2_execute_batch_command {commands} {
    global batch_mode env

    set ret 0
    if [info exists env(WB2_ICEM_PERFORMANCE)] { set time [clock clicks -milliseconds] }
    for {set i 0} {$i < [llength $commands]} {incr i} {
        set cmd [lindex $commands $i]
        set what [lindex $cmd 0]
        if !$batch_mode { ic_socket_message "Executing command $what [lindex $cmd 1]\n" }
        switch -- $what {
            global_properties {
                set args [lindex $cmd 1]
                set ret [aie_wb2_update_global_properties $args]
            }
            properties {
                set args [lindex $cmd 1]
                set ret [aie_wb2_update_properties $args]
            }
            refresh {
                set args [lindex $cmd 1]
                set ret [ic_wb2_refresh $args]
            }
            update {
                set args [lrange $cmd 1 end]
                set ret [eval ic_wb2_update $args]
            }
            duplicate {
                set args [lindex $cmd 1]
                set ret [ic_wb2_duplicate $args]
            }
            import {
                set args [lindex $cmd 1]
                set ret [ic_wb2_import $args]
            }
            execute {
                set error 0
                set args [lindex $cmd 1]
                foreach n [split $args \;] {
                    set n [string trim $n]
                    mess "Executing command \"$n\"..."
                    if [catch {eval ic_wb2_execute $n} ret] {
                        mess "Error executing command \"$n\"; $ret\n" red
                        set error 1
                        break
                    } else {
                        mess "done\n"
                    }
                }
                if $batch_mode {
                    set file "[ic_get_global wb_initProjName].command_results"
                    if !$error {
                        # only the result from the last commmand will be written to the results file
                        set fp [open "$file" w]
                        puts $fp "[list $ret]"
                        close $fp
                        set ret 1
                    } else {
                        if [file exists "$file"] { ic_rm $file }
                        set ret 0
                    }
                }
            }
            default {
                set ret 0
                mess "Error: Unkown command $what\n" red
            }
        }
    }
    if [info exists env(WB2_ICEM_PERFORMANCE)] { mess "Executed command(s) $commands: Finished in [expr ([clock clicks -milliseconds] - $time) / 1000.0] second(s)\n" }
    return $ret
}

proc aie_wb2_run_solver {format1 format2} {
    global file_name wb_initProjName solution 
    
    if [ic_wb2_get_icemcfd_state] {
        mess "Solver is running\n" red
        return
    }
    
    if [info exists solution(solver)] {
        if {$solution(solver) != "$format2"} {
            set solution(solver) ""
        }
    } else {
        set solution(solver) ""
    }
    
    set file_name(domain) $wb_initProjName.uns
	if ![file exists $file_name(domain)] {
	    if ![ic_uns_is_loaded] {
	        mess "Error: domain file $file_name(domain) doesn't exist; create unstruct mesh first\n" red
	    } else {
	        mess "Error: domain file $file_name(domain) doesn't exist; save mesh first\n" red
	    }
	    return
	}
    set file_name(family_boco) $wb_initProjName.fbc
    
    aie_set_global wb2_icemcfd_running 1
    if {$format1 == "fluent6"} {
        if ![file exists $file_name(family_boco)] {
            solution_set_solver $format2 1
            if ![geo_famboco_edit] {
                aie_unset_global wb2_icemcfd_running
                return
            }
        }
	    if [ic_wb2_run_solution FLUENT] {
            mess "\nDone with translation\n"
        }
	    if [file exists ${file_name(family_boco)}_dfupdate] {
	        cmd_rm ${file_name(family_boco)}_dfupdate
	    }
	} elseif {$format1 == "cfx5"} {
	    aie_unset_global wb2_icemcfd_running
	    aie_wb2_run_solver fluent6 {ANSYS Fluent}
	    mess "\nNote: used the FLUENT Mesh File format for CFX.\n" 
    } elseif {$format1 == "polyflow"} {
        if ![file exists $file_name(family_boco)] {
            solution_set_solver $format2 1
            if ![geo_famboco_edit] {
                aie_unset_global wb2_icemcfd_running
                return
            }
        }
	    if [ic_wb2_run_solution POLYFLOW] {
            mess "\nDone with translation\n"
        }
    } elseif {$format1 == "ANSYS"} {
        if ![file exists $file_name(family_boco)] {
            solution_set_solver $format2 1
            if ![geo_famboco_edit] {
                aie_unset_global wb2_icemcfd_running
                return
            }
            famboco_edit_params
        }
        if [ic_wb2_run_solution ANSYS] {
            mess "\nDone with translation\n"
	    }
	} elseif {$format1 == "FENSAP"} {
        if ![file exists $file_name(family_boco)] {
            solution_set_solver $format2 1
            if ![geo_famboco_edit] {
                aie_unset_global wb2_icemcfd_running
                return
            }
        }
        if [ic_wb2_run_solution FENSAP] {
            mess "\nDone with translation\n"
	    }
	}
	aie_unset_global wb2_icemcfd_running
}

proc aie_wb2_parameter_dialog {NodeID ButtonID ObjectID {title ""}} {
    variable ::AIEnv::GUIManagement::GUIDisplayData
    global ic_dialog aie_ShowParametrized

    set GUITree [TreeStack peek]
    set label [$GUITree get $NodeID -key "Label"]
    set variable [$GUITree get $NodeID -key "Variable"]
    set name [$GUITree get $NodeID -key "Name"]
    set type [$GUITree get $NodeID -key "Type"]

    set input "$title: $label"

    if {$ObjectID == "mParamsDEZ" && $title == "Edge Params"} {
        set edge [lrange [mParamsDEZ get edge] 0 1]
        if {$edge != ""} {
            set input "$title ($edge): $label"
        }
    } elseif {$ObjectID == "mszCurveDEZ" && $title == "Curve Mesh Setup"} {
        set curve [mszCurveDEZ get curveList]
        if {[llength $curve] > 1} {
            mess "Error: \"$input\" is only available for all curves (select no curves) or a single curve (select only one curve)\n" red
            return
        }
        if {$curve != ""} {
            set input "$title ($curve): $label"
        }
    } elseif {$ObjectID == "mszSurfDEZ" && $title == "Surface Mesh Setup"} {
        set surface [mszSurfDEZ get surfList]
        if {[llength $surface] > 1} {
            mess "Error: \"$input\" is only available for all surfaces (select no surfaces) or a single surface (select only one surface)\n" red
            return
        }
        if {$surface != ""} {
            set input "$title ($surface): $label"
        }
    } elseif {$ObjectID == "modifyDensityDEZ" && $title == "Modify Density"} {
        set density [modifyDensityDEZ get densityList]
        if {[llength $density] > 1} {
            mess "Error: \"Density: $label\" is only available for all densities (select no density) or for a single density (select only one density)\n" red
            return
        }
        if {$density != ""} {
            set input "Density ($density): $label"
        } else {
            set input "Density: $label"
        }
    } elseif {$ObjectID == "moveBVertexDEZ" && $title == "Set Location"} {
        set vertices [moveBVertexDEZ get vertices]
        if {$vertices != ""} {
            regsub -all "{" $vertices "" vertices
            regsub -all "}" $vertices "" vertices
            if {[llength $vertices] == 0} return
            set vertices [lsort -dictionary $vertices]
            if {[moveBVertexDEZ get SLHow] == "Increment Position"} {
                set input "$title ($vertices): D$label"
            } else {
                set input "$title ($vertices): $label"
            }
        } else {
            if {[moveBVertexDEZ get SLHow] == "Increment Position"} {
                mess "Error: \"Set Location $label\": missing vertices to set for \"Increment Position\"\n" red
            } else {
                mess "Error: \"Set Location $label\": missing vertices to set for \"Set Position\"\n" red
            }
            return
        }
    }
    set ic_dialog(aspect) 800
    if {[ic_wb2_get_parameter input "$input"] == "___NA___"} {
        set mess "Create a new Workbench Input Parameter for\n\"$input\"?"
        if [winfo exists .newinputparam] { top_destroy .newinputparam }
        set n [tk_dialog .newinputparam "$input" "$mess" "" -1 Yes No]
        switch -- $n {
            0 {
                if [aie_wb2_set_input_name $ObjectID "$input" $variable] {
                    $ButtonID configure -text "P" -fg blue
                    $GUITree set $NodeID -key "WBInputParam" 1
                    ::AIEnv::GUIManagement::ToggleGreyByNodeID $NodeID 1
                    mess "Workbench Input Parameter \"$input\" created\n" blue
                } else {
                    $GUITree set $NodeID -key "WBInputParam" 0
                    $ButtonID configure -text "P" -fg white
                    ::AIEnv::GUIManagement::ToggleGreyByNodeID $NodeID 0
                }
            }
        }
    } else {
        if [aie_wb2_unset_input_name $ObjectID "$input"] {
            $ButtonID configure -text "P" -fg white
            $GUITree set $NodeID -key "WBInputParam" 0
            ::AIEnv::GUIManagement::ToggleGreyByNodeID $NodeID 0
            mess "Workbench Input Parameter \"$input\" deleted\n" blue
        }
    }
    if [info exists ic_dialog(aspect)] { unset ic_dialog(aspect) }

    if {$ObjectID == "moveBVertexDEZ" && $title == "Set Location" && $aie_ShowParametrized(vertex)} {
        aie_wb2_show_parametrized vertex
    }
    if {$ObjectID == "mParamsDEZ" && $title == "Edge Params" && $aie_ShowParametrized(edge)} {
        aie_wb2_show_parametrized edge
    }
}

proc aie_wb2_wb_parameter_reset_input {pattern1 pattern2} { 
    set GUITree [TreeStack peek]
    foreach n [aie_get_global_array_names wb_parameter_input_button] {
        if ![string match ${pattern1}* $n] continue
        set buttons [aie_get_global wb_parameter_input_button $n]
        set NodeID [lindex $buttons 0]
        set ButtonID [lindex $buttons 1]
        if ![string match *${pattern2}* $ButtonID] continue
        $GUITree set $NodeID -key "WBInputParam" 0
        $ButtonID configure -text "P" -fg white
        ::AIEnv::GUIManagement::ToggleGreyByNodeID $NodeID 0
    }
}

proc aie_wb2_wb_parameter_input_blocking_edge {{edge ""}} { 
    aie_wb2_wb_parameter_reset_input "Edge Params" mParamsDEZ
    if {$edge == ""} {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Edge Params: *"] {
            set label [lrange $n 2 end]
            set buttons [aie_get_global wb_parameter_input_button [list Edge Params: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    } else {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Edge Params ($edge): *"] {
            set label [lrange $n 4 end]
            set buttons [aie_get_global wb_parameter_input_button [list Edge Params: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    }
}

proc aie_wb2_wb_parameter_input_blocking_move_vertices {{vertices ""}} {
    regsub -all "{" $vertices "" vertices
    regsub -all "}" $vertices "" vertices
    set verts ""
    foreach v $vertices { append verts "$v " }
    set verts [string trimright $verts]
    set vertices $verts
    aie_wb2_wb_parameter_reset_input "Set Location" moveBVertexDEZ
    foreach "n v" [ic_wb2_get_parameters_by_pattern input "Set Location ($vertices): *"] {
       set label [lindex $n end]
       if {[string index $label 0] == "D"} { set label [string range $label 1 end] }
       set buttons [aie_get_global wb_parameter_input_button [list Set Location: $label]]
       aie_wb2_wb_parameter_input_geom_buttons $buttons
       if {$buttons != "" && $label != ""} { aie_update_dez_value moveBVertexDEZ $label $v }
    }
}

proc aie_wb2_wb_parameter_input_geom_curve {{curve ""}} {
    aie_wb2_wb_parameter_reset_input "Curve Mesh Setup" mszCurveDEZ
    if {$curve == ""} {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Curve Mesh Setup: *"] {
            set label [lrange $n 3 end]
            set buttons [aie_get_global wb_parameter_input_button [list Curve Mesh Setup: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    } else {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Curve Mesh Setup ($curve): *"] {
            set label [lrange $n 4 end]
            set buttons [aie_get_global wb_parameter_input_button [list Curve Mesh Setup: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    }
}

proc aie_wb2_wb_parameter_input_geom_surface {{surface ""}} {
    aie_wb2_wb_parameter_reset_input "Surface Mesh Setup" mszSurfDEZ
    if {$surface == ""} {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Surface Mesh Setup: *"] {
            set label [lrange $n 3 end]
            set buttons [aie_get_global wb_parameter_input_button [list Surface Mesh Setup: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    } else {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Surface Mesh Setup ($surface): *"] {
            set label [lrange $n 4 end]
            set buttons [aie_get_global wb_parameter_input_button [list Surface Mesh Setup: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    }
}

proc aie_wb2_wb_parameter_input_geom_density {{density ""}} {
    aie_wb2_wb_parameter_reset_input "Modify Density" modifyDensityDEZ
    if {$density == ""} {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Density: *"] {
            set label [lrange $n 1 end]
            set buttons [aie_get_global wb_parameter_input_button [list Modify Density: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    } else {
        foreach "n v" [ic_wb2_get_parameters_by_pattern input "Density ($density): *"] {
            set label [lrange $n 2 end]
            set buttons [aie_get_global wb_parameter_input_button [list Modify Density: $label]]
            aie_wb2_wb_parameter_input_geom_buttons $buttons
        }
    }
}

proc aie_wb2_wb_parameter_input_geom_buttons {buttons} {
    if {$buttons == "___NA___" || $buttons == ""} return
    set GUITree [TreeStack peek]
    set NodeID [lindex $buttons 0]
    set ButtonID [lindex $buttons 1]
    $ButtonID configure -text "P" -fg blue
    $GUITree set $NodeID -key "WBInputParam" 1
    ::AIEnv::GUIManagement::ToggleGreyByNodeID $NodeID 1
}

proc aie_wb2_set_input_name {dez param variable} {   
    if {[ic_wb2_get_parameter input "$param"] == "___NA___"} {
        set val [$dez get $variable]
        if {$val == ""} {
            mess "Error: missing value for \"$param\"\n" red
            return 0
        }
        if {$dez == "mszGlobalDEZ"} {
            switch -- $variable {
                minSize - gapNum - gnatref {
                    $dez set natSzGGVal 1
                }
                tetra_smooth_niter - tetra_smooth_aspect {
                    ic_set_meshing_params variable 0 tetra_smooth 1
                    $dez set tetra_smooth 1
                }
                tetra_coarsen_niter - tetra_coarsen_aspect {
                    ic_set_meshing_params variable 0 tetra_coarsen 1
                    $dez set tetra_coarsen 1
                }
            }
        }
        ic_wb2_set_parameter input "$param" $val
        return 1
    }
    return 0
}

proc aie_wb2_unset_input_name {dez param} {
    if {[ic_wb2_get_parameter input "$param"] != "___NA___"} {
        ic_wb2_delete_parameter "$param"
        return 1
    }
    return 0
}

proc aie_wb2_parameter_set_part_params {labels} {
    set params ""
    foreach n $labels {
        set p [aie_wb2_parameter_get_part_param $n]
        if {$p != ""} {
            lappend params $p
        }
    }
    return $params
}

proc aie_wb2_parameter_get_part_param {label} {
    switch -- $label {
        "Prism" { return prism }
        "Hexa-core" { return hexcore }
        "Maximum size" { return emax }
        "Height" { return ehgt }
        "Height ratio" { return hrat }
        "Num layers" { return nlay }
        "Tetra size ratio" { return erat }
        "Tetra width" { return ewid }
        "Min size limit" { return emin }
        "Max deviation" { return edev }
        "Prism height limit factor" { return prism_height_limit }
        "Prism growth law" { return law }
        "Internal wall" { return internal_wall }
        "Split wall" { return split_wall }
    }
    return ""
}

proc aie_wb2_parameter_part_dialog {ButtonID part TableID row} {
    global ic_dialog options wb_TableID

    set labels [aie_get_global wb_part_labels]
    set params [aie_wb2_parameter_set_part_params $labels]
    set i 0
    set ii [expr $i + 1]
    set ic_dialog(aspect) 800
    set ic_dialog(topmost) 1
    set note 1
    foreach p $params {
        set v [$TableID get $row,$ii]
        if {$v == ""} {
            set v [ic_geo_get_family_param $part $p]
        }
        set input "Part $part: [lindex $labels $i]"
        if {($v != "" && $v != 0) || ([ic_wb2_get_parameter input "$input"] != "___NA___")} {
            set size [ic_geo_get_ref_size]
            if {([string is double $size] || [string is integer $size]) && $size > 0 && $v != 0} {
                switch -- $p {
                    emax - emin - edev {
                        if $options(show_factor) {
                            set v [expr $v * $size]
                        }
                    }
                }
            }
            $TableID activate $row,$ii
            if {[ic_wb2_get_parameter input "$input"] == "___NA___"} {
                set note 0
                set mess "Create a new Workbench Input Parameter for\n\"$input\"?"
                if [winfo exists .newinputparam] { top_destroy .newinputparam }
                set n [tk_dialog .newinputparam "Create $input" "$mess" "" -1 Yes No Cancel]
                switch -- $n {
                    0 {
                        if [aie_wb2_set_input_part "$input" $v] {
                            aie_wb2_set_input_part_value $part $p $v
                            $ButtonID configure -text "P" -fg blue
                            switch -- $p {
                                "prism" - "hexcore" - "internal_wall" - "split_wall" {
                                    if {$v == 1} {
                                        $TableID tag cell wbcheckon $row,$ii
                                    } else {
                                        $TableID tag cell wbcheckoff $row,$ii
                                    }
                                }
                                default {
                                    $TableID tag cell wbparam $row,$ii
                                }
                            }
                            if [string match "Part *: Prism growth law" $input] {
                                switch -- "$v" {
                                    exponential { set v2 0 }
                                    linear { set v2 1 }
                                    wb-exponential { set v2 3 }
                                    default { set v2 -1 }
                                }
                                mess "Workbench Input Parameter \"$input (value $v2 for the \"Prism growth law\" $v)\" created\n" blue
                                mess "Note: the \"Workbench Parameter Set\" uses the following integer values to define the \"Prism growth law\"\n" blue
                                mess "undefined : -1\nexponential : 0\nlinear : 1\nwb-exponential : 3\n" blue
                            } else {
                                mess "Workbench Input Parameter \"$input\" created\n" blue
                            }
                        }
                    }
                    1 - 2 {
                        switch -- $p {
                            "prism" - "hexcore" - "internal_wall" - "split_wall" {
                                if {$v >= 1} {
                                    $TableID tag cell checkon $row,$ii
                                } else {
                                    $TableID tag cell checkoff $row,$ii
                                }
                            }
                            default {
                                $TableID tag cell enabled $row,$ii
                            }
                        }
                        if {$n == 2} break
                    }
                }
            } else {
                set note 0
                switch -- $p {
                    "prism" - "hexcore" - "internal_wall" - "split_wall" {
                        if {$v == 1} {
                            $TableID tag cell wbraisedon $row,$ii
                        } else {
                            $TableID tag cell wbraisedoff $row,$ii
                        }
                    }
                    default {
                        $TableID tag cell wbraised $row,$ii
                    }
                }
                set mess "Delete Workbench Input Parameter\n\"$input\"?"
                if [winfo exists .delinputparam] { top_destroy .delinputparam }
                set n [tk_dialog .delinputparam "Delete $input" "$mess" "" -1 Yes No Cancel]
                switch -- $n {
                    0 {
                        if [aie_wb2_unset_input_part "$input"] {
                            switch -- $p {
                                "prism" - "hexcore" - "internal_wall" - "split_wall" {
                                    if {$v == 1} {
                                        $TableID tag cell checkon $row,$ii
                                    } else {
                                        $TableID tag cell checkoff $row,$ii
                                    }
                                }
                                default {
                                    $TableID tag cell enabled $row,$ii
                                }
                            }
                            mess "Workbench Input Parameter \"$input\" deleted\n" blue
                        }
                    }
                    1 - 2 {
                        switch -- $p {
                            "prism" - "hexcore" - "internal_wall" - "split_wall" {
                                if {$v == 1} {
                                    $TableID tag cell wbcheckon $row,$ii
                                } else {
                                    $TableID tag cell wbcheckoff $row,$ii
                                }
                            }
                            default {
                                $TableID tag cell wbparam $row,$ii
                            }
                        }
                        if {$n == 2} break
                    }
                }
            }
        }
        incr i
        incr ii
    }
    set wbp [ic_wb2_get_parameters_by_pattern input "Part $part: *"]
    if {$wbp == ""} {
        $ButtonID configure -text "P" -fg white
    } else {
        set p 0
        foreach "p1 p2" $wbp {
            if {[lsearch $labels [lrange $p1 2 end]] >= 0} {
                set p 1; break
            }
        }
        if $p {
            $ButtonID configure -text "P" -fg blue
        } else {
            $ButtonID configure -text "P" -fg white
        }
    }
    if [info exists ic_dialog(aspect)] { unset ic_dialog(aspect) }
    if [info exists ic_dialog(topmost)] { unset ic_dialog(topmost) }
    if $note {
        mess "Please note that a new workbench input parameter for \"Part Mesh Setup\" must have at least a value unequal default\n" red
    }
}

proc aie_wb2_set_input_part {param value} {
    if {[ic_wb2_get_parameter input "$param"] == "___NA___"} {
        if [string match "Part *: Prism growth law" $param] {
            switch -- "$value" {
                exponential { set value 0 }
                linear { set value 1 }
                wb-exponential { set value 3 }
                default { set value -1 }
            }
        }
        ic_wb2_set_parameter input "$param" $value
        return 1
    }
    return 0
}

proc aie_wb2_unset_input_part {param} {
    if {[ic_wb2_get_parameter input "$param"] != "___NA___"} {
        ic_wb2_delete_parameter "$param"
        return 1
    }
    return 0
}

proc aie_wb2_set_input_part_value {part param value} {
    global options
    
    if [string match "Part *: Prism growth law" $param] {
        switch -- "$value" {
            exponential { set value 0 }
            linear { set value 1 }
            wb-exponential { set value 3 }
            default { set value -1 }
        }
    }

	if $options(apply_all) {
		eval ic_geo_set_family_params $part $param $value
	} else {
		eval ic_geo_set_family_params $part no_crv_inf $param $value
	}
}

proc aie_wb2_is_input_parameter {NameID ObjectID LabelID} {
    set validObjects "mszGlobalDEZ mszCurveDEZ mszSurfDEZ mParamsDEZ modifyDensityDEZ moveBVertexDEZ"
    set validGlobalNames "mxzGlobalTypeGeneral mszGlobalTypeShell mxzGlobalTypeTetra mxzGlobalTypePrism"
    set validBlockingNames "edgeParamS SelLocBM"
    set validPrismLabels "{Initial height} {Height ratio} {Number of layers} {Total height} {Min prism quality} \
        {Fillet ratio} {Max prism angle} {Max height over base} {Prism height limit factor}  \
        {Number of surface smoothing steps} {Number of volume smoothing steps}"
    set validDensityLabels "{Size} {Ratio} {Width}"
    
    set nonValidLabels "{Number of nodes} {Aspect Ratio}"
    set nonValidCurveLabels "{Spacing 1} {Ratio 1} {Spacing 2} {Ratio 2} {Max space}"
    
    if {[lsearch $nonValidLabels $LabelID] >= 0} { return 0 }
    
    if {[lsearch $validObjects $ObjectID] < 0} { return 0 }
    if {$ObjectID == "mszGlobalDEZ"} {
        if {[lsearch $validGlobalNames $NameID] < 0} { return 0 }
        if {$NameID == "mxzGlobalTypePrism" && $LabelID != ""} {
            if {[lsearch $validPrismLabels $LabelID] < 0} { return 0 }
        }
    }
    if {$ObjectID == "mParamsDEZ"} {
        if {[lsearch $validBlockingNames $NameID] < 0} { return 0 }
    }
    if {$ObjectID == "moveBVertexDEZ"} {
        if {[lsearch $validBlockingNames $NameID] < 0} { return 0 }
    }
    if {$ObjectID == "mszCurveDEZ"} {
        if {[lsearch $nonValidCurveLabels $LabelID] >= 0} { return 0 }
    }
    if {$ObjectID == "modifyDensityDEZ"} {
        if {[lsearch $validDensityLabels $LabelID] < 0} { return 0 }
    }
    return 1
}

proc aie_wb2_nonvalid_input_title {label} {

    set nonValidLabels "{General}"
    if {[lsearch $nonValidLabels $label] >= 0} { return 1 }
    return 0
}

proc onsetWorkbenchInputDEZLoad {} {

    set wb_input_create 0
    set wb_input_param_name ""
    set wb_input_param_value ""
    set wb_output_create 0
    set wb_output_param_name ""
    set wb_output_param_value ""
    set wb_input_delete 0
    set wb_inputList ""
    foreach "n v" [ic_wb2_get_parameters user_defined] {
        lappend wb_inputList $n
    }
    foreach "n v" [ic_wb2_get_parameters output] {
        if {[ic_get_global wb_parameter_options "$n"] != "___NA___"} {
            lappend wb_inputList $n
        }
    }
    foreach "n v" [ic_wb2_get_parameters input] {
        lappend wb_inputList $n
    }
    set wb_input_del_name ""
}

proc onsetWorkbenchInputDEZAfterLoad {} {

    foreach n "wb_input_create wb_input_delete wb_output_create" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w aie_wb2_trace_wb_input_parameters
        }
        trace variable $n w aie_wb2_trace_wb_input_parameters
    }
    if $wb_input_create {
        set wb_input_delete 0
        set wb_output_create 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey setWBInputName 1
        ::AIEnv::GUIManagement::ToggleGrey setWBInputValue 1
    }
    if $wb_output_create {
        set wb_input_delete 0
        set wb_input_create 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputName 1
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputValue 1
    }
    if $wb_input_delete {
        set wb_input_create 0
        set wb_output_create 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey selWBInputDelete3 1
    }
}

proc onsetWorkbenchInputDEZUnLoad {} {

    foreach n "wb_input_create wb_input_delete wb_output_create" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w aie_wb2_trace_wb_input_parameters
        }
    }
}

proc aie_wb2_trace_wb_input_parameters {name element op} {
    if {$name != ""} {
        set var [lindex [split $name ::] end]
        set on [setWorkbenchInputDEZ get $var]
        switch -- $var {
            wb_input_create {
                if $on {
                    setWorkbenchInputDEZ set wb_input_delete 0
                    ::AIEnv::GUIManagement::ToggleGrey selWBInputDelete3 1  
                    setWorkbenchInputDEZ set wb_output_create 0
                    ::AIEnv::GUIManagement::ToggleGrey setWBOutputName 1
                    ::AIEnv::GUIManagement::ToggleGrey setWBOutputValue 1
                }
            }
            wb_output_create {
                if $on {
                    setWorkbenchInputDEZ set wb_input_delete 0
                    ::AIEnv::GUIManagement::ToggleGrey selWBInputDelete3 1 
                    setWorkbenchInputDEZ set wb_input_create 0
                    ::AIEnv::GUIManagement::ToggleGrey setWBInputName 1
                    ::AIEnv::GUIManagement::ToggleGrey setWBInputValue 1
                }
            }
            wb_input_delete {
                if $on {
                    setWorkbenchInputDEZ set wb_input_create 0
                    setWorkbenchInputDEZ set wb_output_create 0
                    ::AIEnv::GUIManagement::ToggleGrey setWBInputName 1
                    ::AIEnv::GUIManagement::ToggleGrey setWBInputValue 1
                    ::AIEnv::GUIManagement::ToggleGrey setWBOutputName 1
                    ::AIEnv::GUIManagement::ToggleGrey setWBOutputValue 1
                }
            }
        }
    }
}

proc onsetWorkbenchInputDEZOK {} {
    global aie_ShowParametrized

    if $wb_input_create {
        if {$wb_input_param_name == ""} {
            mess "Error: Missing input \"Parameter name\"; unable to create parameter\n" red
            return
        }
        if {$wb_input_param_value == ""} {
            mess "Error: Missing input \"Parameter value\"; unable to create parameter\n" red
            return
        }
        ic_wb2_set_parameter user_defined "$wb_input_param_name" $wb_input_param_value
        mess "User defined input parameter \"$wb_input_param_name\" created\n" blue
    }
    if $wb_output_create {
        if {$wb_output_param_name == ""} {
            mess "Error: Missing output \"Parameter name\"; unable to create parameter\n" red
            return
        }
        if {$wb_output_param_value == ""} {
            mess "Error: Missing output \"IC Function\"; unable to create parameter\n" red
            return
        }
        if [catch {eval $wb_output_param_value} res] {
            mess "Error: IC Function \"$wb_output_param_value returned an error\".\nError messsage is \"$res\"\n" red
            return
        }
        if {![string is double -strict $res] && ![string is integer -strict $res]} {
            mess "Error: IC Function \"[lindex $wb_output_param_value 0]\" must return an integer value or a float value\n" red
            return
        }
        ic_wb2_set_parameter output "$wb_output_param_name" "$res"
        ic_wb2_set_parameter options "$wb_output_param_value" "$wb_output_param_name"
        mess "User defined output parameter \"$wb_output_param_name\" created\n" blue
    }
    if $wb_input_delete {
        if {$wb_input_del_name == ""} {
            mess "Error: Missing \"Parameter name\"; unable to delete parameter\n" red
            return
        }
        ic_wb2_delete_parameter $wb_input_del_name
        if {[ic_get_global wb_parameter_options "$wb_input_del_name"] != "___NA___"} {
            ic_unset_global wb_parameter_options "$wb_input_del_name"
        }
        mess "\"Parameter $wb_input_del_name\" deleted\n"
    }
    set list ""
    foreach "n v" [ic_wb2_get_parameters user_defined] {
        lappend list $n
    }
    foreach "n v" [ic_wb2_get_parameters output] {
        if {[ic_get_global wb_parameter_options "$n"] != "___NA___"} {
            lappend list $n
        }
    }
    foreach "n v" [ic_wb2_get_parameters input] {
        lappend list $n
    }
    
    setWorkbenchInputDEZ set wb_inputList $list
    setWorkbenchInputDEZ set wb_input_param_name ""
    setWorkbenchInputDEZ set wb_input_param_value ""
    setWorkbenchInputDEZ set wb_output_param_name ""
    setWorkbenchInputDEZ set wb_output_param_value ""
    setWorkbenchInputDEZ set wb_input_del_name ""
    
    if $aie_ShowParametrized(vertex) {
        aie_wb2_show_parametrized vertex
    }
    if $aie_ShowParametrized(edge) {
        aie_wb2_show_parametrized edge
    }
}

proc onsetWorkbenchOutputDEZLoad {} {
    global hex_diagnostic_3d hex_diagnostic_2d hex_diagnostic_1d
    
    set wb_output_quality 0
    set wb_output_delete_quality 0
    set wb_output_num_elems 0
    set wb_output_delete_num_elements 0
    set wb_qualityList [ic_diagnostic_info]
    set wb_output_metric Quality
    foreach "n" "wb_output_node wb_output_line wb_output_tri wb_output_quad wb_output_hexa wb_output_tetra wb_output_penta wb_output_pyra" {
        set $n 0
    }
    set wb_output_check_mesh 0
    set wb_output_delete_check_mesh 0
    set wb_output_block_quality 0
    set wb_output_delete_criterion 0
    set wb_output_num_blocks 0
    set wb_output_delete_num_blocks 0
	if [ic_hex_blocking_loaded] {
	    set mesh_dim [format %d [ic_hex_mesh_dimension]]
	} else {
	    set mesh_dim 3
	}
	switch -- $mesh_dim {
	    3 {
            set wb_criterionList [lsort [array names hex_diagnostic_3d]]
	    }
	    2 {
            set wb_criterionList [lsort [array names hex_diagnostic_2d]]
	    }
	    1 {
            set wb_criterionList [lsort [array names hex_diagnostic_1d]]
	    }
	}
	set wb_output_criterion "Determinant 2x2x2"
}

proc onsetWorkbenchOutputDEZAfterLoad {} {
    global diagWBTypes wb_check_mesh_funcs wb_check_mesh_names
    global hex_diagnostic_3d hex_diagnostic_2d hex_diagnostic_1d
    
    set etypes [ic_uns_list_types]
    set types ""
    foreach et $etypes {
	    if ![regexp NODE $et] {
	        lappend types $et
	    }
    }
    
    if ![ic_uns_is_loaded] {
        set types "TRI_3 TETRA_4"
    }
    
    if {(![info exists diagWBTypes]) || ([join $types] != $diagWBTypes)} {
        selWBOutputMetricMS clear
	    selWBOutputMetricMS set -key "rowLabel" $types
	    selWBOutputMetricMS set -key "columnLabel" [list "Yes" "No"]
	    selWBOutputMetricMS set -key "title" "Mesh types to check for metric \"$wb_output_metric\""
	    selWBOutputMetricMS set -key "rowExclusive" 1
        selWBOutputMetricMS build
        set diagWBTypes [join $types]
    }

	foreach row $types {
	    if {([regexp LINE $row]) || ([regexp BAR $row])} {
		    selWBOutputMetricMS select $row No
	    } else {
		    selWBOutputMetricMS select $row Yes
	    }
    }

    foreach n "wb_output_quality wb_output_delete_quality wb_output_num_elems wb_output_metric wb_output_delete_num_elements \
        wb_output_block_quality wb_output_delete_criterion wb_output_criterion wb_output_num_blocks wb_output_delete_num_blocks \
        wb_output_check_mesh wb_output_delete_check_mesh" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w aie_wb2_trace_wb_output_parameters
        }
        trace variable $n w aie_wb2_trace_wb_output_parameters
    }
    
    foreach "name check func" [list "Duplicate element" wb_output_check_duplicate duplicate \
            "Uncovered faces" wb_output_check_uncovered uncovered \
            "Missing internal faces" wb_output_check_missing missing_internal \
            "Periodic problems" wb_output_check_periodic periodic_problem \
            "Volume orientations" wb_output_check_volume vol_orient \
            "Surface orientations" wb_output_check_surface surf_orient \
            "Hanging elements" wb_output_check_hanging hanging \
            "Penetrating elements" wb_output_check_penetrating penetrating \
            "Disconnected bar elements" wb_output_check_disconnect disconnbars \
            "Multiple edges" wb_output_check_multi_edges multiple \
            "Triangle boxes" wb_output_check_tri_boxes triangle_box \
            "2 single edges" wb_output_check_2_single single_2 \
            "Single-multiple edges" wb_output_check_single_multi single_multiple \
            "Stand-alone surface mesh" wb_output_check_stand_alone standalone \
            "Single edges" wb_output_check_single_edges single \
            "Delaunay violation" wb_output_check_delaunay_vio delaunay \
            "Overlapping elements" wb_output_check_overlapp_elems overlap \
            "Non-manifold vertices" wb_output_check_non_manifold nmanvert \
            "Unconnected vertices" wb_output_check_unconn_verts disconnected_vert] {
        set $check 0
        set wb_check_mesh_funcs($check) $func
        set wb_check_mesh_names($check) $name
    }

    if !$wb_output_quality {
        ::AIEnv::GUIManagement::ToggleGrey selWBOutputMetric3 1
        ::AIEnv::GUIManagement::ToggleGrey selWBOutputMetricMS 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey selWBOutputMetric3 0
        ::AIEnv::GUIManagement::ToggleGrey selWBOutputMetricMS 0
        set wb_output_delete_quality 0
    }
    if !$wb_output_num_elems {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputEleNum 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputEleNum 0
        set wb_output_delete_num_elements 0
    }
    if !$wb_output_check_mesh {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckMesh3 1
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckMesh4 1
        #::AIEnv::GUIManagement::ToggleGrey setWBOutputcheckMeshElemRG 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckMesh3 0
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckMesh4 0
        #::AIEnv::GUIManagement::ToggleGrey setWBOutputcheckMeshElemRG 0
        set wb_output_delete_check_mesh 0
    }
    if !$wb_output_block_quality {
        ::AIEnv::GUIManagement::ToggleGrey selWBOutputCriterion3 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey selWBOutputCriterion3 0
        set wb_output_delete_criterion 0
    }
    if !$wb_output_num_blocks {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputBlockNum 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputBlockNum 0
        set wb_output_delete_num_blocks 0
    }
    
    foreach "n v" [ic_wb2_get_parameters output] {
        if [string match "Min quality of *" $n] {
            if !$wb_output_quality { set wb_output_quality 1 }
            if [string match "*Min side (Quad Optimized)*" $n] {
                set first [string first \( $n 40]
                set last [string last \) $n 40]
            } elseif {[string match "*Aspect Ratio (Fluent)*" $n]} {
                set first [string first \( $n 36]
                set last [string last \) $n 36]
            } else {
                set first [string first \( $n]
                set last [string last \) $n]
            }
            set metric [string range $n 15 [expr $first-2]]
            setWorkbenchOutputDEZ set wb_output_metric "$metric"
            set types [string range $n [expr $first + 1] [expr $last - 1]]
	        foreach row $types {
	            if {([regexp LINE $row]) || ([regexp BAR $row])} {
		            selWBOutputMetricMS select $row No
	            } else {
		            selWBOutputMetricMS select $row Yes
	            }
            }
         } elseif {[string match "Number of * elements" $n]} {
            if !$wb_output_num_elems { set wb_output_num_elems 1 }
            foreach "t1 t2" "wb_output_node NODE wb_output_line LINE_ wb_output_tri TRI_ wb_output_quad QUAD_ wb_output_hexa HEXA_ wb_output_tetra TETRA_ \
                wb_output_penta PENTA_ wb_output_pyra PYRA_" {
                if [string match "* ${t2}*" $n] {
                    setWorkbenchOutputDEZ set $t1 1
                }
            }
        } elseif {[string match "Check Mesh: *" $n]} {
            if !$wb_output_check_mesh { set wb_output_check_mesh 1 }
            foreach nn [array names wb_check_mesh_names] {
                if {$wb_check_mesh_names($nn) == "[string range $n 12 end]"} {
                    if ![setWorkbenchOutputDEZ get $nn] {
                        setWorkbenchOutputDEZ set $nn 1
                    }
                }
            }
        } elseif {[string match "Number of * Blocks" $n]} {
            if ![ic_hex_blocking_loaded] continue
            if !$wb_output_num_blocks { set wb_output_num_blocks 1 }
            set nn [string tolower [lindex $n 2]]
            if ![setWorkbenchOutputDEZ get wb_output_$nn] {
                setWorkbenchOutputDEZ set wb_output_$nn 1
            }            
        } elseif {[string match "Min pre-mesh quality of *" $n]} {
            if ![ic_hex_blocking_loaded] continue
            if !$wb_output_block_quality { set wb_output_block_quality 1 }
            set dim [format %d [ic_hex_mesh_dimension]]
            foreach nn [array names hex_diagnostic_${dim}d] {
                if {[lrange $n 4 end] == $nn} {
                    set wb_output_criterion $nn
                    break
                }
            }  
        }
    }
    
    busy reset
}

proc onsetWorkbenchOutputDEZUnLoad {} {

    foreach n "wb_output_quality wb_output_delete_quality wb_output_num_elems wb_output_metric wb_output_delete_num_elements \
        wb_output_block_quality wb_output_delete_criterion wb_output_criterion wb_output_num_blocks wb_output_delete_num_blocks \
        wb_output_check_mesh wb_output_delete_check_mesh" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w aie_wb2_trace_wb_output_parameters
        }
    }
}

proc aie_wb2_trace_wb_output_parameters {name element op} {
    if {$name != ""} {
        set var [lindex [split $name ::] end]
        if {$var != "wb_output_metric" && $var != "wb_output_criterion"} {
            set on [expr ![setWorkbenchOutputDEZ get $var]]
        }
        switch -- $var {
            wb_output_quality {
                ::AIEnv::GUIManagement::ToggleGrey selWBOutputMetric3 $on
                ::AIEnv::GUIManagement::ToggleGrey selWBOutputMetricMS $on
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_delete_quality 0
                }
            }
            wb_output_delete_quality {
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_quality 0
                }
            }
            wb_output_metric {
                selWBOutputMetricMS set -key "title" "Mesh types to check for metric \"[setWorkbenchOutputDEZ get wb_output_metric]\""
            }
            wb_output_num_elems {
                ::AIEnv::GUIManagement::ToggleGrey setWBOutputEleNum $on
                ::AIEnv::GUIManagement::ToggleGrey setWBOutputEleNumDelete [expr !$on]
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_delete_num_elements 0
                }
            }
            wb_output_delete_num_elements {
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_num_elems 0
                }
            }
            wb_output_check_mesh {
                ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckMesh3 $on
                ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckMesh4 $on
                #::AIEnv::GUIManagement::ToggleGrey setWBOutputcheckMeshElemRG $on
                ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckMeshDelete [expr !$on]
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_delete_check_mesh 0
                }
            }
            wb_output_delete_check_mesh {
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_check_mesh 0
                }
            }
            wb_output_block_quality {
                 ::AIEnv::GUIManagement::ToggleGrey selWBOutputCriterion3 $on
                 if !$on {
                    setWorkbenchOutputDEZ set wb_output_delete_criterion 0
                }
            }
            wb_output_delete_criterion {
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_block_quality 0
                }
            }
            wb_output_num_blocks {
                ::AIEnv::GUIManagement::ToggleGrey setWBOutputBlockNum $on
                ::AIEnv::GUIManagement::ToggleGrey setWBOutputBlockNumDelete [expr !$on]
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_delete_num_blocks 0
                }
            }
            wb_output_delete_num_blocks {
                if !$on {
                    setWorkbenchOutputDEZ set wb_output_num_blocks 0
                }
            }
        }
    }
}

proc aie_wb2_check_periodic {} {
    if [setWorkbenchOutputDEZ get wb_output_check_periodic] {
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckPeriodic 1
	    if ![ic_geo_is_loaded] {
		    mess "Error: can't do check periodic: no geometry is loaded\n" red
		    setWorkbenchOutputDEZ set wb_output_check_periodic 0
		    ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckPeriodic 0
		    return
	    }
        if {[lindex [ic_geo_get_periodic_data] 1] == "none"} {
	        mess "Error: there is no periodicity defined in the mesh\n" red
	        setWorkbenchOutputDEZ set wb_output_check_periodic 0
	        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckPeriodic 0
	        return
        }
        set mess "Select only the surface part(s) which contain the periodic faces"
        set parts [select_families 0 1 0 "$mess" fam_visible +300+300 "Periodic problems"]
        if {$parts != ""} {
            mess "Selected parts $parts\n"
            ic_wb2_set_parameter options periodic_parts "$parts"
        } else {
            setWorkbenchOutputDEZ set wb_output_check_periodic 0
            ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckPeriodic 0
        }
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckPeriodic 0
    } else {
        aie_unset_global wb_parameter_options periodic_parts
        ::AIEnv::GUIManagement::ToggleGrey setWBOutputCheckPeriodic 0
    }
}

proc onsetWorkbenchOutputDEZOK {} {
    global diagWBTypes hex_diagnostic_3d hex_diagnostic_2d hex_diagnostic_1d project_type use_output_blocks wb_check_mesh_funcs wb_check_mesh_names

    if $wb_output_quality {
        if ![ic_uns_is_loaded] {
            mess "Warning: no mesh is loaded!\n" red
        }
        set types ""
        foreach row $diagWBTypes {
	        if [selWBOutputMetricMS query $row Yes] {
	            lappend types $row
	        }
        }
        if {$types != ""} {
            if ![ic_uns_is_loaded] {
                mess "Unable to determine the \"Min quality of ${wb_output_metric} ($types)\"; setting to \"-1\"\n" red
                ic_wb2_set_parameter output "Min quality of ${wb_output_metric} ($types)" -1
            } else {
                ic_wb2_set_parameter output "Min quality of ${wb_output_metric} ($types)" [ic_uns_min_metric $wb_output_metric "" $types]
            }
        }
    } else {
        if $wb_output_delete_quality {
            ic_wb2_delete_parameters_by_pattern output "Min quality of *"
        }
    }
    if $wb_output_num_elems {
        set types [lsort [ic_uns_list_possible_types]]
        if [array exists element_type] { array unset element_type }
        if [ic_uns_is_loaded] {
            foreach t [lsort [ic_uns_list_types]] {
                set element_type([lindex [split ${t} _] 0]) 1
            }
        }
        foreach "n1 t1" "wb_output_node NODE wb_output_line LINE_ wb_output_tri TRI_ wb_output_quad QUAD_ wb_output_hexa HEXA_ \
            wb_output_tetra TETRA_ wb_output_penta PENTA_ wb_output_pyra PYRA_" {
            if [set $n1] {
                if ![ic_uns_is_loaded] {
                    mess "Unable to determine the \"Number of [lindex [split ${t1} _] 0] elements\"; no mesh is loaded\n" red
                    foreach t2 $types {
                        if [regexp ${t1}+ $t2] {
                            mess "Workbench output parameter \"Number of ${t2} elements\" created\n" blue
                            ic_wb2_set_parameter output "Number of ${t2} elements" -1
                        }
                    }
                } else {
                    foreach t2 $types {
                        if [regexp ${t1}+ $t2] {
                            set nelems [ic_count_elements $t2]
                            if $nelems {
                                ic_wb2_set_parameter output "Number of ${t2} elements" $nelems
                                mess "Workbench output parameter \"Number of ${t2} elements\" created\n" blue
                                break
                            } else {
                                if ![info exists element_type([lindex [split ${t2} _] 0])] {
                                    set mess "Element type [lindex [split ${t2} _] 0] does not exist. Create the output parameter?"
                                    if [tk_messageBox -type yesno -message $mess] {
                                        ic_wb2_set_parameter output "Number of ${t2} elements" 0
                                        mess "Workbench output parameter \"Number of ${t2} elements\" created\n" blue
                                        break
                                    }
                                }
                            }
                        } 
                    }
               }
            } else {
                ic_wb2_delete_parameters_by_pattern output "Number of $t1* elements"
            }
        }
    } else {
        if $wb_output_delete_num_elements {
            ic_wb2_delete_parameters_by_pattern output "Number of * elements"
        }
    }
    
    if $wb_output_check_mesh {
        foreach check [array names wb_check_mesh_funcs] {
            set name "$wb_check_mesh_names($check)"
            if [setWorkbenchOutputDEZ get $check] {
                if ![ic_uns_is_loaded] {
                    mess "Unable to run \"Check Mesh: $name\"; no mesh is loaded\n" red
                    ic_wb2_set_parameter output "Check Mesh: $name" -1
                } else {
                    set map [ic_uns_create_diagnostic_subset]
                    ic_uns_create_diagnostic_edgelist 1
                    set what "$wb_check_mesh_funcs($check)"
                    if {$what == "periodic_problem" && [ic_wb2_get_parameter options periodic_parts] != "___NA___"} {
                        set parts [ic_wb2_get_parameter options periodic_parts]
                    } else {
                        set parts ""
                    }
                    set ret [ic_uns_diagnostic subset all diag_type $what fix_fam "" disp_subset $map diag_verb $name fams "$parts" busy_off 0]
                    ic_wb2_set_parameter output "Check Mesh: $name" [lindex $ret 0]
                    ic_uns_subset_delete $map
                    ic_uns_create_diagnostic_edgelist 0
                }
            } else {
                ic_wb2_delete_parameters_by_pattern output "Check Mesh: $name"
                if {$name == "Periodic problems"} {
                    aie_unset_global wb_parameter_options periodic_parts
                }
            }
        }
    } else {
        if $wb_output_delete_check_mesh {
            ic_wb2_delete_parameters_by_pattern output "Check Mesh: *"
        }
    }
    
    if $wb_output_block_quality {
        if ![ic_hex_blocking_loaded] {
            mess "Unable to determine the \"Min pre-mesh quality of ${wb_output_criterion}\"; no blocking is loaded\n" red
            return
        }
        if {[hex_mesh_up_to_date 1] == 0} {
            aie_hex_recompute_mesh
        } 
        if {[hex_mesh_up_to_date 0] == 0} return
        set dim [format %d [ic_hex_mesh_dimension]]
        if {${wb_output_criterion} != "Constant Radius" && ${wb_output_criterion} != "Opp.Face Area Ratio" && \
            ${wb_output_criterion} != "Opp.Face Parallelism" &&  ${wb_output_criterion} != "Custom quality"} {
            set diag [lindex [aie_get_global hex_diagnostic_${dim}d ${wb_output_criterion}] 0]
            if {$diag != "___NA___"} {
                set m [ic_hex_ratio_check_minquality $diag "" "" $project_type]
                if {$m != ""} {
                    if {${wb_output_criterion} == "Angle"} { set m [expr $m * 90.0] }
                    ic_wb2_set_parameter output "Min pre-mesh quality of ${wb_output_criterion}" $m
                } else {
                    mess "Unable to determine the \"Min pre-mesh quality of ${wb_output_criterion}\"\n" red
                }
            } else {
               mess "Unable to determine the \"Min pre-mesh quality of ${wb_output_criterion}\"\n" red
            }
        }
    } else {
        if $wb_output_delete_criterion {
            ic_wb2_delete_parameters_by_pattern output "Min pre-mesh quality of *"
        }
    }
    if $wb_output_num_blocks {
        foreach "t1 t2" "All wb_output_all Mapped wb_output_mapped Free wb_output_free Swept wb_output_swept" {
            if [set $t2] {
                if ![ic_hex_blocking_loaded] {
                    mess "Unable to determine the \"Number of $t1 Blocks\"; no blocking is loaded\n" red
                    ic_wb2_set_parameter output "Number of ${t1} Blocks" -1
                } else {
                    if $use_output_blocks {
                        set m [ic_hex_get_block_type_number [lindex [split $t2 _] end] output_blocks]
                    } else {
                        set m [ic_hex_get_block_type_number [lindex [split $t2 _] end]] 
                    }
                    if {$m != ""} {
                        ic_wb2_set_parameter output "Number of ${t1} Blocks" $m
                    }
                }
            } else {
                ic_wb2_delete_parameter output "Number of ${t1} Blocks"
            }
        }
    } else {
        if $wb_output_delete_num_blocks {
            ic_wb2_delete_parameters_by_pattern output "Number of * Blocks"
        }
    }
}

proc aie_wb2_update_output_parameters {what} {

    if [ic_wb2_exists_output_parameter] return
    busy 1
    mess "Updating workbench output parameters...\n"
    foreach "n v" [ic_wb2_get_parameters output] {
        if {$what == "mesh"} {
            if [string match "Number of * elements" $n] {
                aie_set_global wb_parameter_output [ic_count_elements [lindex $n 2]] $n
            } elseif {[string match "Min quality of *" $n]} {
                if [string match "*Min side (Quad Optimized)*" $n] {
                    set first [string first \( $n 40]
                    set last [string last \) $n 40]
                } elseif {[string match "*Aspect Ratio (Fluent)*" $n]} {
                    set first [string first \( $n 36]
                    set last [string last \) $n 36]
                } else {
                    set first [string first \( $n]
                    set last [string last \) $n]
                }
                set m [string range $n 15 [expr $first-2]]
                set t [string range $n [expr $first + 1] [expr $last - 1]]
                aie_set_global wb_parameter_output [ic_uns_min_metric $m "" $t] $n
            } elseif {[string match "Check Mesh: *" $n]} {
                switch -- [string range $n 12 end] {
                    {Surface orientations} { set m surf_orient }
                    {Hanging elements} { set m hanging }
                    {Periodic problems} { set m periodic_problem }
                    {Single-multiple edges} { set m single_multiple }
                    {Unconnected vertices} { set m disconnected_vert }
                    {Uncovered faces} { set m uncovered }
                    {Disconnected bar elements} { set m disconnbars }
                    {Delaunay violation} { set m delaunay }
                    {Missing internal faces} { set m missing_internal }
                    {Single edges} { set m single }
                    {Stand-alone surface mesh} { set m standalone }
                    {Multiple edges} { set m multiple }
                    {2 single edges} { set m single_2 }
                    {Overlapping elements} { set m overlap }
                    {Duplicate element} { set m duplicate }
                    {Penetrating elements} { set m penetrating }
                    {Non-manifold vertices} { set m nmanvert }
                    {Triangle boxes} { set m triangle_box }
                    {Volume orientations} { set m vol_orient }
                    default { continue }
                }
                set map [ic_uns_create_diagnostic_subset]
                ic_uns_create_diagnostic_edgelist 1
                if {$m == "periodic_problem" && [ic_wb2_get_parameter options periodic_parts] != "___NA___"} {
                    set parts [ic_wb2_get_parameter options periodic_parts]
                } else {
                    set parts ""
                }
                set ret [ic_uns_diagnostic subset all diag_type $m fix_fam "" disp_subset $map diag_verb $n fams "$parts" busy_off 0 quiet 1]
                aie_set_global wb_parameter_output [lindex $ret 0] $n
                ic_uns_subset_delete $map
                ic_uns_create_diagnostic_edgelist 0
            }
        } elseif {$what == "blocking"} {     
            if {[string match "Number of * Blocks" $n]} {
                set output_blocks [aie_get_global use_output_blocks]
                if {$output_blocks == 0} {
                    aie_set_global wb_parameter_output [ic_hex_get_block_type_number [string tolower [lindex $n 2]]] $n
                } elseif {$output_blocks == 1} {
                    aie_set_global wb_parameter_output [ic_hex_get_block_type_number [string tolower [lindex $n 2]] output_blocks] $n
                }
            } elseif {[string match "Min pre-mesh quality of *" $n]} {
                set m [lrange $n 4 end]
                set dim [format %d [ic_hex_mesh_dimension]]
                set diag [lindex [aie_get_global hex_diagnostic_${dim}d $m] 0]
                set proj [aie_get_global project_type]
                if {$diag != "___NA___" && $proj != "___NA___"} {
                    set mm [ic_hex_ratio_check_minquality $diag "" "" $proj]
                    if {$m == "Angle"} { set mm [expr $mm * 90.0] }
                    aie_set_global wb_parameter_output $mm $n
                }
            }
        }
    }
    mess "Done\n"
    busy 0
}

proc aie_wb2_show_parametrized {what} {
    global aie_ShowParametrized display_flag

    if ![ic_hex_blocking_loaded] return
    
    if !$aie_ShowParametrized($what) {
        set aie_ShowParametrized($what,entities) ""
        hex_update_display $what
        return
    }
    
    if {$what == "vertex"} {
        if !$display_flag(vert) { return }
    } else {
        if !$display_flag($what) { return }
    }
    
    set inputList ""
    foreach "n v" [ic_wb2_get_parameters input] {
        lappend inputList $n
    }
    set entities ""
    catch { array unset temp }
    
    switch $what {
        vertex {
            foreach param $inputList {
                if {[string match "Set Location (*): *" $param]} {
                    set first [expr [string first \( $param] + 1]
                    set last [expr [string first \) $param] - 1]
                    if ![info exists temp([string range $param $first $last])] {
                        append entities " [string range $param $first $last]"
                        set temp([string range $param $first $last]) 1
                    }
                }
            }
        }
        edge {
            foreach param $inputList {
                if {[string match "Edge Params (*): *" $param]} {
                    set first [expr [string first \( $param] + 1]
                    set last [expr [string first \) $param] - 1]
                    if ![info exists temp([string range $param $first $last])] {
                        append entities " highlight [string range $param $first $last]"
                        set temp([string range $param $first $last]) 1
                    }
                }
            }
        }
        default {
            return
        }
    }
    
    set aie_ShowParametrized($what,entities) $entities
    hex_update_display $what
}

proc aie_wb2_dummy {} {}

proc aie_wb2_is_running {} {
    return [ic_wb2_is_running]
}
