proc aie_set_uns_subset_visible {name} {
    global options display_mesh_selection
    
    if {$name == "" || ![ic_uns_subset_exists $name]} return
    if {![info exists display_mesh_selection] || !$display_mesh_selection} return
    set num [expr [ic_uns_subset_count_elements $name] + [ic_uns_subset_count_nodes $name]]
    if !$num return
    if {[info exists options(uns_warn_user_if_display)] && \
        [string is integer $options(uns_warn_user_if_display)] && \
        $num < $options(uns_warn_user_if_display)} {
        ic_uns_subset_visible $name 1
    }
}

proc ondeleteNodesDEZAfterLoad {} {
    global ExecuteUserProcAfterLoad
    
    set Name "deleteNodesDEZ"
    set project_restored 1
    set ExecuteUserProcAfterLoad 0
    if [info exists ::AIEnv::GUIManagement::DEZ::${Name}_data] {
        set project_restored 0
    }
    if {!$auto_pick_mode || $project_restored} {
        if ![ic_uns_is_loaded] {
	        msg ERROR "No mesh available"
	        deleteNodesDEZ hide
	        return
	    }
    }

    if $auto_pick_mode {
	    if {$project_restored} {
	        deleteNodesPick pick
	    } else {
	        set ExecuteUserProcAfterLoad 1
	    }
    }
    if {[trace vinfo nodeList] != ""} {
        trace vdelete nodeList w aie_trace_delete_nodes
    }
    trace variable nodeList w aie_trace_delete_nodes
}

proc aie_trace_delete_nodes {name element op} {
    set nodes [deleteNodesDEZ get nodeList]
    if {$nodes != "" && [ic_uns_subset_exists $nodes]} {
        aie_set_uns_subset_visible $nodes
    }
}

proc ondeleteNodesPickPick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc ondeleteNodesPickFinish {} {
    if {$nodeList != ""} {
        if $auto_pick_mode {
    	    deleteNodesDEZ apply   	    
	        deleteNodesPick pick
	    } else {
	        aie_set_uns_subset_visible $nodeList
	    }
    }
}

proc ondeleteNodesDEZOK {} {
    if {$nodeList != ""} {
	    ic_uns_delete_nodes $nodeList
	    ic_uns_subset_delete $nodeList
	    aie_updateMeshVis
	    mess "Done \"Delete Nodes\"\n" blue
	    set nodeList ""
    }
}

proc ondeleteNodesDEZUnLoad {} {
    if {[trace vinfo nodeList] != ""} {
        trace vdelete nodeList w aie_trace_delete_nodes
    }
    if {$nodeList != ""} {
	    ic_uns_subset_delete $nodeList
	    set nodeList ""
    }
}

proc ondeleteElemsDEZAfterLoad {} {
    global ExecuteUserProcAfterLoad
    
    set Name "deleteElemsDEZ"
    set project_restored 1
    set ExecuteUserProcAfterLoad 0
    if [info exists ::AIEnv::GUIManagement::DEZ::${Name}_data] {
        set project_restored 0
    }
    if {!$auto_pick_mode || $project_restored} {
	    if ![ic_uns_is_loaded] {
	        msg ERROR "No mesh available"
	        deleteElemsDEZ hide
	        return
	    }
    }
    if $auto_pick_mode {
	    if {$project_restored} {
	        deleteElemsPick pick
	    } else {
	        set ExecuteUserProcAfterLoad 1
	    }
    }
    if {[trace vinfo elemList] != ""} {
        trace vdelete elemList w aie_trace_delete_elems
    }
    trace variable elemList w aie_trace_delete_elems
}

proc ondeleteElemsDEZUnLoad {} {
    if {$elemList != ""} { ic_uns_subset_delete $elemList }
    if {[trace vinfo elemList] != ""} {
        trace vdelete elemList w aie_trace_delete_elems
    }
    set elemList ""
}

proc aie_trace_delete_elems {{name ""} {element ""} {op ""}} {
    global auto_pick_mode
    
    if {$name != ""} { set elemList [deleteElemsDEZ get elemList] }
    if {($elemList != "" && [ic_uns_subset_exists $elemList])} {
        if $auto_pick_mode {
            deleteElemsDEZ apply
        } else {
            aie_set_uns_subset_visible $elemList
        }
    }
}

proc ondeleteElemsPickPick {} {
     if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc ondeleteElemsPickFinish {} {
     if {$elemList != ""} {
        if $auto_pick_mode {
    	    deleteElemsDEZ apply
	        deleteElemsPick pick
	    } else {
	        aie_set_uns_subset_visible $elemList
	    }
    }
}

proc ondeleteElemsDEZOK {} {
    if {$elemList != ""} {
        ic_delete_elements subset $elemList
        ic_uns_subset_delete $elemList
        aie_updateMeshVis
        mess "Done \"Delete Elements\"\n" blue
        set elemList ""
    }
}

#-------------------------------------Auto pick procedure for Move Nodes----------------------------------

proc onmoveNodesDEZLoad {} {
    global take_first_press

    if {$distance == ""} { set distance 1 }
    if ![info exists moveNodesGGVal] { set moveNodesGGVal 0 }
    if ![info exists moveNodesTypeVal] { set moveNodesTypeVal 0 }
    if {$moveNodesGGVal == 0} {
        if {$moveNodesTypeVal == 0} {
            set take_first_press 1
        } else {
            set take_first_press 0
        }
    } else {
        set take_first_press 0
    }
    if ![info exists moveNodesToCurveGGVal] {
        set moveNodesToCurveGGVal 0
    }
    if ![info exists moveNodesPointMethodVal] {
        set moveNodesPointMethodVal 0
    }
    if {![info exists nodeCrvTol] || $nodeCrvTol == ""} {
        set nodeCrvTol 0.0
    }
    if {![info exists nodePointTol] || $nodePointTol == ""} {
        set nodePointTol 0.0
    }
    set lockedFlag 0
}

proc onmoveNodesDEZAfterLoad {} {
    global projectionSurfList
    
    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        moveNodesDEZ hide
        return
    }
    foreach n "projNodesGGVal moveNodesToCurveGGVal moveNodesPointMethodVal" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w aie_move_node_proj_trace
        }
        trace variable $n w aie_move_node_proj_trace
    }
    if {[trace vinfo elemList] != ""} {
        trace vdelete elemList w aie_move_nodes_trace_elems
    }
    trace variable elemList w aie_move_nodes_trace_elems
    if {[trace vinfo nodeList] != ""} {
        trace vdelete nodeList w aie_move_nodes_trace_nodes
    }
    trace variable nodeList w aie_move_nodes_trace_nodes
    set projectionSurfList [list "All Parts" "Active Parts"]
    moveNodesDEZ onmoveNodesInterLoad
    aie_move_node_proj_trace "" "" ""
}

proc aie_move_node_proj_trace {name element op} {

    if ![ic_geo_is_loaded] {
        ::AIEnv::GUIManagement::ToggleGrey projNodesPoint 1
        ::AIEnv::GUIManagement::ToggleGrey moveNodesToCurveGG 1
        ::AIEnv::GUIManagement::ToggleGrey moveNodesPointByTolGI 1
        moveNodesDEZ set projNodesGGVal 1
        moveNodesDEZ set moveNodesPointMethodVal 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey projNodesPoint 0
        ::AIEnv::GUIManagement::ToggleGrey moveNodesToCurveGG 0
        ::AIEnv::GUIManagement::ToggleGrey moveNodesPointByTolGI 0
	    if [moveNodesDEZ get moveNodesToCurveGGVal] {
	        ::AIEnv::GUIManagement::ToggleGrey moveNodesToCurveTol 0
	        ::AIEnv::GUIManagement::ToggleGrey moveNodesToCurvePick 0
	    } else {
	        ::AIEnv::GUIManagement::ToggleGrey moveNodesToCurveTol 1
	        ::AIEnv::GUIManagement::ToggleGrey moveNodesToCurvePick 1
	    }
    }
}

proc aie_move_nodes_trace_elems {name element op} {
    set elems [moveNodesDEZ get elemList]
    if {$elems != "" && [ic_uns_subset_exists $elems]} {
        aie_set_uns_subset_visible $elems
    }
}

proc aie_move_nodes_trace_nodes {name element op} {
    set nodes [moveNodesDEZ get nodeList]
    if {$nodes != "" && [ic_uns_subset_exists $nodes]} {
        aie_set_uns_subset_visible $nodes
    }
}

proc onmoveNodesDEZUnLoad {} {
    global take_first_press
    
    set take_first_press 0
    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    if {$elemList != ""} { ic_uns_subset_delete $elemList }
    foreach n "projNodesGGVal moveNodesToCurveGGVal moveNodesPointMethodVal" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w aie_move_node_proj_trace
        }
    }
    if {[trace vinfo elemList] != ""} {
        trace vdelete elemList w aie_move_nodes_trace_elems
    }
    if {[trace vinfo nodeList] != ""} {
        trace vdelete nodeList w aie_move_nodes_trace_nodes
    }
    set nodeList ""
    set elemList ""
}

proc onmoveNodesInterLoad {} {
    global take_first_press auto_pick_mode
    
    if {$moveNodesGGVal != 0}  return
    if ![info exists moveNodesTypeVal] {
        set moveNodesTypeVal 0
    }
    set projectionList [list "All Parts" "Active Parts" "None" ]
    if {![info exists proj] || $proj == ""} {
        if {[info exists proj_surf] && [ic_geo_is_loaded]} {
            set proj $proj_surf
        }
    }
    if {![info exists proj] || $proj == ""} {
        set proj "All Parts"
    }
    if ![ic_geo_is_loaded] {
        set proj "None"
    }
    if [info exists moveNodesGGVal] {
        if {$moveNodesGGVal == 0 } {
            if {$moveNodesTypeVal == 0} {
                set take_first_press 1
            } else {
                set take_first_press 0
            }
        } else {
            set take_first_press 0
        }
    }
    if {$auto_pick_mode && $moveNodesGGVal == 0} {
        if $moveNodesTypeVal {
            moveNodesIntact pick
        } else {
            moveNodesDynamic pick
        }
    }
}

proc onmoveNodesInterUnLoad {} {
    global take_first_press

    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    set take_first_press 0
    set nodeList ""
}

proc onmoveNodesSingleLoad {} {
    global take_first_press

    if {$moveNodesGGVal == 0} {
        set take_first_press 1
    }
}

proc onmoveNodesMultipleLoad {} {
    global take_first_press

    set take_first_press 0
}

proc onmoveNodesPrismEdgeLoad {} {
    global smooth

    if {[info exists smooth(prism_height)] == 0 } {
        set initheight 1.0
    } else {
        set initheight $smooth(prism_height)
    }
    if {[info exists smooth(prism_ratio)] == 0} {
        set prismratio 1.5
    } else {
        set prismratio $smooth(prism_ratio)
    }
    set isimmutable [ic_uns_isimmutable all]
	if $isimmutable {
        set immutable [ic_uns_get_immutable_elements all]
        # PENTA_6 PENTA_15 PENTA_18
        if {[lsearch -regexp $immutable "PENTA_"] > -1} {
            mess "[llength $immutable] ([llength [lsearch -all -regexp $immutable "PENTA_"]] prism) locked elements are present in the mesh, they will not be moved unless you use \"Redistribute locked prism elements\"\n" red
        }
    }
}

proc onmoveNodesExactLoad {} {
    set csys_name [ic_csystem_get_current]
    set csys_type [lindex [ic_csystem_get $csys_name] 0]
    switch $csys_type {
        cartesian { set moveNodesExactCsysVal 0 }
        cylindrical { set moveNodesExactCsysVal 1 }
    }
    if $auto_pick_mode {moveNodesEx pick}
}

proc onoffsetMeshLoad {} {
    if ![ic_uns_is_loaded] {
	    msg ERROR "No mesh available"
	    offsetMeshDEZ hide
	    return
    }
    if $auto_pick_mode {
	    offsetElemsPick pick
    }
}

proc onoffsetMeshUnLoad {} {
    if {$elemList != ""} { ic_uns_subset_delete $elemList }
    set elemList ""
}

proc onmoveNodesProjSurfLoad {} {
    global projectionSurfList onmoveNodesInit

    if {$proj_surf == ""} {set proj_surf $proj}
    if {$proj_surf == "" || $proj_surf == "None"} {
        set proj_surf "All Parts"
    }
    if ![info exists onmoveNodesInit] {
	    set onmoveNodesInit 1
        set projectionSurfList [list "All Parts" "Active Parts" ]
	    set dir_x 0; set dir_y 0; set dir_z 1
	    set moveNodesProjSurfMethVal 0
	    set moveNodesProjSnapMethVal 0
	    set NodesProjNormalFlag 0
	    set moveNodesProjSurfDirEGVal 0
	    set moveNodesProjSnapDirEGVal 0
    }
    if $auto_pick_mode {moveNodesIntact2 pick}
}

proc onmoveNodesProjSurfUnLoad {} {
    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    set nodeList ""
}

proc onmoveNodesProjCurveLoad {} {
    if $auto_pick_mode {moveNodesIntact3 pick}
}

proc onmoveNodesProjPointLoad {} {
    if $auto_pick_mode {moveNodesIntact4 pick}
}

proc onmoveNodesUnProjLoad {} {
    if $auto_pick_mode {moveNodesIntact5 pick}
}

proc onmoveNodesProjCurveUnLoad {} {
    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    set nodeList ""
}

proc onmoveNodesProjPointUnLoad {} {
    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    set nodeList ""
}

proc onmoveNodesUnProjUnLoad {} {
    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    set nodeList ""
}

proc onmoveNodesUpProjLoad {} {
    global projectionSurfList onmoveNodesInit

    if {$proj_surf == ""} {set proj_surf $proj}
        if {$proj_surf == "" || $proj_surf == "None"} {
	        set proj_surf "All Parts"
        }
        if ![info exists onmoveNodesInit] {
	        set onmoveNodesInit 1
	        set projectionSurfList [list "All Parts" "Active Parts" ]
	        set dir_x 0; set dir_y 0; set dir_z 1
	        set moveNodesProjSurfMethVal 0
	        set moveNodesProjSnapMethVal 0
	        set NodesProjNormalFlag 0
	        set moveNodesProjSurfDirEGVal 0
	        set moveNodesProjSnapDirEGVal 0
    }
    if $auto_pick_mode {moveNodesIntact6 pick}
}

proc onmoveNodesUpProjUnLoad {} {
    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    set nodeList ""
}

proc onlulockElementsUnLoad {} {
    if {$lulockList != ""} { ic_uns_subset_delete $lulockList }
    set lulockList ""
}

proc onmoveNodesOnLineLoad {} {
    if $auto_pick_mode {
        alignDirectionPick pick
    }
}

proc onmoveNodesOnLineUnLoad {} {
    if {$nodeList != ""} { ic_uns_subset_delete $nodeList }
    set nodeList ""
}

#-----------------------------------End of Auto Pick procedures for Move Nodes-----------------------------
#----------------------------------- Procedures for AutoApply for Move Nodes-------------------------------

proc onmoveNodesIntactPick {} {
    # should be empty before node selection
    if {$nodeList != "" && [ic_uns_subset_exists $nodeList]} {
        ic_uns_subset_delete $nodeList
        set nodeList ""
    }
}

proc onmoveNodesDynamicPick {} {
    # should be empty before node selection
    if {$nodeList != "" && [ic_uns_subset_exists $nodeList]} {
        ic_uns_subset_delete $nodeList
        set nodeList ""
    }
}

proc onmoveNodesIntactFinish {} {
    if {$nodeList != ""} {
	    moveNodesDEZ apply
	    if {$auto_pick_mode && $moveNodesTypeVal == 1} {
	        moveNodesIntact pick
	    }
    }
}

proc onmoveNodesDynamicFinish {} {
    if {$nodeList != ""} {
        moveNodesDEZ apply
        if {$moveNodesTypeVal == 0} {
            moveNodesDynamic pick
        }
    }
}

proc onmoveNodesExPick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc onmoveNodesExFinish {} {
    if {$nodeList != ""} {
        aie_set_uns_subset_visible $nodeList
    }
}

proc onoffsetElemsPickPick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc onoffsetElemsPickFinish {} {
    if {$elemList != ""} {
        if $auto_pick_mode {
    	    moveNodesDEZ apply
            offsetElemsPick pick
        } else {
            aie_set_uns_subset_visible $elemList
        }
    }
}

proc onmoveNodesIntact2Pick {} {
    if {$nodeList != ""} { 
        ic_uns_subset_delete $nodeList
    }
}

proc onmoveNodesIntact2Finish {} {
    if {$nodeList != ""} { 
        if $auto_pick_mode {
            if {$moveNodesProjSurfMethVal == 0} {
                moveNodesDEZ apply
	            moveNodesIntact2 pick
	        }
	    } else {
	        aie_set_uns_subset_visible $nodeList
	    }
    }
}

proc onmoveNodesIntact3Pick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc onmoveNodesIntact3Finish {} {
    if {$nodeList != ""} {
        if $auto_pick_mode {
  	        if [ic_geo_is_loaded] {
  	            if $moveNodesToCurveGGVal {
  	                moveNodesToCurvePick pick
  	            } else {
  	                moveNodesDEZ apply
  	                moveNodesIntact3 pick
  	            }
  	        } else {
  	            moveNodesDEZ apply
  	            moveNodesIntact3 pick
  	        }
  	    } else {
  	        aie_set_uns_subset_visible $nodeList
  	    }
    }
}

proc onmoveNodesIntact4Pick {} {
    if {$nodeList != ""} { 
        ic_uns_subset_delete $nodeList
    }
}

proc onmoveNodesIntact4Finish {} {
    if {$nodeList != ""} {
        if $auto_pick_mode {
            if [ic_geo_is_loaded] {
	            switch $moveNodesPointMethodVal {
	                0 {
	                    if !$projNodesGGVal {
	                        projNodesPoint pick
	                    }
	                }
	                1 {
	                    projNodesPoints pick
	                }
	            }
	        } else {
	            moveNodesDEZ apply
	            moveNodesIntact4 pick
	        }
        } else {
            aie_set_uns_subset_visible $nodeList
        }
    }
}

proc onprojNodesPointFinish {} {
    if {$projPoint != "" && $auto_pick_mode} {
        moveNodesDEZ apply
        moveNodesIntact4 pick
    }
}

proc onmoveNodesIntact5Pick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc onmoveNodesIntact5Finish {} {
    if {$nodeList != ""} {
        if $auto_pick_mode {
            moveNodesDEZ apply
	        moveNodesIntact5 pick
	    } else {
	        aie_set_uns_subset_visible $nodeList
	    }
    }
}

proc onmoveNodesIntact6Pick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc onmoveNodesIntact6Finish {} {
    if {$nodeList != ""} {
        if {$auto_pick_mode && [llength $mvpointList2] == 2} {
            moveNodesDEZ apply
	        moveNodesIntact6 pick
	    } else {
	        aie_set_uns_subset_visible $nodeList
	    }
    }
}

proc onalignDirectionPickFinish {} {
    if {$alignDir != "" && $auto_pick_mode} {
        alignNodesPick pick
    }
}

proc onalignNodesPickPick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc onalignNodesPickFinish {} {
    if {$nodeList != ""} {
        if $auto_pick_mode {
            moveNodesDEZ apply
            alignDirectionPick pick
        } else {
            aie_set_uns_subset_visible $nodeList
        }
    }
}

proc onmoveNodesRefLocFinish {} {
    set xyz  [va_check_data_set_point  $ref_point xyz]
    set X [lindex $xyz 0]
    set Y [lindex $xyz 1]
    set Z [lindex $xyz 2]
}

#----------------------------------- End of Procedures for AutoApply for Move Nodes------------------------

proc onmoveNodesDEZOK {} {
    global fam_visible
    # nodeList could be empty for move nodes interactive    
    switch $moveNodesGGVal {
        0 - 1 - 3 -  5 - 6 - 7 - 8 - 10 {
            if {$nodeList == "" || ![ic_uns_subset_exists [lindex $nodeList 0]]} {
                mess  "No node(s) selected.\n" red
                return
            }
        }
    }

    switch $moveNodesGGVal {
	    0 {
	        set xypos ""
	        if !$moveNodesTypeVal {
		        set xypos [lindex $nodeList 1]
		        set nodeList [lindex $nodeList 0]
		        moveNodesDEZ setclean
	        }
	        if ![ic_uns_subset_exists $nodeList] {
		        mess "Subset $nodeList does not exist; Please select Nodes to move\n"
		        return
	        }
	        ic_uns_subset_configure $nodeList -visible 1
	        if ![warn_if_periodic $nodeList] {
		        ic_uns_subset_delete $nodeList
		        set nodeList ""
		        return
	        }
	        # This is expensive but required otherwise nodes will move
	        # off the geometry as the geometry would be in different family which
	        # may not be visible
	        switch $proj {
		        "All Parts" {
		            select_move_uns_map $nodeList 0 $allow_invert $xypos all
		        }
		        "Active Parts" {
		            select_move_uns_map $nodeList 0 $allow_invert $xypos vis
		        }
		        "None" {
		            select_move_uns_map $nodeList 0 $allow_invert $xypos none
		        }
	        }
#	        if !$project_geom {
#		        select_move_uns_map $nodeList 0 $allow_invert $xypos none
#	        } elseif !$project_active {
#		        select_move_uns_map $nodeList 0 $allow_invert $xypos all
#	        } else {
#		        select_move_uns_map $nodeList 0 $allow_invert $xypos vis
#	        }
	    }

	    1 {
	        if ![warn_if_periodic $nodeList] {
		        ic_uns_subset_delete $nodeList
		        set nodeList ""
		        return
	        }
	        switch $moveNodesExactCsysVal {
		        0 {
		            set xval $moveNodesExactBVertexXVal
		            set yval $moveNodesExactBVertexYVal
		            set zval $moveNodesExactBVertexZVal
		        }
		        1 {
		            set xval $moveNodesExactCylRVal
		            set yval $moveNodesExactCylTVal
		            set zval $moveNodesExactCylZVal
		        }
	        }
	        set val2(xval) $X; set val2(yval) $Y; set val2(zval) $Z;
	        set doit ""; set val ""
	        foreach p {xval yval zval} {
		        if [set $p] {
		            if {$val2($p) == ""} {
			            lappend doit 0
			            lappend val 0
		            } else {
			            lappend doit 1
			            lappend val $val2($p)
		            }
		        } else {
		            lappend doit 0
		            lappend val 0
		        }
	        }
	        set csys_name [ic_csystem_get_current]
	        set amt [ic_uns_move_nodes_exact $nodeList $moveNodesExactRGVal \
				$doit $val $csys_name]
	        if [lindex $amt 3] {
		        mess "[lindex $amt 3] nodes moved,\
			        min [lindex $amt 0],\
			        max [lindex $amt 1],\
			        mean [expr {[lindex $amt 2] / ([lindex $amt 3] + 0.0)}]\n"
	            aie_updateMeshVis
	        } else {
	        	mess "0 nodes moved\n"
	        }
	        return
	    }
	    2 {
            if {$elemList == ""} {
                mess "Must specify elements to offset\n"
                return
    	    }
    	    if {$distance == ""}  {
                mess "Must specify distance\n"
                return
    	    }
            set types [ic_uns_subset_list_types $elemList]
            set found 0
            foreach t "TRI_3 TRI_6 QUAD_4 QUAD_8 QUAD_9" {
                if {[lsearch $types $t] >= 0} {
                    set found 1
                    break
                }
            }
            if !$found {
	    	    mess "Must specify shell elements to offset\n"
                return
            }
   	        ic_uns_offset_mesh map $elemList dir normal dist $distance
   	        ic_uns_subset_delete $elemList
    	    set elemList ""
	    }

	    3 {
	        if {$alignDir == ""} {
		        msg ERROR "No reference direction specified"
		        return
	    }
	        set pos [ic_uns_get_node_positions $alignDir]
	        ic_uns_subset_delete $alignDir
	        set $alignDir ""
	        if {[llength $pos] != 2} return
	        if {$nodeList == ""} {
		        msg ERROR "No nodes selected for alignment"
		        return
	        }
	        ic_uns_project_nodes_to_line [lindex $pos 0] [lindex $pos 1] 0 $nodeList
	    }

	    4 {
	        global smooth
	        
	        set smooth(prism_height) $initheight
	        set smooth(prism_ratio) $prismratio
            set local $use_local_redist
	        set end_aspect 0.001
	        
	        ic_uns_redistribute_prism_edge $smooth(prism_height) $moveNodesPrismEdgeEGVal $smooth(prism_ratio) $local $end_aspect !$lockedFlag
	    }
        5 - 10 {
            if {$moveNodesGGVal == 5} {
                set projtype surface
            } else {
                set projtype same
            }
            set vec [list $dir_x $dir_y $dir_z]
            set fam_active ""
            switch $proj_surf {
                "All Parts" {
                    set fam_active "all"
                }
                "Active Parts" {
                    set fam_active "vis"
                }
            }
            if {$fam_active != "" && (($moveNodesGGVal == 5 && \
                ($moveNodesProjSurfMethVal == 0 || $moveNodesProjSurfMethVal == 1)) || \
                ($moveNodesGGVal != 5 && ($moveNodesProjSnapMethVal == 0 || \
                $moveNodesProjSnapMethVal == 1)))} {
                if {$fam_active == "vis" || $fam_active == "all"} {
                    if {$fam_active == "vis"} {
                        set fam_active ""
                        foreach f [ic_uns_list_families] {
                            if {([ic_uns_check_family $f]) && [info exists fam_visible($f)] && ($fam_visible($f))} {
                                # check if part contains surfaces
                                # (only for surface projection)
                                if {$moveNodesGGVal != 5 || [llength [ic_geo_get_objects surface $f]] > 0} {
                                    lappend fam_active $f
                                }
                            }
                        }
                        if {$fam_active == ""} {
                            mess "No active surface part\n" red
                            return
                        }
                    } else {
                        set any_surface_fam 0
                        foreach f [ic_uns_list_families] {
                            if {[ic_uns_check_family $f]} {
                                # check if part contains surfaces
                                if {$moveNodesGGVal != 5 || [llength [ic_geo_get_objects surface $f]] > 0} {
                                    set any_surface_fam 1
                                    break
                                }
                            }
                        }
                        if {!$any_surface_fam} {
                            if {$moveNodesGGVal == 5} {
                                mess "No surface part in geometry\n" red
                            } else {
                                mess "No part in geometry\n" red
                            }
                            return
                        }
                        set fam_active ""
                    }
                }
                set dir_vec ""
                if {($moveNodesGGVal == 5 && $moveNodesProjSurfDirEGVal == 0) || \
                     ($moveNodesGGVal == 10 && $moveNodesProjSnapDirEGVal == 0)} {
                    # explicit
                    if {$NodesProjNormalFlag == 1} {
                        set dir_vec [list $dir_x $dir_y $dir_z]
                    } else {
                        set dir_vec [list [expr $dir_x * -1] [expr $dir_y * -1] [expr $dir_z * -1]]
                    }
                } else {
                    # vector
                    if {[llength $mvpointList2] < 2} {
                        msg ERROR "Not enough nodes selected for direction vector"
                        return
                    }
                    set dir_vec [ic_vcalc diff [lindex $mvpointList2 0] [lindex $mvpointList2 1]]
                }
                if {($moveNodesGGVal == 5 && $moveNodesProjSurfMethVal == 0) || \
                    ($moveNodesGGVal == 10 && $moveNodesProjSnapMethVal == 0)} {
                    mess "Direction Components: Nearest\n"
                } else {
                    mess "Direction Components: $dir_x $dir_y $dir_z\n"
                }
                if {$moveNodesGGVal == 5} {
                    set mth $moveNodesProjSurfMethVal
                } else {
                    set mth $moveNodesProjSnapMethVal
                }
                if {($moveNodesGGVal == 5 && $moveNodesProjSurfDirEGVal == 0 && $mth == 1 && \
                    $NodesProjNormalFlag == 0) || \
                    ($moveNodesGGVal == 10 && $moveNodesProjSnapDirEGVal == 0 && $mth == 1 && \
                    $NodesProjNormalFlag == 0)} {
                    set csys_name [ic_csystem_get_current]
                    set doit ""; set val ""
                    foreach p {dir_x dir_y dir_z} {
                        if {[set $p] != 0} {
                            if {[set $p] == ""} {
                                lappend doit 0
                                lappend val 0
                            } else {
                                lappend doit 1
                                lappend val [set $p]
                            }
                        } else {
                            lappend doit 0
                            lappend val 0
                        }
                    }
                    set before_move [ic_uns_subset_list_elements $nodeList]
                    ic_undo_group_begin
                    ic_uns_move_nodes_exact $nodeList 0 "$doit" "$val" $csys_name
                    set after_move [ic_uns_get_node_positions $nodeList]
                    set err [ic_uns_set_node_dimension $nodeList $projtype 0 $fam_active $mth $NodesProjNormalFlag $dir_vec]
                    ic_undo_group_end
                    if $err {
                        set i 0; set pos ""
                        set smap [ic_uns_subset_create ""]
                        foreach n [ic_uns_get_node_positions $nodeList] {
                            if {$n == [lindex $after_move $i]} {
                                set num [lindex [lindex $before_move $i] end]
                                ic_uns_subset_add_node_numbers $smap $num 1
                                lappend pos [lindex [lindex $before_move $i] 2]
                            }
                            incr i
                        }
                        if {$pos != ""} {
                            ic_uns_set_node_positions $smap $pos
                        }
                        ic_uns_subset_delete $smap
                    }                   
                } else {
                    if {($moveNodesGGVal == 5 && $moveNodesProjSurfMethVal == 0) || \
                        ($moveNodesGGVal == 10 && $moveNodesProjSnapMethVal == 0)} {
                        ic_uns_set_node_dimension $nodeList $projtype 0 $fam_active $mth $NodesProjNormalFlag "0 0 0"
                    } else {
                        ic_uns_set_node_dimension $nodeList $projtype 0 $fam_active $mth $NodesProjNormalFlag $dir_vec
                    }
                }
            }
        }

	    6 {
	        busy 1
	        set projtype curve
	        if $moveNodesToCurveGGVal {
                if {$nodeCrvTol == "" || $nodeCrvTol < 0} {
                    mess "Please enter a valid tolerance\n" red
                    busy reset
                    return
                }
                set i 0; set opts ""
                catch { unset ele }
                foreach n [ic_uns_subset_list_elements $nodeList] {
                    if {[lindex $n 0] == "VERTEX"} {
                        set ele($i) [lindex $n 1]
                        lappend opts [lindex $n 2]
                        incr i
                    }
                }
	            set nodes_map [ic_uns_subset_create]
	            if {$nodes_map == ""} {
	                ic_uns_subset_delete $nodes_map
	                busy reset
	                return
	            }
	            if {$curveList == ""} {
	                set to_proj [ic_geo_get_objects $projtype]
	                mess "Using all existing curves to project nodes by tolerance\n"
	            } else {
	                set to_proj $curveList
	                mess "Using selected curves to project nodes by tolerance\n"
	            }
	            if {$to_proj == ""} {
	                ic_uns_subset_delete $nodes_map
	                busy reset
	                return
	            }
                set n 0
	            foreach p1 $opts {
	                set dist 0.0
	                set p2 [ic_geo_project_coords $projtype $to_proj $p1]
	                foreach i {0 1 2} {
	                    set p [expr {[lindex $p2 $i] - [lindex $p1 $i]}]
	                    set dist [expr {$dist + $p * $p}]
	                }
	                if {[expr {sqrt($dist)}] <= $nodeCrvTol} {
                        ic_uns_subset_add_node_numbers $nodes_map $ele($n)
	                }
                    incr n
	            }
                ic_uns_subset_delete $nodeList
                set nodeList $nodes_map
                set count [ic_uns_subset_count_nodes $nodeList]
                if $count {
                    mess "Projected $count nodes by tolerance $nodeCrvTol to curves\n"
                } else {
                    mess "No nodes found to project within this tolerance\n"
                }
            }
	        ic_uns_set_node_dimension $nodeList $projtype
	        busy reset
	    }

	    7 {
	        set projtype point
            set nodeList [lindex $nodeList 0]
	        switch $moveNodesPointMethodVal {
	            0 {
	                if {[ic_uns_subset_count_nodes $nodeList] > 32000} {
		                mess "Error: Can only set 32000 nodes to prescribed at one time\n" red
		                return
	                }
	                if $projNodesGGVal {
		                ic_uns_set_node_dimension $nodeList self
	                } else {
		                set opts [ic_uns_get_node_positions $nodeList]
		                if ![ic_geo_is_loaded] {
		                    set i 1
		                    set arglist ""
		                    foreach op $opts {
			                    lappend arglist [list "Point $i" $op get_graphics_loc]
			                    incr i
		                    }
		                    set npts [question_box .projpt "Project Point" "Point Coords to Project to" ""]
		                 if {$npts == ""} return
		                    ic_uns_set_node_positions $nodeList [list $npts]
	                    } else {
                            if {$projPoint == ""} {
                                mess "Select point to project to\n"
                                return
                            }
			                set ptobj $projPoint
			                set ptt [ic_geo_get_point_location $ptobj]
			                ic_uns_set_node_positions $nodeList [list $ptt]
			                ic_uns_set_node_dimension $nodeList $projtype
	                    }
	                }
	            }
	            1 {
	                if {$nodePointTol == "" || $nodePointTol < 0} {
	                    mess "Please enter a valid tolerance\n" red
                        return
                    }
                    set nodes [ic_uns_subset_list_elements $nodeList]
                    set i 0; set opts ""
                    catch { unset ele }
                    foreach n $nodes {
                        if {[lindex $n 0] == "VERTEX"} {
                            set ele($i) [lindex $n 1]
                            lappend opts [lindex $n 2]
                            incr i
                         }
                    }
                    if {$projPoints == ""} {
                        set to_proj [ic_geo_get_objects $projtype]
                        mess "Using all existing points to project nodes by tolerance\n"
                    } else {
                        set to_proj $projPoints
                        mess "Using selected points to project nodes by tolerance\n"
                    }
                    busy 1
                    set count_all 0
                    foreach pp $to_proj {
                        set nodes_map [ic_uns_subset_create]
                        if {$nodes_map == ""} return
                        set p2 [ic_geo_get_point_location $pp]
	                    set n 0
	                    foreach p1 $opts {
	                        set dist 0.0
	                        foreach i {0 1 2} {
	                            set p [expr {[lindex $p2 $i] - [lindex $p1 $i]}]
	                            set dist [expr {$dist + $p * $p}]
	                        }
	                        if {[expr {sqrt($dist)}] <= $nodePointTol} {
                                ic_uns_subset_add_node_numbers $nodes_map $ele($n)
	                        }
                            incr n
                        }
                        set count [ic_uns_subset_count_nodes $nodes_map]
                        if {$count > 32000} {
                            mess "Error projecting nodes by tolerance to point ${pp}: can only set 32000 nodes to prescribed at one time\n" red
                            ic_uns_subset_delete $nodes_map
                            break
                        } else {
	                        set count_all [expr $count + $count_all]
	                        ic_uns_set_node_positions $nodes_map [list $p2]
	                        ic_uns_set_node_dimension $nodes_map $projtype
	                        ic_uns_subset_delete $nodes_map
	                    }
                    }
                    mess "Projected $count_all nodes by tolerance $nodePointTol to points\n"
                    busy reset
		        }
	        }
	    }
	
	    8 {
	        set projtype none 
	        ic_uns_set_node_dimension $nodeList $projtype
	    }
	    
	    9 {
            if {$lulockList == ""} {
                msg ERROR "Please select elements"
                return
            }
            busy 1
            ic_uns_immutable $lulockList $locktypeg
   	        if [ic_uns_subset_exists $lulockList ] {
		        ic_uns_subset_delete $lulockList
	        }
    	    set lulockList ""
            busy 0
        }
        
	    11 {
	        set projtype reset
	        # reset dimension of vertices in entire mesh
	        ic_uns_set_node_dimension all $projtype
	    }	    
	
	    12 {
	        switch $moveNodesPlaneNormEGVal {
		        0 { 
		            set nrm [ic_vset -vec - $Planenormal]
		            set p1 $PlanePntList
		            set px [ic_vcalc vec_norm $nrm]
		            set py [ic_vcalc product $nrm $px]
		            set p2 [ic_vcalc sum $p1 $px]
		            set p3 [ic_vcalc sum $p1 $py]					
		        }
		        1 {	
		            set p1 $PlanePnt1
		            set p2 $PlanePnt2	
		            set p3 $PlanePnt3										
		            set nrm [ic_vcalc product $p1 $p2 $p3]
		        }
	        }
	        # Note: picker always return xyz in LCS: convert into global
	        foreach vec "nrm p1 p2 p3" {
		        set v [set $vec]
		        if {$v == ""} { return }
		        set $vec [ic_coords_into_global $v]
	        }
	        ic_uns_project_nodes_to_plane $p1 $nrm $nodeList
	    }
    }

    if {$nodeList != ""} {
        aie_reset_icons_subset $nodeList
        ic_uns_subset_delete $nodeList
    }
    mess "Done\n" blue
    set nodeList ""
    aie_updateMeshVis
}

proc onmoveNodesDEZCancel {} {
    if {$nodeList != ""} { 
	    ic_uns_subset_delete $nodeList 
    }
    set nodeList ""
}

proc onmoveNodesPickFinish {} {
    if {$moveNodesGGVal == 0} {
	    moveNodesDEZ apply
    }
}

proc onlulockElementsPickPick {} {
    if {$lulockList != ""} {
        ic_uns_subset_delete $lulockList
    }
}

proc onlulockElementsPickFinish {} {
    if {$auto_pick_mode && $lulockList != ""} {
        moveNodesDEZ apply
    }
}

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

proc ontransformElemsToolsDEZLoad {} {
    global lcs_data

    if ![info exists transformElemsToolsInit] {
        set transformElemsToolsInit 1
        set transformElemsEGVal 0
        set translateElemsEGVal 0
        set ElemRotateAxisOptionEGVal 0
        set ElemMirrorAxisOptionEGVal 0
        set x 0; set y 0; set z 0
        set xF 1; set yF 1; set zF 1
        set rot_angle 0
        set moveElemesCopyGGVal 0
        set moveElemesCopyGG2Val 0
        set moveElemesCopyGG3Val 0
        set moveElemesCopyGG4Val 0
        set RotateElemCenterEGVal 0
        set ReflectElemCenterEGVal 0
        set ScaleElemsCentEGVal 0
        set transAutoMeshEGVal 0
        set incrParts ""
        set rotateAutoMeshList ""
    }
    if {$transformElemsEGVal == 4 && $transAutoMeshEGVal == 2} {
        if ![llength [ic_image get global]] {
            ic_image csys_im cartesian
        }
    }
}

proc ontransformElemsToolsDEZAfterLoad {} {
    if ![ic_uns_is_loaded] {
	    msg ERROR "No mesh available"
	    transformElemsToolsDEZ hide
	    return
    }
    foreach n "moveElemesCopyGGVal moveElemesCopyGG2Val moveElemesCopyGG3Val" {
        if {[trace vinfo $n] != ""} {
	        trace vdelete $n w trace_moveElemesCopyGG
        }
        trace variable $n w trace_moveElemesCopyGG
    }
    if {[trace vinfo elemList] != ""} {
	    trace vdelete elemList w trace_moveElemList
    }
    trace variable elemList w trace_moveElemList
}

proc ontransformElemsToolsDEZUnLoad {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
    set elemList ""
    if {[trace vinfo elemList] != ""} {
	    trace vdelete elemList w trace_moveElemList
    }
    foreach n "moveElemesCopyGGVal moveElemesCopyGG2Val moveElemesCopyGG3Val" {
        if {[trace vinfo $n] != ""} {
	        trace vdelete $n w trace_moveElemesCopyGG
        }
    }
    if [llength [ic_image get global]] {
       ic_image delete csys_im
    }
}

proc onrotateAutoMeshFromLcsLoad {} {
    if {$transformElemsEGVal == 4 && $transAutoMeshEGVal == 2} {
        if ![llength [ic_image get global]] {
            ic_image csys_im cartesian
        }
    }
}

proc onrotateAutoMeshFromLcsUnLoad {} {
   if [llength [ic_image get global]] {
       ic_image delete csys_im
    }
}

proc ontransAutoMeshEGILoad {} {
    if {$transformElemsEGVal == 4 && $transAutoMeshEGVal == 2} {
        if ![llength [ic_image get global]] {
            ic_image csys_im cartesian
        }
    }
}

proc ontransAutoMeshEGIUnLoad {} {
   if [llength [ic_image get global]] {
       ic_image delete csys_im
    }
}

proc trace_moveElemesCopyGG {name element op} {
    if ![transformElemsToolsDEZ get $name] {
        switch $name {
            ::AIEnv::DEZ::transformElemsToolsDEZ::moveElemesCopyGGVal {
                transformElemsToolsDEZ set copyElemsMergeNodesGG0Val 0
                ::AIEnv::GUIManagement::ToggleGrey copyElemsMergeNodesGI0 1
            }
            ::AIEnv::DEZ::transformElemsToolsDEZ::moveElemesCopyGG2Val {
                transformElemsToolsDEZ set copyElemsMergeNodesGG1Val 0
                ::AIEnv::GUIManagement::ToggleGrey copyElemsMergeNodesGI1 1
            }
            ::AIEnv::DEZ::transformElemsToolsDEZ::moveElemesCopyGG3Val {
                transformElemsToolsDEZ set copyElemsMergeNodesGG2Val 0
                ::AIEnv::GUIManagement::ToggleGrey copyElemsMergeNodesGI2 1
            }
        }
    }
}

proc trace_moveElemList {name element op} {
    set elems [transformElemsToolsDEZ get elemList]
    if {$elems != ""} {
        if [ic_uns_subset_exists $elems] {
            aie_set_uns_subset_visible $elems
        }
    }
}

proc ontransfmoveElemesPickPick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc ontransfmoveElemesPickFinish {} {
    if {$elemList != ""} {
        aie_set_uns_subset_visible $elemList
    }
}

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

proc ontransformElemsToolsDEZOK {} {
    global dir

    if {$elemList == ""} {
        msg ERROR "No mesh selected"
        return
    }

    set use_map $elemList
    set make_copy 0
    switch $transformElemsEGVal {
        0 { if $moveElemesCopyGGVal { set make_copy 1 } }
        1 { if $moveElemesCopyGG2Val { set make_copy 1 } }
        2 { if $moveElemesCopyGG3Val { set make_copy 1 } }
        3 { if $moveElemesCopyGG4Val { set make_copy 1 } }
        4 { if $moveElemesCopyGG5Val { set make_copy 1 } }
    }
    if !$make_copy {
        set numCopies 1
    }
    set ncount 1
    set use_smap 0
    if {$transformElemsEGVal == 0 || $transformElemsEGVal == 1} {
        set ncount $numCopies
    }
    ic_start_bigunsop 1
    set tdv_active_set 0
    if {$make_copy && $ncount > 1} {
        tdv_active 0
        set tdv_active_set 1
    }
    if $make_copy {
        set use_smap 1
        set enn 0; set nnn 0
        for {set i 0} {$i < $ncount } {incr i} {
            set smap($i) [ic_uns_subset_create ""]
            if {$i > 0} {
                ic_uns_subset_subtract_from $use_map $smap([expr $i - 1])
            }
            set nn [ic_uns_duplicate_elements $use_map $smap($i)]
            set num_e [lindex $nn 0]; set num_n [lindex $nn 1]
            if {$ncount > 1} {
                status_message "Stage [expr $i + 1]: $num_e new elements, $num_n new nodes"
                update idletasks
            } else {
                status_message "$num_e new elements, $num_n new nodes"
                update idletasks
            }
            set enn [expr $enn + $num_e]; set nnn [expr $nnn + $num_n]
        }
        mess "Summary: $enn new elements, $nnn new nodes\n"
    }
    catch { unset off_set }
    catch { unset transfCenter }
    catch { unset argList }
    ic_undo_group_begin
    for {set i 0} {$i < $ncount} {incr i} {
        if {$use_smap} {
            set nmap $smap($i)
        } else {
            set nmap $use_map
        }
        set argList [list ic_uns_move_elements $nmap]
        set text_print ""
        switch $transformElemsEGVal {
            0 {
                # TRANSLATION
                set text_print "Moving"
                if ![info exists off_set] {
                    switch $translateElemsEGVal {
                        0 {
                            set off_set [list $x $y $z]
                            mess "Translation Components: $off_set\n"
                        }
                        1 {
                            set off_set [ic_vcalc diff [lindex $pointList2 0] [lindex $pointList2 1]]
                        }
                    }
                }
                set tt ""
                foreach j {0 1 2} {
                    lappend tt [expr {($i+1) * [lindex $off_set $j]}]
                }
                lappend argList translate $tt
            }
            1 {
                set text_print "Rotating"
                if ![info exists transfCenter] {
                    # in Rotation-----------
                    switch $ElemRotateAxisOptionEGVal {
                        0 {set rot_axis {1 0 0} }
                        1 {set rot_axis {0 1 0} }
                        2 {set rot_axis {0 0 1} }
                        3 {
                            set rot_axis [ic_vcalc diff [lindex $axisElemList 0] [lindex $axisElemList 1]]
                        }
                    }
                    if {$rot_axis ==""} {
                        if $tdv_active_set { tdv_active 1 }
                        mess "\nRotation axis was not specified" red
                        ic_undo_group_end
                        ic_finish_bigunsop
                        return
                    }
                    mess "\nAngle: $rot_angle\n"
                    if {$rot_angle==0} {
                        if $tdv_active_set { tdv_active 1 }
                        mess "Error: Angle was not specified!\n" red
                        ic_undo_group_end
                        ic_finish_bigunsop
                        return
                    }
                    # take care of center of rotation-----
                    switch $RotateElemCenterEGVal {
                        0 { set transfCenter {0 0 0} }
                        1 { set transfCenter "centroid"}
                        2 {
                            if {$rotateCenterPnt == ""} {
                            if $tdv_active_set { tdv_active 1 }
                                mess "Error: Rotation center point not selected\n" red
                                ic_undo_group_end
                                ic_finish_bigunsop
                                return
                            }
                            set transfCenter [ic_geo_get_point_location $rotateCenterPnt]
                        }
                    }
                }
                set rot [expr {($i+1) * $rot_angle}]
                lappend argList rotate $rot rotate_axis $rot_axis
                lappend argList cent $transfCenter
            }
            2 {
                set text_print "Mirroring"
                # IN MIRROR
                switch $ElemMirrorAxisOptionEGVal {
                    0 {set mirror_norm {1 0 0} }
                    1 {set mirror_norm {0 1 0} }
                    2 {set mirror_norm {0 0 1} }
                    3 {
                        set mirror_norm [ic_vcalc diff [lindex $normPointList 0] [lindex $normPointList 1]]
                    }
                }
                lappend argList mirror $mirror_norm
                switch $ReflectElemCenterEGVal {
                    0 { set transfCenter {0 0 0} }
                    1 { set transfCenter "centroid"}
                    2 {
                        if {$reflectCenterPnt == ""} {
                            if $tdv_active_set { tdv_active 1 }
                            mess "Error: Reflection center point not selected\n" red
                            ic_undo_group_end
                            ic_finish_bigunsop
                            return
                        }
                        set transfCenter [ic_geo_get_point_location $reflectCenterPnt]
                    }
                }
                lappend argList cent $transfCenter
            }
            3 {
                set text_print "Scaling"
                set scaleFactor [list $xF $yF $zF]
                lappend argList scale $scaleFactor
                switch $ScaleElemsCentEGVal {
                    0 { set transfCenter {0 0 0} }
                    1 { set transfCenter "centroid"}
                    2 {
                        if {$scaleCenterPnt == ""} {
                            if $tdv_active_set { tdv_active 1 }
                            mess "Error: Scale center point not selected\n" red
                            ic_undo_group_end
                            ic_finish_bigunsop
                            return
                        }
                        set transfCenter [ic_geo_get_point_location $scaleCenterPnt]
                    }
                }
                lappend argList cent $transfCenter
                set cur_csys [ic_csystem_get_current]
                if {$cur_csys != "global"} {
                    if {[lindex [ic_csystem_get $cur_csys] 0] != "cartesian"} {
                        mess "Error: current coordinate system $cur_csys is not cartesian\n" red
                        ic_undo_group_end
                        ic_finish_bigunsop
                        return
                    } else {
                        set reset_csys ""
                        ic_uns_move_lcs_lcs $cur_csys global $nmap
                        lappend reset_csys $nmap
                        if {$reset_csys != ""} {
                            ic_csystem_set_current global
                        }
                    }
                }
            }
            4  {
                switch $transAutoMeshEGVal {
                    0 {
                        if {[llength $rotateAutoMeshList] != 6} {
                            ic_mess "Select 6 locations\n" red
                            ic_undo_group_end
                            ic_finish_bigunsop
                            return
                        }
                        foreach "p00 p01 p02 p10 p11 p12" $rotateAutoMeshList ""
                            if {[ic_csystem_get_current] != "global"} {
                                foreach p "p00 p01 p02 p10 p11 p12" {
                                    set $p [ic_coords_into_global [set $p]]
                                }
                            }
                            set from [list $p00 $p01 $p02]
                            set to [list $p10 $p11 $p12]							
                        }
                    1 {
                        if {[llength $rotateAutoMeshList] != 2} {
                            mess "Select two curves\n" red
                            ic_undo_group_end
                            ic_finish_bigunsop
                            return
                        }
                        foreach i "0 1" {
                            set crv [lindex $rotateAutoMeshList $i]
                            if ![llength [ic_geo_check_objects_exist curve $crv]] {
                                mess "Select two curves!\n" red
                                ic_undo_group_end
                                ic_finish_bigunsop
                                return
                            }
                            set p${i}0 [lindex [ic_geo_get_crv_pos 0 $crv] 0]
                            set p${i}1 [lindex [ic_geo_get_crv_pos 0.5 $crv] 0]
                            set p${i}2 [lindex [ic_geo_get_crv_pos 1 $crv] 0]
                        }
                        set from [list $p00 $p01 $p02]
                        set to [list $p10 $p11 $p12]			 
                    }
                    2 {
                        # From LCS to LCS
                        set from $fromLCS
                        set to $toLCS
                    }
                }
                ic_uns_move_lcs_lcs $from $to $nmap
            }
        }

        #----evaluate
        if {$nmap !=""} {eval $argList}
        # scale LCS reset
        switch $transformElemsEGVal {
            3 {
                if {[info exists reset_csys] && $reset_csys != ""} {
                    ic_uns_move_lcs_lcs global $cur_csys $nmap
                    ic_csystem_set_current $cur_csys
                    unset reset_csys; unset cur_csys
                }
            }
        }
        if {$i == [expr $ncount - 1] && $text_print != ""} {
            if $make_copy { mess "Copy [expr $i + 1] done\n" }
                mess "$text_print elements done\n"
            } elseif {$text_print != "" && $make_copy} {
                status_message "Copy [expr $i + 1] done"
                update idletasks
            }
            if {$incrParts != "" && $make_copy} {
            foreach part $incrParts {
                if ![ic_uns_subset_move_part_elements $nmap $part ${part}_$i] {
                    mess "Increment part failed for part $part\n" red
                } else {
                    mess "Increment part $part to ${part}_$i\n"
                }
            }
        }
        if $make_copy {
            ic_uns_subset_delete $nmap
        }
    }
    aie_create_parts_in_tree_if_needed

    catch { unset smap }
    set elemList $use_map
    if {$make_copy && ($numCopies > 0)} {
        set copy_elems_nodes 0
        set merge_tol ""
        switch $transformElemsEGVal {
            0 {
                set copy_elems_nodes $copyElemsMergeNodesGG0Val
                if {$copyElemsMergeNodesGI0TVal == 1} {
                    set merge_tol $mergeTol
                }
            }
            1 {
                set copy_elems_nodes $copyElemsMergeNodesGG1Val
                if {$copyElemsMergeNodesGI1TVal == 1} {
                    set merge_tol $mergeTol
                }
            }
            2 {
                set copy_elems_nodes $copyElemsMergeNodesGG2Val
                if {$copyElemsMergeNodesGI2TVal == 1} {
                    set merge_tol $mergeTol
                }
            }
        }
        if $copy_elems_nodes {
            if {$merge_tol == ""} {
                set merge_tol "by_min_edge"
            }
            ic_uns_merge_nodes all $merge_tol "0 0 0" "0 0 0" 0 1 1
            if $mergeElems {
                set subset [ic_uns_create_diagnostic_subset]
                ic_uns_diagnostic subset all diag_type duplicate disp_subset $subset quiet 1
                ic_uns_delete_contents $subset
                ic_uns_subset_delete $subset
                set elemList ""
            }
        }
    }
    if $tdv_active_set {
        status_message ""
        update idletasks
        tdv_active 1
    }
    ic_undo_group_end
    ic_finish_bigunsop
    aie_create_parts_in_tree_if_needed
    aie_update_parts_in_tree_if_needed
    aie_part_update_nodes
    aie_update_parts_vis 0
    transformElemsToolsDEZ setdirty
    mess "Done transform\n"
}

#-----------------------------------------------------------------------
proc onmorphElemsToolsDEZLoad {} {
#Insert default args here
mess "OK Load\n"
}
#-----------------------------------------------------------------------
proc onmorphElemsToolsDEZApply {} {
#Insert script that should occur when hitting Apply here
mess "OK Apply\n"
}

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


proc checkMidSideTetraElements {on} {
    if $standardTetra {
        if {$on == "2"} {
            set standardTetra 0
        } elseif {$on == "1"} {
            set strongTetra 0
        }
    } elseif $strongTetra {
        if {$on == "2"} {
            set standardTetra 0
        } elseif {$on == "1"} {
            set strongTetra 0
        }
    }
}

#-----------------------------------Auto Pick procedures for Merge Nodes---------------------------------
proc onmergeInterRMLoad {} {
    if $auto_pick_mode {mergeNodesPick pick}
}
#-----
proc onmergeTolRMLoad {} {
    if $auto_pick_mode {mergeNodesPick2 pick}
}
#-----------------------------------End of Auto Pick procedures for Merge Nodes----------------------------

proc onmergeNodesDEZLoad {} {
    global uns_select_for

    set uns_select_for merge
}

proc onmergeNodesDEZAfterLoad {} {
    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        mergeNodesDEZ hide
        return
    }
    if {[trace vinfo mergeNodeList] != ""} {
	    trace vdelete mergeNodeList w aie_trace_mergeNodeList
    }
    trace variable mergeNodeList w aie_trace_mergeNodeList
}

proc onmergeNodesDEZUnLoad {} {
    global uns_select_for
    
    set uns_select_for select
    if {[trace vinfo mergeNodeList] != ""} {
	    trace vdelete mergeNodeList w aie_trace_mergeNodeList
    }
}

proc aie_trace_mergeNodeList {name element op} {
    set elems [mergeNodesDEZ get mergeNodeList]
    if {$elems != ""} {
        if [ic_uns_subset_exists $elems] {
            aie_set_uns_subset_visible $elems
        }
    }
}

proc onmergeNodesDEZOK {} {
    global auto_pick_mode plot_window histo_crit

    set nmerged 0
    set print_mess 1

    set active_subsets ""
    if {$mergeNodesEGVal == "0" || $mergeNodesEGVal == "1"} {
        catch { unset active_subsets_types; unset active_subsets_parts }
        foreach sub [ic_uns_subset_list_visible Selected] {
            set vis [expr [::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $sub 1] == 1]
            if !$vis continue
            lappend active_subsets $sub
            set active_subsets_types($sub) [ic_uns_subset_list_types $sub]
            set active_subsets_parts($sub) [ic_uns_subset_list_families $sub]
        }
    }
    switch $mergeNodesEGVal {
        0 {
	        if {$mergeNodeList == ""} return
	        set nmerged [ic_uns_merge_nodes $mergeNodeList "" {0 0 0} {0 0 0} $mergeNodesPropagFlag $mergeNodesForceFlag $mergeNodesForceFlag $mergeNodesAveFlag]
	    }
	    1 {
	        if {$mergeNodeList == ""} return
	        if {$tol == ""} {
		        mess "Error: No tolerance specified for merging\n" red
		        return
	        } else {
		        set nmerged [ic_uns_merge_nodes $mergeNodeList $tol {0 0 0} {0 0 0} 0 $mergeNodesTolForceFlag $mergeNodesTolForceFlag 0 $mergeNodesSingleEdgesFlag]
		        set print_mess 0
	        }
	    }
	    2 {
	        set print_mess 0
	        switch $mergeMeshGGVal {
	            0 {
		            if {$mergeMeshSurfParts == ""} {
			            mess "Warning: No surface mesh part selected for merging\n" red
			            return
		            }
		            set merge_fams ""
		            foreach part $mergeMeshSurfParts {
			            foreach f [ic_geo_list_families_in_part $part] {
			                lappend merge_fams $f
			            }
		            }
		            set fixed_fams ""
		            foreach part $mergeMeshVolParts {
			            foreach f [ic_geo_list_families_in_part $part] {
			                lappend fixed_fams $f
			            }
		            }
		            ic_merge_meshes $merge_fams $fixed_fams
		            set mergeMeshSurfParts ""
		            set mergeVolSurfParts ""
		            aie_updateMeshVis
	                return
	            }
	            1 {
	                if [ic_geo_is_loaded] {
	                    set proj 1
	                } else {
	                    set proj 0
	                }
	                if ![ic_uns_is_loaded] {
	                    mess "Mesh is not loaded.\n" red
	                    return
	                }
	                if ![ic_uns_num_couplings] {
	                    mess "This mesh has no couplings.\n" red
	                    return
	                }
	                if ![info exists resolvedb] {
	                    set resolvedb 0
	                }
	                busy 1
	                ic_uns_uncouple all $proj $resolvetypeg $resolvedb
	                busy 0
	                aie_updateMeshVis
	                return
	            }
	            default {
	                mess "Please select a criteria to merge meshes\n" red
	                return
	            }
	        }
	    }
    }

    if {($mergeNodesEGVal == "0" || $mergeNodesEGVal == "1") && $active_subsets != ""} {
        set new_elems [lindex $nmerged 3]
        if [llength $new_elems] {
            foreach sub $active_subsets {
                set types $active_subsets_types($sub)
                set parts $active_subsets_parts($sub)
                aie_mesh_subset_update_elements $sub $new_elems $types $parts "0 1 2 3"
            }
        }
    }

    if $print_mess {
        mess "[lindex $nmerged 2] merged nodes were eliminated\n"
    }
    ::AIEnv::GUIManagement::Tree::UpdateUnsMeshVisibility
    aie_updateMeshVis

if 0 {
    if {[info exists plot_window] && [winfo exists $plot_window.graph]} {
        if {[info exists histo_crit] && $histo_crit != ""} {
            aie_smooth_update_histogram $histo_crit
        }
    }
}

    if {$mergeNodeList != ""} {
        ic_uns_subset_delete $mergeNodeList
        set mergeNodeList ""
        if $auto_pick_mode {
            switch $mergeNodesEGVal {
                0 { mergeNodesPick pick }
                1 { mergeNodesPick2 pick }
            }
        }
    }
}

proc onmergeNodesPickPick {} {
    global auto_pick_mode

    if {$mergeNodeList != ""} {
        ic_uns_subset_delete $mergeNodeList
    }
}

proc onmergeNodesPickFinish {} {
    global auto_pick_mode

    if {$mergeNodeList != ""} {
        if $auto_pick_mode {
	        mergeNodesDEZ apply
	    } else {
	        aie_set_uns_subset_visible $mergeNodeList
	    }
    }
}

proc onmergeNodesPick2Finish {} {
    global auto_pick_mode

    if 0 {
	if $auto_pick_mode {
	    if {$mergeNodeList != ""} {
		mergeNodesDEZ apply
	    }
	}
    }
}

proc onmergeNodesDEZCancel {} {
    if {$mergeNodeList != ""} {
	    ic_uns_subset_delete $mergeNodeList
	    set mergeNodeList ""
    }
}

# this is executed upon loading edit elems DEZ

proc oneditElemsDEZLoad {} {
	# Load up the dde's list for this DEZ
	set elemsTypeDDEList {
		Tri
		Quad
		Tet
		Prism
		Hex
		
	}
	
	# The variable name "createdde" is specified in the resource file
	# as the name of the variable which will hold the user's selection.
	# Check to see if this variable exists.
	if { ![info exists createdde] } {
		mess "The variable createdde DOES NOT exist. Setting the\ncombo box default value to the first item.\n\n" blue
		# The variable dofs doesn't exist so this must be the very
		# first time the user loads this form.  Therefore set
		# the variable dofs to the default value
		set createdde [lindex $elemsTypeDDEList 0]
		# Make sure that the combo box now displays the proper
		# default value.  
		editElemsTypeDDE setvalue first
	} else {
		mess "The variable createdde DOES exist. Searching for the\nuser's previous choice in the list of possible choices.\n\n" blue
		# The variable dofs does exist for this dez so the user 
		# must have made a previous selection.  So, look for the
		# value in the list of choices to find it's index
		set Index [lsearch $elemsTypeDDEList $createdde]
		# set Index [lsearch $currentDOFs $createdde]
		if { $Index != -1 } {
			mess "The user's previous choice: \"$createdde\" was found at index: \"$Index\"\nSetting the default combo box value accordingly\n\n" blue
			# All we need to do is set the combo box to point
			# to the proper value.  We use the @## where ## is an integer
			# value pointing to the desired element type in the list.  The
			# values begin with 0.
			editElemsTypeDDE setvalue @$Index
			#elemsTypeDDEList setvalue @$Index
			#createElemsTypeDDE setvalue @$Index
		} else {
			mess "The user's previous choice: \"$createdde\" was not found!\nSetting default value to the first item in the list\n\n" red
			# The variable dofs does exist, but for some reason
			# doesn't point to a valid list item. This shouldn't
			# ever happen but be careful anyway
			set createdde [lindex $elemsTypeDDEList 0]
			editElemsTypeDDE setvalue first
		}
	}
 editElemsTypeDDE setvalue first

}

proc onconvertMeshTypeDEZLoad {} {
    if {$skew == ""} {
	    set skew 160
	    set warp 20
	    set improvementFlag 1
	    if [ic_geo_is_loaded] {
	        set projectFlag 1
	    } else {
	        set projectFlag 0
	    }
	    set quadrizationFlag 0
	    set tet2hextype 0
	    set aspect 0.2
    }
    if [ic_geo_is_loaded] {
        set project 1
        ::AIEnv::GUIManagement::ToggleGrey createMidSideGeom 0
    } else {
        set project 0
        ::AIEnv::GUIManagement::ToggleGrey createMidSideGeom 1
    }
    if {$deleteMidNodesFlag == ""} {set deleteMidNodesFlag 0}
    if {$proj_tol == ""} {set proj_tol 0.01}
    if {$dev == ""} {set dev 0.1666666}
    if {$ang == ""} {set ang 30.0}
    if {$chord == ""} {set chord 0.35}
    if {$midfaceNode == ""} {set midfaceNode 0}
    if {$interf == ""} {set interf 0}
    if {$keep_interfE == ""} {set keep_interfE 0}
    if {$keep_interfN == ""} {set keep_interfN 0}
    set all_to_tet_cons 1
    set deleteMidNodesMethod 0
    set createMidSideCalcVal 1
    set createMidSelectVal 0
    set deleteMidNodesElVal 0
    set deleteMidNodesNdVal 0
    set all_elem 1
    set use_active_lcs 0
    if {$quad2TriGGVal == ""} {set quad2TriGGVal 0}
    set midNodesList ""
    set midNodesIters 8
    set midNodesAcc 0.001
    
}

proc trace_create_mid_side_mid {name element op} {
    if [ic_uns_is_loaded] {
        set types [ic_uns_list_types]
        if {[lsearch $types HEXA_8] >= 0 || \
            [lsearch $types HEXA_20] >= 0 || \
            [lsearch $types QUAD_4] >= 0 || \
            [lsearch $types QUAD_8] >= 0 || \
            [lsearch $types PYRA_5] >= 0 || \
            [lsearch $types PYRA_13] >= 0 || \
            [lsearch $types PENTA_6] >= 0 || \
            [lsearch $types PENTA_15] >= 0} {
            ::AIEnv::GUIManagement::ToggleGrey createMidSideMid 0
        } else {
            ::AIEnv::GUIManagement::ToggleGrey createMidSideMid 1
        }
    }
}


proc trace_create_mid_side_geo {name element op} {
    if [convertMeshTypeDEZ get project] {
        ::AIEnv::GUIManagement::ToggleGrey createMidSideCalc 0
        if [::AIEnv::GUIManagement::GetGreyFlag createMidSideChecks] {
            ::AIEnv::GUIManagement::ToggleGrey createMidSideChecks 0
        }
        if [::AIEnv::GUIManagement::GetGreyFlag checkMidSideOptions] {
            ::AIEnv::GUIManagement::ToggleGrey checkMidSideOptions 0
        }
        if [::AIEnv::GUIManagement::GetGreyFlag autoRefineMid] {
            ::AIEnv::GUIManagement::ToggleGrey autoRefineMid 0
        }
        if ![convertMeshTypeDEZ get createMidSideCalcVal] {
            ::AIEnv::GUIManagement::ToggleGrey createMidSideCalculate 1
        }
        if ![convertMeshTypeDEZ get createMidSideCheck1Val] {
            ::AIEnv::GUIManagement::ToggleGrey createMidSideGreyDev 1
        }
        if ![convertMeshTypeDEZ get createMidSideCheck2Val] {
            ::AIEnv::GUIManagement::ToggleGrey createMidSideAng 1
        }
        if ![convertMeshTypeDEZ get createMidSideCheck3Val] {
            ::AIEnv::GUIManagement::ToggleGrey createMidSideGreyMax 1
        }
    } else {
        ::AIEnv::GUIManagement::ToggleGrey createMidSideCalc 1
        ::AIEnv::GUIManagement::ToggleGrey createMidSideChecks 1
        ::AIEnv::GUIManagement::ToggleGrey checkMidSideOptions 1
        ::AIEnv::GUIManagement::ToggleGrey autoRefineMid 1
    }
    if [convertMeshTypeDEZ get createMidSelectVal] {
        ::AIEnv::GUIManagement::ToggleGrey createMidSideSel 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey createMidSideSel 1
    }
    if [convertMeshTypeDEZ get deleteMidNodesMethod] {
        if [convertMeshTypeDEZ get deleteMidNodesNdVal] {
            ::AIEnv::GUIManagement::ToggleGrey convertNodesPick6 0
        } else {
            ::AIEnv::GUIManagement::ToggleGrey convertNodesPick6 1
        }
    } else {
        if [convertMeshTypeDEZ get deleteMidNodesElVal] {
            ::AIEnv::GUIManagement::ToggleGrey convertElemsPick6 0
        } else {
            ::AIEnv::GUIManagement::ToggleGrey convertElemsPick6 1
        }
    }
}

proc onconvertMeshTypeDEZUnLoad {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
        set elemList ""
    }
    if {$splitNodeList != ""} {
        ic_uns_subset_delete $splitNodeList
        set splitNodeList ""
    }
    foreach n "project proj_tol createMidSideCheck1Val createMidSideCheck2Val createMidSideCheck3Val" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w trace_create_mid_side_geo
        }
    }
    if {[trace vinfo midfaceNode] != ""} {
        trace vdelete midfaceNode w trace_create_mid_side_mid
    }
}

proc onconvertMeshTypeDEZAfterLoad {} {
    global ExecuteUserProcAfterLoad
    set Name "convertMeshTypeDEZ"
    set project_restored 1
    set ExecuteUserProcAfterLoad 0
    if [info exists ::AIEnv::GUIManagement::DEZ::${Name}_data] {
	    set project_restored 0
    }
    if ![ic_uns_is_loaded] {
	    msg ERROR "No mesh available"
	    convertMeshTypeDEZ hide
	    return
    }
    if [info exist convertMeshTypeGGVal] {
	    if {$convertMeshTypeGGVal == "4"} {
	        if [info exist convertSomeToSolidVal] {
		        if $convertSomeToSolidVal {
		            ::AIEnv::GUIManagement::ToggleGrey convertSomeToSolidG 0
		        } else {
		            ::AIEnv::GUIManagement::ToggleGrey convertSomeToSolidG 1
		        }
	        }
	    }
    }
    if {!$project_restored} {
	    set ExecuteUserProcAfterLoad 1
    }
    if ![info exists all2tettype]  { set all2tettype 0 }
    foreach n "project proj_tol createMidSideCheck1Val createMidSideCheck2Val createMidSideCheck3Val" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w trace_create_mid_side_geo
        }
        trace variable $n w trace_create_mid_side_geo
    }
    trace_create_mid_side_geo "" "" ""
    if {[trace vinfo midfaceNode] != ""} {
        trace vdelete midfaceNode w trace_create_mid_side_mid
    }
    trace variable midfaceNode w trace_create_mid_side_mid
    trace_create_mid_side_mid "" "" ""
}

proc onconvertMeshTypeDEZOK {} {

    set active_subsets ""; set new_elems ""
    if {$convertMeshTypeGGVal == "0" || $convertMeshTypeGGVal == "1" || $convertMeshTypeGGVal == "5" || \
        $convertMeshTypeGGVal == "6"} {
        catch { unset active_subsets_types; unset active_subsets_parts }
        foreach sub [ic_uns_subset_list_visible Selected] {
            set vis [expr [::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $sub 1] == 1]
            if !$vis continue
            lappend active_subsets $sub
            set active_subsets_types($sub) [ic_uns_subset_list_types $sub]
            set active_subsets_parts($sub) [ic_uns_subset_list_families $sub]
        }
    }
    
    switch $convertMeshTypeGGVal {
        0 {
            if {$elemList == ""} {
                set sel_map [ic_uns_create_selection_subset 0]
                ic_uns_subset_make_all $sel_map
                set elemList $sel_map
            }
            if {$improvementFlag > 2} {
                # automatic
                set maxsteps -1
            } elseif {$improvementFlag == 2} {
                # automatic, stop if less than 2 % free triangles
                set maxsteps -2
            } elseif {$improvementFlag == 1} {
                # automatic, stop if less than 20 % free triangles
                set maxsteps -20
            } else {
                set maxsteps 0
            }
            if {![ic_geo_is_loaded] && $projectFlag == "1"} {
               mess "Warning: no geometry loaded. Automatic reset of \"Surface Projection\" to \"Off\".\n" red
               set projectFlag 0
            }
            set new_elems [ic_change_tri_quad_2 $elemList $projectFlag 0 0 $maxsteps $skew $warp $quadrizationFlag]
            ic_uns_subset_delete $elemList
            set elemList ""
            mess "Done \"Tri to Quad\" conversion\n" blue
        }
	    1 {
	        switch $quad2TriGGVal {
		        0 {
		            if {$elemList == ""} return
		            set new_elems [ic_uns_change_type $elemList quad tri 0]
		            ic_uns_subset_delete $elemList
		            set elemList ""
		        } 
		        1 {
		            if {$splitNodeList == "" || [ic_uns_subset_count_nodes $splitNodeList] <= 1} {
			            msg ERROR "Too few face nodes selected to split\n"
			            return
		            }
		            ic_uns_split_hexa_into_prisms_propagete $splitNodeList
		            ic_uns_subset_delete $splitNodeList
		            set splitNodeList ""
		        }
	        }
	        mess "Done \"Quad to Tri\" conversion\n" blue
	    }
	    2 {
	        switch $tet2hextype {
		        0 {
		            if {$elemList == ""} return
		            set proj 0
		            if $tetToHexProjectChkGGVal {
			            set proj 1
		            }
		            ic_uns_change_type $elemList tetra hexa $proj 0 $normal
		            ic_uns_subset_delete $elemList
		            set elemList ""
		        }
		        1 {
		            if $tetToHexGGVal {
			            set fams $vol_parts
		            } else {
			            set fams ""
		            }
		            ic_uns_convert_to_hexas $aspect $fams $use_active_lcs
		        }
	        }
	        mess "Done \"Tet to Hex\" conversion\n" blue
	    }
	    3 {
            if {$all_to_tet_cons == ""} {set all_to_tet_cons 1}
	        switch $all2tettype {
	            0 {
	                if { $convertSomeToTetVal} {
		                if {$elemList == ""} {
		                    mess "Warning: no elements selected for \"Convert Mesh Type\"\n" red
		                    return
		                } else {
		                    ic_uns_change_type $elemList all tetra 0 $all_to_tet_cons
		                    mess "Done \"Selected elements to Tetra\" conversion\n" blue
		                }
	                } else { 
		                ic_uns_change_type all all tetra 0 $all_to_tet_cons
		                mess "Done \"All to Tetra\" conversion\n" blue
	                }
	            }
	            1 {
	                if {$elemList == ""} {
	                    mess "Warning: no elements selected for \"Convert Mesh Type\"\n" red
	                    return
	                } else {
	                    ic_uns_change_type $elemList prism tetra 0 $all_to_tet_cons
	                }
	            }
	        }
	        if {$elemList != ""} {
	            ic_uns_subset_delete $elemList
	            set elemList ""
	        }
	    }
	    4 {
	        set thickness "-1.0"
            if { $solid_thickness != "" } {
                set thickness $solid_thickness
	        }
	        if { $convertSomeToSolidVal} {
		        if {$elemListSolid == ""} {
		            mess "Warning: no elements selected for \"Shell to Solid\".\n" red
		            return
		        } else {
 		            ic_uns_change_shell_solid $elemListSolid $thickness $solid_adjust $solid_hext
 		            mess "Done \"Selected shell elements to Solid\" conversion\n" blue
		        }
	        } else { 
 		        ic_uns_change_shell_solid all $thickness $solid_adjust $solid_hext
 		        mess "Done \"Shell to Solid\" conversion\n" blue
	        }
	        if {$elemListSolid != ""} {
	       	    ic_uns_subset_delete $elemListSolid
	            set elemListSolid "" 
	        }
	    }
	    5 {
		    if !$autoRefineMidVal { set smoothRefineMidVal 0 }
    		set args " iters 10 project $project \
		    max_dev_half $dev check_max_dev_half $createMidSideCheck1Val \
           	    max_dev_nproj $ang check_max_dev_nproj $createMidSideCheck2Val \
            	max_dev_chord [expr $chord * 100.0] check_max_dev_chord $createMidSideCheck3Val \
            	check_tet10_standard $standardTetra check_tet10_strong $strongTetra \
            	check_proj 0 max_leap 3.5 midface $midfaceNode \
		        create_interf $interf refine $autoRefineMidVal \
            	smooth_refine $smoothRefineMidVal calc_projection $createMidSideCalcVal \
                calc_projection_tol $proj_tol "
    		    if $createMidSelectVal {
		            if {$elemList != ""} {
	    		        lappend args all_elem 0 name $elemList
		            } else {
	    		        mess "No elements selected\n" red
	    		        return
		            }
    		    } else {
    		        lappend args all_elem 1 name ""
    		    }
    		    mess "Start create mid side nodes...\n"
    		    eval ic_change_linear_quadratic $args
    		    mess "Done create mid side nodes.\n"
    		    if {$elemList != ""} {
	                ic_uns_subset_delete $elemList
	                set elemList ""
	            }
	    }
	    6 {
		    if {$deleteMidNodesMethod} {
		        set keep_interf $keep_interfN
		        set deleteMidNodesSel $deleteMidNodesNdVal
                set listDeleteMid $nodeListDeleteMid
		        set messageType "Nodes"
		    } else {
		        set keep_interf $keep_interfE
		        set deleteMidNodesSel $deleteMidNodesElVal
                set listDeleteMid $elemListDeleteMid
		        set messageType "Elements"
		    }
		    if {$deleteMidNodesFlag == ""} {set deleteMidNodesFlag 0}
		    if $deleteMidNodesFlag {
		        set deleteMidNodesF 1
		    } else {
		        set deleteMidNodesF 0
		    }
		    if {$deleteMidNodesSel} {
		        if {$listDeleteMid == ""} {
			        mess "Warning: no $messageType selected for \"Delete Mid Side Nodes\".\n" red
			        return
		        } else {
			        if $deleteMidNodesMethod {
			            set unsmap2 [ic_uns_subset_create]
			            set fam [lindex [ic_uns_subset_list_families $listDeleteMid] 0] 
			            ic_uns_create_element NODE $fam $listDeleteMid 0 $unsmap2 0 0 0
 			            ic_change_quadratic_linear $unsmap2 $deleteMidNodesF $keep_interf
			            ic_delete_elements subset $unsmap2 type NODE 
			            ic_uns_subset_delete $unsmap2
		            } else {
 			            ic_change_quadratic_linear $listDeleteMid $deleteMidNodesF $keep_interf
		            }
		        }
		    } else { 
 		        ic_change_quadratic_linear all $deleteMidNodesF $keep_interf
		    }
		    if {$listDeleteMid != ""} {
		        ic_uns_subset_delete $listDeleteMid
	            set listDeleteMid ""
		        if {$deleteMidNodesMethod} {
			        set nodeListDeleteMid ""
		        } else {
			        set elemListDeleteMid ""
		        }
		    }
	    }
	    7 {
            # Smooth Mid-Nodes
            if {$midNodesList == ""} {
                mess "No elements selected\n" red
                return
            }
            mess "Smoothing mid-nodes for quadratic surface elements...\n"
            ic_smooth_quad $midNodesList [ic_geo_is_loaded] -$midNodesIters -$midNodesAcc 0 4 2 0 0 0 0 "Determinant"
            mess "Done smoothing mid-nodes for quadratic surface elements\n"
            mess "Smoothing mid-nodes for quadratic volume elements...\n"
            ic_smooth_hexa $midNodesList 0 -$midNodesIters -$midNodesAcc 2 0 0 0 "Determinant"
            mess "Done smoothing mid-nodes for quadratic volume elements\n"
            set mess_done "smooth mid-nodes"
            ic_uns_subset_delete $midNodesList
            set midNodesList ""
	    }
    }
    if {($convertMeshTypeGGVal == "0" || $convertMeshTypeGGVal == "1") && $active_subsets != "" && $new_elems != ""} {
        set stop 0
        foreach n $new_elems {
            if ![string is integer $n] {
                set stop 1
                break
            }
        }
        if !$stop {
            # recreate the (deleted or new) elements in that subset(s) again
            foreach sub $active_subsets {
                set types $active_subsets_types($sub)
                set parts $active_subsets_parts($sub)
                aie_mesh_subset_update_elements $sub $new_elems $types $parts "0 1 2 3"
            }
        }
    }
    aie_updateMeshVis
}

#-----------------------------------Auto Pick procedures for Convert Mesh -----------------------------------

proc ontriToQuadLoad {} {
    if $auto_pick_mode {convertElemsPick pick}
}

proc onquadToTriLoad {} {
    if $auto_pick_mode {
	    if $quad2TriGGVal {
	        splitHexNodesPick pick
	    } else {
	        convertElemsPick2 pick
	    }
    }
}

proc ontetToHexaLoad {} {
    if $auto_pick_mode {convertElemsPick3 pick}
}

#-----------------------------------End of Auto Pick procedures for Convert Mesh -----------------------------
#----------------------------------- Procedures for AutoApply for Convert Mesh -------------------------------

proc onconvertElemsPickPick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc onconvertElemsPickFinish {} {
    if {($elemList != "") && $auto_pick_mode} {
        convertMeshTypeDEZ apply
	    convertElemsPick pick
    }
}

proc onconvertElemsPick2Pick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc onconvertElemsPick2Finish {} {
    if {($elemList != "") && $auto_pick_mode} {
  	    convertMeshTypeDEZ apply
	    convertElemsPick2 pick
    }
}

proc onconvertElemsPick3Pick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc onconvertElemsPick3Finish {} {
    if {($elemList != "") && $auto_pick_mode} {
  	    convertMeshTypeDEZ apply
	    convertElemsPick3 pick
    }
}

proc oncreateMidSideSelPick {} {
    if {$createMidSelectVal && $elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc oncreateMidSideSelFinish {} {
    if {$createMidSelectVal && ($elemList != "") && $auto_pick_mode} {
  	    convertMeshTypeDEZ apply
  	    createMidSideSel pick
    }
}

proc onconvertElemsPick6Pick {} {
    if {$deleteMidNodesElVal && $elemListDeleteMid != ""} {
        ic_uns_subset_delete $elemListDeleteMid
    }
}

proc onconvertElemsPick6Finish {} {
    if {$deleteMidNodesElVal && ($elemListDeleteMid != "") && $auto_pick_mode} {
  	    convertMeshTypeDEZ apply
  	    convertElemsPick6 pick
    }
}

proc onconvertNodesPick6Pick {} {
    if {$deleteMidNodesNdVal && $nodeListDeleteMid != ""} {
         ic_uns_subset_delete $nodeListDeleteMid
    }
}

proc onconvertNodesPick6Finish {} {
    if {$deleteMidNodesNdVal && ($nodeListDeleteMid != "") && $auto_pick_mode} {
  	    convertMeshTypeDEZ apply
  	    convertNodesPick6 pick
    }
}

proc onsplitHexNodesPickPick {} {
    if {$splitNodeList != ""} {
        ic_uns_subset_delete $splitNodeList
    }
}

proc onsplitHexNodesPickFinish {} {
    if {$auto_pick_mode && $splitNodeList != ""} {
	    convertMeshTypeDEZ apply
	    splitHexNodesPick pick
    }
}

#----------------------------------- End ofProcedures for AutoApply for Convert Mesh ------------------------
#------------------------------------------------------------------------

proc ontetToHexDEZOK {} {
    ic_uns_change_type $elemList tetra hexa $proj
    ic_uns_subset_delete $elemList
    set elemList ""
}

proc allToTet {} {
    ic_uns_change_type all all tetra 0
}

proc ontriToQuadDEZOK {} {
    set skew 160
    set warp 120
    set improvement 1

    ic_change_tri_quad skew $skew warp $warp \
	    iters $smoothSteps conver $smoothQuality improvement \
	    $improvement quadrization $quadrization
}

proc ontriToQuadDEZLoad {} {
    set smoothSteps 6
    set smoothQuality 0.25
}

#-----------------------------------Auto Pick procedures for Move Nodes -----------------------------------

proc onsplitNode2Load {} {
    if $auto_pick_mode {splitNodeScrenSel pick}
}

proc onsplitEdgeLoad {} {
    set SplitEdgeGGVal 0
    if $auto_pick_mode {splitEdgeScrenSel pick}

}

proc onswapEdgeLoad {} {
    if {$swapEdgeEGVal == 0 && $auto_pick_mode} {
	    swapEdgeScrenSel pick
    }
}

proc onSplitElemsRGLoad {} {
    if $auto_pick_mode {editElemsScrenSel pick}
}

proc onSplitIntWallLoad {} {
    if $auto_pick_mode {internalWallPick pick}
}

proc onYSplitHexasLoad {} {
    if $auto_pick_mode {ysplitHexaNodeSel pick}
}

proc onSplitPrismsLoad {} {
    global smooth

    if ![info exists smooth(n_layers)] {
	    set smooth(n_layers) "3"
    }
    if ![info exists smooth(prism_ratio)] {
        set smooth(prism_ratio) "1.5"
    }
    if ![info exists smooth(only_one)] {
	    set smooth(only_one) 0
	}
	if ![info exists smooth(layer_number)] {
	    set smooth(layer_number) 0
    }
    
    set n_layers $smooth(n_layers)
    set prism_ratio $smooth(prism_ratio)
    set layer_number $smooth(layer_number)
    if $smooth(only_one) {
	    set splitPrismSpecLayGGVal 1
	    ::AIEnv::GUIManagement::ToggleGrey splitPrismLayGroup 0
    } else {
	    set splitPrismSpecLayGGVal 0
	    ::AIEnv::GUIManagement::ToggleGrey splitPrismLayGroup 1
    }
    if {$splitPrismEGVal == ""} {
	    set splitPrismEGVal 0
    }
    if {$skip_pyras == ""} {
	    set skip_pyras 0
    }
}

#-----------------------------------End of Auto Pick procedures for Move Nodes-----------------------------
#----------------------------------- Procedures for AutoApply for Split Mesh -------------------------------

proc onsplitNodeScrenSelPick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc onsplitNodeScrenSelFinish {} {
    if {$nodeList != ""} {
        if $auto_pick_mode {
            splitMeshDEZ apply
	        splitNodeScrenSel pick
	    } else {
	        aie_set_uns_subset_visible $nodeList
	    }
    }
}

proc onsplitEdgeScrenSelPick {} {
    if {$edgeList != ""} {
        ic_uns_subset_delete $edgeList
    }
}

proc onsplitEdgeScrenSelFinish {} {
    if $SplitEdgeGGVal return
    if {$edgeList != ""} {
        if $auto_pick_mode {
  	        splitMeshDEZ apply
	        splitEdgeScrenSel pick
	    } else {
	        aie_set_uns_subset_visible $edgeList
	    }
    }
}

proc onswapEdgeScrenSelPick {} {
    if {$edgeList != ""} {
        ic_uns_subset_delete $edgeList
    }
}

proc onswapEdgeScrenSelFinish {} {
    if {$edgeList != ""} {
        if $auto_pick_mode {
  	        splitMeshDEZ apply
	        swapEdgeScrenSel pick
	    } else {
	        aie_set_uns_subset_visible $edgeList
	    }
    }
}

proc oneditElemsScrenSelPick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc oneditElemsScrenSelFinish {} {
    if {$elemList != ""} {
        if $auto_pick_mode {
  	        splitMeshDEZ apply
	        editElemsScrenSel pick
	    } else {
	        aie_set_uns_subset_visible $elemList
	    }
    }
}

proc oninternalWallPickFinish {} {
    if {($splitParts != "") && $auto_pick_mode } {
  	    splitMeshDEZ apply
    }
}

proc onysplitHexaNodeSelPick {} {
    if {$nodeList != ""} {
  	    ic_uns_subset_delete $nodeList
    }
}

proc onysplitHexaNodeSelFinish {} {
    if {$nodeList != ""} {
        if $auto_pick_mode {
  	        splitMeshDEZ apply
  	    } else {
  	        aie_set_uns_subset_visible $nodeList
  	    }
    }
}

#-----------------------------------  End ofProcedures for AutoApply for Split Mesh ------------------------

proc onsplitMeshDEZLoad {} {
    if {$swapEdgeEGVal == ""} {
        set swapEdgeEGVal 0
        set SplitEdgeGGVal 0
        set quality 0.2
        set max_deviation 0.2
        set niter 5
        set split_ratio 0.5
        set swapEdgeAutoGVal 0
        set split_propagate 0
        set split_project 1
    }
}

proc onsplitMeshDEZAfterLoad {} {
    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        splitMeshDEZ hide
        return
    }
    aie_select_split_propagate
    aie_split_mesh_non_manifold
    if {[info exists editElemsGGVal] && $editElemsGGVal == "4"} {
        onSplitIntWallsLoad
    }
}

proc onsplitMeshDEZUnLoad {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
        set nodeList ""
    }
    if {$edgeList != ""} {
        ic_uns_subset_delete $edgeList
        set edgeList ""
    }
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
        set elemList ""
    }
    internalWallPick set -key selectOptions ""
}

proc onSplitIntWallsLoad {{after 0}} {
    set only_internal [ic_uns_internal_wall_families_get]
    if {$only_internal != ""} {
        ::AIEnv::GUIManagement::ToggleGrey sp5 0
        internalWallPick set -key selectOptions "::AIEnv::DEZ::splitMeshDEZ::splitParts $only_internal"
        if $after {
            mess "[llength $only_internal] internal wall part(s)\n" blue
        } else {
            mess "Found [llength $only_internal] internal wall part(s)\n" blue
        }
    } else {
        ::AIEnv::GUIManagement::ToggleGrey sp5 1
        internalWallPick set -key selectOptions ""
    }
}

proc onselectSplitPropagate {} {

    if {([ic_uns_dimension] < 3)} {
        if $split_propagate {
            ::AIEnv::GUIManagement::ToggleGrey splitEdgeProj 1
            ::AIEnv::GUIManagement::ToggleGrey splitEdgeRatio 0
            set split_project 0
        } else {
            ::AIEnv::GUIManagement::ToggleGrey splitEdgeProj 0
            ::AIEnv::GUIManagement::ToggleGrey splitEdgeRatio 1
        }
        if $split_project {
            ::AIEnv::GUIManagement::ToggleGrey splitEdgeRatio 1
            set split_project 0
        } else {
            if $split_propagate {
                ::AIEnv::GUIManagement::ToggleGrey splitEdgeRatio 0
            }
        }  
    } else {
        ::AIEnv::GUIManagement::ToggleGrey splitEdgeProj 0
        ::AIEnv::GUIManagement::ToggleGrey splitEdgeRatio 0
    }
}

proc aie_select_split_propagate {} {
    splitMeshDEZ onselectSplitPropagate
}

proc aie_split_mesh_non_manifold {} {
    if [splitMeshDEZ get opt5] {
        splitNodeScrenSel set -key selectOptions "replace_previous"
    } else {
        splitNodeScrenSel set -key selectOptions ""
    }
}

proc onsplitMeshDEZOK {} {

    if {$editElemsGGVal == 0} {
	    if {![info exists nodeList] || $nodeList == ""} {
	        mess "Error: No nodes selected.\n" red
	        return
	    }
	    set sel_map $nodeList
	    ic_uns_subset_configure $sel_map -visible 1
	    set fam_active [array names fam_visible]
	    if {$opt5 == 1} {
	        if {[ic_uns_subset_count_nodes $nodeList] > 1} {
		        msg WARNING "Only single node split supported for Non-manifold option."
		        ic_uns_subset_delete $nodeList
		        set nodeList ""
		        return
	        }
	        set adj [ic_uns_subset_create "" 1]
	        ic_uns_add_near_node $adj $sel_map
	        ic_uns_update_family_type $adj __same__ "1d 2d" restrict_to
	        ic_uns_subset_visible visible 0
	        set move_map [select_unstruct element 0 $adj "" "elements to go with the moved node"]
	        ic_uns_subset_delete $adj
	        ic_uns_subset_visible visible 1
	        if {$move_map != ""} {
		        if {[ic_count_elements TETRA_4] > 0} {
		            set na [ic_uns_add_adjacent_tetras $move_map $sel_map]
		            if {![lindex $na 0] || ([lindex $na 0] == [lindex $na 1])} {
			            set mess "[lindex $na 0] out of [lindex $na 1] tetras will be moved with the node.  Continue?"
				        switch -- [tk_dialog .nonmanmove "Non-manifold" $mess "" -1 Yes No] {
				            1 - -1 { 
				                if [winfo exists .nonmanmove] { top_destroy .nonmanmove }
			                    ic_uns_subset_delete $move_map
			                    ic_uns_subset_delete $sel_map
			                    return
			                }
		                }
		            }
		            ic_uns_subset_visible $move_map 1
		            ic_uns_split_node_non_man $sel_map $move_map
		            select_move_uns_map $sel_map 0 0 "" $fam_active
		            ic_uns_subset_visible $move_map 0
	            }
	        } else {
	            select_move_uns_map $sel_map 1 0 "" $fam_active
	        }
        }
        mess "Done \"Split Nodes\"\n" blue
    }
    
    if {$editElemsGGVal == 1} {
	    switch $SplitEdgeGGVal {
	        0 {
		        if {$edgeList == ""} {
		            mess "Error: No mesh edges selected\n" red
		            return
		        }
		        set sel_map $edgeList
		        if {$split_propagate == 0} {
		            set any_probl [ic_uns_split_edges $sel_map $split_propagate $split_project 1]
		            if {$any_probl} {
			            switch -- [ tk_dialog .split_warn "Warning" "Split will make the mesh inconsistent.\n  Do you wish to Continue." "" -1 Yes No ] {
			                -1 { if [winfo exists .split_warn] { top_destroy .split_warn; return } }
			                0 {}
			                1 { return }
			            }
		            }
		            if  $split_project {
			            set nsurfs [llength [ic_geo_get_objects surface]]
			            if {$nsurfs > 1000 && (![ic_geo_root_surface_built])} {
			                set msg "Warning: Surface search needs to be initialized once; projection may take a long time"
			                mess "$msg\n" red
			            }
		            }
		            ic_uns_split_edges $sel_map $split_propagate $split_project
		        } else {
		            ic_uns_split_edges_propagate $sel_map $split_ratio
		        }
		        if [ic_hex_blocking_loaded] {
		            hex_command "update_ref_uns_mesh"
		            hex_update_display mesh
		        }
		        set edgeList ""
	        }
	        1 {
		        set mess [ic_uns_split_double_wall all]
		        regsub -all \{ $mess "" mess; regsub -all \} $mess "" mess
		        mess "$mess" blue
	        }
	        2 {
		        ic_uns_split_spanning_edges all
 	            set edgeList ""
	        }
	        3 {
		        ic_uns_split_spanning_edges visible "boundary_too"
		        set edgeList ""
		        
	        }
	    }
	    mess "Done \"Split Edges\"\n" blue
    }

    if {$editElemsGGVal == 2} {
	    switch $swapEdgeEGVal {	   
	        0 {	
		        if {$edgeList == ""} {
		            mess "Error: No mesh edges selected\n" red
		            return
		        }
		        set sel_map $edgeList
		        set try_harder 0
		        set n [ic_uns_swap_edges $sel_map $try_harder]
		        if $n {
		            mess "$n edges could not be swapped\n"
		        }
	        }
	        1 {
		        set sel_map ""
		        mess "Swapping edges ...\n"
		        set threshold $quality
		        if $swapEdgeAutoGVal {	   
		            set max_dev $max_deviation
		            set threshold "0.01"
		        } else {
		            set max_dev "-1.0"
		        }
		        ic_uns_swap_edges_auto all $threshold $niter $max_dev
		        mess "Done \"Swap Edges\"\n" blue
	        }
	    }
    }

    if {$editElemsGGVal == 3} {
	    if {![info exists elemList] || $elemList == ""} {
	        mess "Error: No elements selected.\n" red
	        return
	    }
	    set sel_map $elemList
	    ic_uns_split_elements $sel_map
	    mess "Done \"Split Tri Elements\"\n" blue
    }

    if {$editElemsGGVal == 4} {
	    if {$splitParts == ""} {
	        msg ERROR "No parts selected for Internal wall"
	        return 
	    }
	    set split_p ""
	    foreach p $splitParts {
	        if ![::AIEnv::GUIManagement::Tree::GroupExists part ${p}_BACK] {
	            append split_p "${p}_BACK "
	        }
	        ::AIEnv::GUIManagement::Tree::NewPart ${p}_BACK
	    }
	    if $volume {
	        if ![::AIEnv::GUIManagement::Tree::GroupExists part THERMAL_SHELL] {
	            append split_p "THERMAL_SHELL"
	        }
	        ::AIEnv::GUIManagement::Tree::NewPart THERMAL_SHELL
	        ic_uns_split_internal_faces all $splitParts _BACK 0 THERMAL_SHELL
	    } else {
	        ic_uns_split_internal_faces all $splitParts _BACK 0
	    }
        if {$split_p != ""} {
            mess "New parts created: $split_p\n"
        }
	    ::AIEnv::GUIManagement::Tree::RefreshPartVisibility
	    set splitParts ""
	    mess "Done \"Split Internal Wall\"\n" blue
	    onSplitIntWallsLoad 1
	    return
    }

    if {$editElemsGGVal == 5} {
        if {![info exists nodeList] || $nodeList == "" || ![ic_uns_subset_exists $nodeList]} {
            mess "Error: No vertex selected\n" red
            return
        }
	    ic_uns_ysplit_hexas_at_vertex $nodeList
	    ic_uns_subset_delete $nodeList
	    set nodeList ""
	    mess "Done \"Y-Split Hexas At Vertex\"\n" blue
    }

    if {$editElemsGGVal == 6} {
        global smooth

	    set smooth(n_layers) $n_layers
	    set smooth(prism_ratio) $prism_ratio
	    if [ic_uns_isimmutable all] {
	        if {$split_prism_parts != ""} {
	            set sub1 [ic_uns_create_selection_subset 0]
	            ic_uns_subset_visible $sub1 0
	            ic_uns_subset_make_families $sub1 $split_prism_parts
                ic_uns_uniqify $sub1
                set isimmutable [ic_uns_isimmutable $sub1]
	            if $isimmutable {
	                set immutable [ic_uns_get_immutable_elements $sub1]
                    mess "[llength $immutable] locked elements are present in the mesh, please unlock them before using \"Split Prism\"\n" red
                }
                ic_uns_subset_delete $sub1
                if $isimmutable return
            } else {
                mess "Locked elements are present in the mesh, please unlock them before using \"Split Prism\"\n" red
                return
            }
	    }
	    set cmd "ic_uns_split_prisms all $smooth(n_layers) $smooth(prism_ratio)"
	    if $splitPrismSpecLayGGVal {
	        set smooth(only_one) 1
	        set smooth(layer_number) $layer_number
	        set laynum $smooth(layer_number)
	        lappend cmd $laynum
	    } else {
	        set smooth(only_one) 0
	        lappend cmd ""
	    }
	    if $splitPrismEGVal {
	        lappend cmd $prism_height
	    } else {
	        lappend cmd ""
	    }
	    lappend cmd "$split_prism_parts"
	    if {$split_surface_parts == ""} {
	        mess "No selected prism surface part\n"
	        mess "All prism surface parts will be used\n"
	    }
	    lappend cmd "$split_surface_parts"
        if {$skip_pyras == "1"} {
            lappend cmd "skip_pyras"
        }
        eval $cmd
	    busy reset
	    mess "Done \"Split Prisms\"\n" blue
    } else {
	    if {[info exists sel_map] && [ic_uns_subset_exists $sel_map]} {
	        aie_reset_icons_subset $sel_map
	        ic_uns_subset_delete $sel_map
	    }
    }
}

proc onsmoothDEZLoad {} {
    global env

    smoothDEZ setdirty
    if {$quality == ""} {
	    set qualityDDList {
	        "Quality"
	        "Aspect ratio"
	        "Custom quality"
	        "Determinant"
	        "Min angle"
	        "Max orthogls"
	        "Max warp"
	        "Max warpgls"
	        "Skew"
	    }

	    set iters 5
	    set quality 0.20
	    set violateTol 0.1
	    set violateGGVal 0
	    set minEdgeLen 5
	    set minEdgeGGVal 0
	    set PrePointFlag 0
	    set SFitFlag 0
	    set prismWarpRatio 0.5
	    set NoCollapseFlag 1
	    set HexGroupFlag 1
	    set resSf 0.5
	    set resVl 0.05
        if ![info exists advLaplacGGVal] {
            set advLaplacGGVal 0
        }
        if ![info exists LaplacCriterion] {
            set LaplacCriterion 0
        }
        if ![info exists advLaplacResSfGGVal] {
            set advLaplacResSfGGVal 0
        }
        if ![info exists advLaplacResVlGGVal] {
            set advLaplacResVlGGVal 0
        }
        if {![info exists env(AI_ENV_CFD_ONLY)] || !$env(AI_ENV_CFD_ONLY)} {
	        chooseQualityDDE setvalue @0
        } else {
	        chooseQualityDDE setvalue @1
	    }
	    set smoothMethod 0
    }
    
    # some options need to be greyed based off hex mesh vs. other mesh...
    set types [ic_uns_subset_list_types all]
    set has_hex 0
    set has_prism 0
    foreach t $types {
	    if {[string range $t 0 3] == "HEXA"} {set has_hex 1 }
	    if {[string range $t 0 4] == "PENTA"} {set has_prism 1 }
    }
    if $has_hex {
	    ::AIEnv::GUIManagement::ToggleGrey noGrouping 0
	    ::AIEnv::GUIManagement::ToggleGrey IgnorePPointChk 0
	    ::AIEnv::GUIManagement::ToggleGrey SfitChk 0
    } else {
	    ::AIEnv::GUIManagement::ToggleGrey noGrouping 1
	    ::AIEnv::GUIManagement::ToggleGrey IgnorePPointChk 1
	    ::AIEnv::GUIManagement::ToggleGrey SfitChk 1
    }
    if $has_prism {
	    ::AIEnv::GUIManagement::ToggleGrey PrismWarpValue 0
    } else {
	    ::AIEnv::GUIManagement::ToggleGrey PrismWarpValue 1
    }
}

proc onsmoothDEZAfterLoad {} {
    global fam_visible smooth

    if ![ic_uns_is_loaded] {
	    msg ERROR "No mesh available"
	    smoothDEZ hide
	    return
    }
    set etypes [ic_uns_list_types]
    set types ""
    foreach et $etypes {
	    if {(![regexp NODE $et]) && (![regexp LINE $et]) && (![regexp BAR $et])} {
	        lappend types $et
	    }
    }
    if {(![info exists smoothTypes]) || ([join $types] != $smoothTypes)} {
        smoothMeshMS clear
	    smoothMeshMS set -key "rowLabel" $types
	    smoothMeshMS set -key "columnLabel" [list "Smooth" "Freeze" "Float"]
	    smoothMeshMS set -key "title" "Smooth Mesh Type"
	    smoothMeshMS set -key "rowExclusive" 1
        smoothMeshMS build
        set smoothTypes [join $types]
	    foreach row $types {
            smoothMeshMS select $row Smooth
        }
    }
    
    aie_smooth_clear_histogram
    ic_uns_subset_create smooth_do_map 0
    ic_uns_subset_create smooth_show_map 1 "" 0
    ic_uns_subset_configure smooth_do_map -list_type 1
    ic_uns_subset_configure smooth_show_map -shade flat_wire -color white -dont_change_color_or_shade 1

    set types ""
    foreach row $smoothTypes {
	    if [smoothMeshMS query $row Smooth] {
	        lappend types $row
	    }
    }
    set fams ""

    if {[trace vinfo qualitydde] != ""} {
	    trace vdelete qualitydde w trace_qualitydde_default_values
    }
    trace variable qualitydde w trace_qualitydde_default_values

    if {[trace vinfo advLaplacGGVal] != ""} {
	    trace vdelete advLaplacGGVal w trace_advLaplacGGVal_group
    }
    trace variable advLaplacGGVal w trace_advLaplacGGVal_group
    if {[trace vinfo advLaplacResSfGGVal] != ""} {
	    trace vdelete advLaplacResSfGGVal w trace_advLaplacGGVal_group
    }
    trace variable advLaplacResSfGGVal w trace_advLaplacGGVal_group
    if {[trace vinfo advLaplacResVlGGVal] != ""} {
	    trace vdelete advLaplacResVlGGVal w trace_advLaplacGGVal_group
    }
    trace variable advLaplacResVlGGVal w trace_advLaplacGGVal_group
     
    switch $smoothMethod {
	    0 {
	        foreach f [ic_uns_list_families] { lappend fams $f }
	        set smooth(families) $fams
	        ic_uns_update_family_type smooth_do_map $fams $types update 1
	    }
	    1 {
	        foreach f [array names fam_visible] {
		        if {$f == "VORFN" || $f == "ORFN"} {continue}
		        if $fam_visible($f) {
		            lappend fams $f
		        } else {
		            lappend fix_fams $f
		        }
	        }
	        set smooth(families) $fams
	        ic_uns_update_family_type smooth_do_map $fams $types update 1
	    }
	    2 {
	        ic_uns_subset_delete smooth_do_map
	        ic_uns_subset_create smooth_do_map 0
	        foreach vismap [ic_uns_subset_list_visible] {
		        if {$vismap != "Selected"} {
		            ic_uns_subset_add_from smooth_do_map $vismap
		        }
	        }
	    }
        3 {
	        ic_uns_subset_delete smooth_do_map
	        ic_uns_subset_create smooth_do_map 0
	        foreach vismap [ic_uns_subset_list_visible] {
		        if {$vismap != "Selected"} {
		            ic_uns_subset_add_from smooth_do_map $vismap
		        }
	        }
            set fams ""
            set subset_parts [ic_uns_subset_list_families smooth_do_map]
            foreach f [array names fam_visible] {
                if {$f == "VORFN" || $f == "ORFN"} {continue}
		        if {$fam_visible($f) || (([lsearch $subset_parts $f] >= 0) && ([lsearch $fams $f] < 0))} {
                    lappend fams $f
                }
            }
	        set smooth(families) $fams
            ic_uns_update_family_type smooth_do_map $fams $types update 1
        }
    }

    set smooth(histogram) smooth
    set smooth(eval) 0
    
    if ![aie_histo_warn_too_many_elements] {
        aie_smooth_update_histogram $qualitydde
    }
    trace_advLaplacGGVal_group "" "" ""
    ::AIEnv::GUIManagement::ToggleGrey smoothRefreshHisto 0
}

foreach ll {SmoothMeshDEZMALL SmoothMeshDEZMVP SmoothMeshDEZMVS smoothMeshDEZACT} {
    proc on$ll\Load {} {
        smoothDEZ smooth_update_selection_subset
    }
}

proc trace_qualitydde_default_values {name element op} {
    set qualitydde [smoothDEZ get qualitydde]
    switch $qualitydde {
    	Quality - "Custom quality" - Determinant {
    	    smoothDEZ set quality 0.2
    	}
	    "Aspect ratio" {
	        smoothDEZ set quality 0.1
	    }
	    "Min angle" {
	        smoothDEZ set quality 14.0
	    }
	    "Max warp" {
	        smoothDEZ set quality 10.0
	    }
	    "Max warpgls" {
	        smoothDEZ set quality 10.0
	    }
	    "Max orthogls" {
	        smoothDEZ set quality 0.2
	    }
	    Skew {
	        smoothDEZ set quality 0.2
	    }
    }
}

proc trace_advLaplacGGVal_group {name element op} {
    if {[smoothDEZ get advLaplacGGVal] == "1"} {
        ::AIEnv::GUIManagement::ToggleGrey advLaplacG 0
        if {[smoothDEZ get advLaplacResSfGGVal] == "1"} {
            ::AIEnv::GUIManagement::ToggleGrey advLaplacResSf 0
        } else {
            ::AIEnv::GUIManagement::ToggleGrey advLaplacResSf 1
        }
        if {[smoothDEZ get advLaplacResVlGGVal] == "1"} {
            ::AIEnv::GUIManagement::ToggleGrey advLaplacResVl 0
        } else {
            ::AIEnv::GUIManagement::ToggleGrey advLaplacResVl 1
        }
    } else {
        ::AIEnv::GUIManagement::ToggleGrey advLaplacG 1
        ::AIEnv::GUIManagement::ToggleGrey advLaplacResSf 1
        ::AIEnv::GUIManagement::ToggleGrey advLaplacResVl 1
    }
}

proc smooth_update_selection_subset {} {
    global smooth_do_map fam_visible smooth

    aie_smooth_clear_histogram
    ic_uns_subset_create smooth_do_map 0
    ic_uns_subset_create smooth_show_map 1 "" 0
    ic_uns_subset_configure smooth_do_map -list_type 1
    ic_uns_subset_configure smooth_show_map -shade flat_wire -color white -dont_change_color_or_shade 1

    set types ""
    foreach row $smoothTypes {
        if [smoothMeshMS query $row Smooth] {
            lappend types $row
        }
    }
    
    set fams ""
    switch $smoothMethod {
        0 {
            foreach f [ic_uns_list_families] { lappend fams $f }
            set smooth(families) $fams
            ic_uns_update_family_type smooth_do_map $fams $types update 1
        }
        1 {
            foreach f [array names fam_visible] {
                if {$f == "VORFN" || $f == "ORFN"} continue
                if $fam_visible($f) { lappend fams $f }
            }
            set smooth(families) $fams
            ic_uns_update_family_type smooth_do_map $fams $types update 1
        }
        2 {
            ic_uns_subset_delete smooth_do_map
            ic_uns_subset_create smooth_do_map 0
            foreach vismap [ic_uns_subset_list_visible Selected] {
                if {$vismap != ""} {
                    ic_uns_subset_add_from smooth_do_map $vismap
                }
            }
        }
        3 {
            ic_uns_subset_delete smooth_do_map
            ic_uns_subset_create smooth_do_map 0
            set added 0
            foreach vismap [ic_uns_subset_list_visible Selected] {
                if {$vismap != ""} {
                    ic_uns_subset_add_from smooth_do_map $vismap
                    set added 1
                    
                }
            }
            if $added {
                set subset_fams [ic_uns_subset_list_families smooth_do_map]
                foreach f [array names fam_visible] {
                    if !$fam_visible($f) continue
                    if {$f == "VORFN" || $f == "ORFN"} continue
		            if {$fam_visible($f) || (([lsearch $subset_fams $f] >= 0) && ([lsearch $fams $f] < 0))} {
                        lappend fams $f
                    }
                }
            } else {
                foreach f [array names fam_visible] {
                    if {$f == "VORFN" || $f == "ORFN"} continue
                    if $fam_visible($f) { lappend fams $f }
                }
            }
            set smooth(families) $fams
            ic_uns_update_family_type smooth_do_map $fams $types update 1
        }
    }
    set smooth(histogram) smooth
    set smooth(eval) 0
    aie_smooth_update_histogram $qualitydde

}

proc onChooseQualityDDEModify {dez val} {
    global histo_minv histo_maxv

    set histo_minv ""
    set histo_maxv ""
    aie_smooth_update_histogram $val
}

proc smoothRefreshHistogram {} {
    smoothDEZ smooth_update_selection_subset
    ::AIEnv::GUIManagement::ToggleGrey smoothRefreshHisto 0
}

proc aie_refresh_histogram {} {
    global histo_title histo_minv histo_maxv beta_mode
    global histo_ylim histo_nbars histo_status plot_window
    
    set q [qualityMetricsDEZ get qualdiag]
    set title [lindex [ic_diagnostic_info] $q]
    if {$title == "Mesh Distribution"} {
        mess "No histogram available for \"Mesh Distribution\"\n"
        return
    }
    if {![info exists histo_title] || $histo_title == ""} return
    foreach n [lsort -dictionary [array names histo_status]] {
        set histo_status($n) 0
    }
    eval aie_smooth_update_histogram \"$title\" $histo_nbars $histo_minv $histo_maxv $histo_ylim \"\"
    aie_redraw_histogram
    histo_highlight $plot_window 1 smooth_show_elements {}
    ::AIEnv::GUIManagement::ToggleGrey smoothRefreshQHisto 0
}

proc trace_smooth_update_histogram {name element op} {
    global smooth histo_minv histo_maxv

    set types ""
    foreach row [smoothMeshMS get -key rowLabel] {
	    if [smoothMeshMS query $row Smooth] {
	        lappend types $row
	    }
    }

    set only_visible [smoothDEZ get onlyVisible]
    if !$only_visible {
	    ic_uns_update_family_type smooth_do_map $smooth(families) $types update 1
    } else {
	    ic_uns_subset_delete smooth_do_map
	    ic_uns_subset_create smooth_do_map 0
	    foreach vismap [ic_uns_subset_list_visible Selected] {
	        if {$vismap != ""} {
		        ic_uns_subset_add_from smooth_do_map $vismap
	        }
	    }
    }

    aie_delete_histogram
    set histo_minv ""
    set histo_maxv ""
    set smooth(histogram) smooth
    set smooth(eval) 0
    aie_smooth_update_histogram  [smoothDEZ get qualitydde]
    if {[aie_active_dez] == "qualityMetricsDEZ"} {
        ::AIEnv::GUIManagement::ToggleGrey smoothRefreshQHisto 0
    }
    if {[aie_active_dez] == "smoothDEZ"} {
        ::AIEnv::GUIManagement::ToggleGrey smoothRefreshHisto 0
    }
}

proc onsmoothDEZOK {} {
    global smooth unstruct_diag smoothTypes
    global fam_visible smooth options

    if {$qualitydde == "Qualitygls"} { set qualitydde "Quality"}

    smoothDEZ setdirty
    set smooth(prism_warp_weight) $prismWarpRatio
    set smooth(iters) $iters
    set smooth(max_val) $quality
    set smooth(violate_tol) $violateTol
    set smooth(min_edge_len) $minEdgeLen

    set types ""
    foreach row $smoothTypes {
	    if [smoothMeshMS query $row Smooth] {
	        lappend types $row
	    }
    }

    set cmd ""
    set fams ""
    set fix_fams ""
    catch { unset changed_parts }
    
    switch $smoothMethod {
	    0 {
	        foreach f [ic_uns_list_families] { lappend fams $f }
	        set smooth(families) $fams
	        ic_uns_update_family_type smooth_do_map $fams $types update 1
	    }
	    1 {
	        foreach f [array names fam_visible] {
		        if {$f == "VORFN" || $f == "ORFN"} {continue}
		            if $fam_visible($f) {
		                lappend fams $f
		        } else {
		                lappend fix_fams $f
		        }
	        }
	        set smooth(families) $fams
	        ic_uns_update_family_type smooth_do_map $fams $types update 1
	    }
	    2 {
	        ic_uns_subset_delete smooth_do_map
	        ic_uns_subset_create smooth_do_map 0
	        foreach vismap [ic_uns_subset_list_visible Selected] {
		        if {$vismap != ""} {
		            ic_uns_subset_add_from smooth_do_map $vismap
		        }
	        }
	    }
	    3 {
	        ic_uns_subset_delete smooth_do_map
	        ic_uns_subset_create smooth_do_map 0
            foreach f [array names fam_visible] {
                if {$f == "VORFN" || $f == "ORFN"} {continue}
		        if $fam_visible($f) {
		            lappend fams $f
		        } else {
		            lappend fix_fams $f
		        }
	        }
            set added 0
	        foreach vismap [ic_uns_subset_list_visible Selected] {
                if {$vismap != "" && [::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $vismap] == "1"} {
		            ic_uns_subset_add_from smooth_do_map $vismap
		            set added 1
		        }
	        }
            if $added {
                set change_elems ""
                set subset_parts [ic_uns_subset_list_families smooth_do_map]
                foreach f $fix_fams {
                    if {[lsearch $subset_parts $f] >= 0} {
                        lappend change_elems $f
                    }
                }
                ic_undo_suspend
                foreach p $change_elems {
                    ic_uns_subset_move_part_elements smooth_do_map $p ${p}_TMP_PART
                    lappend fams ${p}_TMP_PART
                    lappend changed_parts $p ${p}_TMP_PART
                }
                ic_undo_resume
            }
            set smooth(families) $fams
            ic_uns_update_family_type smooth_do_map $fams $types update 1
	    }
    }

    lappend cmd map smooth_do_map
    lappend cmd upto $smooth(max_val)
    lappend cmd iterations $smooth(iters)
    lappend cmd prism_warp_weight $smooth(prism_warp_weight)
    lappend cmd fix_families $fix_fams

    switch $qualitydde {
	    AspectRatio { set smooth(criterion) "Aspect ratio" }
	    MaxWarp { set smooth(criterion) "Max warp"}
	    default { set smooth(criterion) $qualitydde }
    }
    set unstruct_diag(which) $smooth(criterion)
    lappend cmd metric $unstruct_diag(which)

    mess "Smoothing [ic_uns_subset_count_elements smooth_do_map] elements, $smooth(iters) iterations, up to $smooth(max_val) ...\n"

    foreach col { Smooth Freeze Float } {
	    foreach row $smoothTypes {
	        set val [smoothMeshMS query $row $col]
	        if $val {
		        lappend cmd [string tolower $col] $row
	        }
	    }
    }

    if $advLaplacGGVal {
	    set lapl_crit 1
	    if {$LaplacCriterion == "edge"} {
	        set lapl_crit 2
	    }
	    lappend cmd laplace $lapl_crit
	    if $advLaplacResSfGGVal {
	        if {$resSf < 0.0} {
	            set resSf 0.0
	            msg Warning "\"Residual on Surfaces\" below 0. Reset to 0.0\n"
	        }
	        if {$resSf > 1.0} {
	            set resSf 1.0
	            msg Warning "\"Residual on Surfaces\" above 1. Reset to 1.0\n"
	        }
	        lappend cmd residual_sf $resSf
	    }
	    if $advLaplacResVlGGVal {
	        if {$resVl < 0.0} {
	            set resVl 0.0
	            msg Warning "\"Residual in Volume\" below 0. Reset to 0.0\n"
	        }
	        if {$resVl > 1.0} {
	            set resVl 1.0
	            msg Warning "\"Residual in Volume\" above 1. Reset to 1.0\n"
	        }
	        lappend cmd residual_vl $resVl
	    }
    }
    if $AllElFlag {
	    lappend cmd all_elements 1
    }
    if !$NoCollapseFlag {
	    lappend cmd no_collapse 1
    }
    if $RefineFlag {
	    lappend cmd refine 1
    }
    if $violateGGVal {
	    if {$smooth(violate_tol) == ""} {
	        msg ERROR "No tolerance specified for violate geometry"
	        return
	    }
	    if {$relative_tol == 1} {
	        set smooth(violate_tol) [expr $smooth(violate_tol) * -1.0]
	    }
	    lappend cmd violate_geometry $smooth(violate_tol)
    }
    if $minEdgeGGVal {
	    if {$smooth(min_edge_len) == ""} {
	        msg ERROR "No value specified for \"Min. edge\" length"
	        return
	    }
	    lappend cmd min_edge_len $smooth(min_edge_len)
    }
    if !$HexGroupFlag {
	    lappend cmd group_bad_elem 0
    }
    if $PrePointFlag {
	    lappend cmd ignore_pp 1
    }
    if $SFitFlag {
	    lappend cmd sfit 1
    }
    set n_processors 1
    if {[info exists options(n_processors)] && $options(n_processors) != ""} {
        set n_processors $options(n_processors)
    }
    lappend cmd n_processors $n_processors
    with_view_inactive {
	    eval ic_smooth_elements $cmd
    }
    if [info exists changed_parts] {
        ic_undo_suspend
        foreach "p1 p2" $changed_parts {
            ic_uns_subset_move_part_elements smooth_do_map $p2 $p1
            if [ic_uns_check_family $p2] {
                if [ic_uns_count_in_families $p2] {
                    ic_uns_move_family_elements $p2 $p1
                }
                ic_uns_delete_family $p2
                if {[ic_geo_family_is_empty $p2] && [info exists fam_visible($p2)]} {
                    unset fam_visible($p2)
                }
            }
        }
        ic_undo_resume
        unset changed_parts
    }

    if $violateGGVal {
	    if {$relative_tol == 1} {
	        set smooth(violate_tol) [expr $smooth(violate_tol) * -1.0]
	    }
    }

    set smooth(histogram) smooth
    set smooth(eval) 0
    aie_smooth_update_histogram $qualitydde
    ::AIEnv::GUIManagement::ToggleGrey smoothRefreshHisto 0
}

proc onsmoothDEZUnLoad {} {
    global plot_window

    if {[trace vinfo qualitydde] != ""} {
        trace vdelete qualitydde w trace_qualitydde_default_values
    }
    if {[trace vinfo advLaplacGGVal] != ""} {
	    trace vdelete advLaplacGGVal w trace_advLaplacGGVal_group
    }
    if {[trace vinfo advLaplacResSfGGVal] != ""} {
	    trace vdelete advLaplacResSfGGVal w trace_advLaplacGGVal_group
    }
    if {[trace vinfo advLaplacResVlGGVal] != ""} {
	    trace vdelete advLaplacResVlGGVal w trace_advLaplacGGVal_group
    }
    if {[ic_uns_subset_exists smooth_do_map] && ([info exists plot_window] && ![winfo exists $plot_window])} {
        ic_uns_subset_delete smooth_do_map
    }
}

proc onsmoothSOEDEZLoad {} {
    global env test_smooth

    set itersSurf 10
    set itersVol 5
    set alphaSurf 0.5
    set alphaVol 0.5
    set critAvrChaSurf 0.001
    set critAvrChaVol 0.001
    set expansionSurf 0.0
    set expansionVol 0.0
    set stabilizeSurf 1.0
    set stabilizeVol 2.0
    set useorthoDistSurf 0
    set useorthoDistVol 0
    set fixGeoFlag 0
    set niterPost 3
    set limitPost 0.2
    set edgesOptions2SOEVal 0
    set numLayersFix 0
    set firstLayersDist -1
    set fixLayers 0
    set partFixList ""
    set partFirstList ""
    set partBorderList ""
    set edgeRebunchList ""
    set SrfFitFlag 1
    set UpdDispFlag 0
    set KperGeomFlag 1
    set activePartsOnlyFlag 0
    set rebunchEdges 1
    set treatUnstruct 2
    set fixVolOrient 0
    set fix_layers_settings ""
    set layer_distance_settings ""

    smoothSOEDEZ setdirty
    set AllowActiveReload 1
    if ![info exists env(AI_ENV_ALPHA)] {
        set smoTypeEGVal 1
        set smoothTypeSOESTFaVal 0
        set smoothTypeSOESTVlVal 0
    }
}

proc onsmoothSOEDEZAfterLoad {} {
    global test_smooth smooth env beta_mode

    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        smoothSOEDEZ hide
        return
    }

    set hexa_ele 0
    set quad_ele 0
    set volume_ele 0
    set surface_ele 0
    set types [ic_uns_list_types]
    if {[lsearch $types HEXA_8] >= 0 || \
        [lsearch $types HEXA_20] >= 0 || \
        [lsearch $types HEXA_27] >= 0} {
        set hexa_ele 1
        set volume_ele 1
    }
     if {[lsearch $types QUAD_4] >= 0 || \
        [lsearch $types QUAD_4_X] >= 0 || \
        [lsearch $types QUAD_8] >= 0 || \
        [lsearch $types QUAD_8_X] >= 0 || \
        [lsearch $types QUAD_9] >= 0} {
        set quad_ele 1
        set surface_ele 1
    }
    if !$surface_ele {
        if {[lsearch $types TRI_3] >= 0 || \
            [lsearch $types TRI_3_X] >= 0 || \
            [lsearch $types TRI_6] >= 0 || \
            [lsearch $types TRI_6_X] >= 0} {
            set surface_ele 1
        }
    }
    if !$volume_ele {
        if {[lsearch $types TETRA_4] >= 0 || \
            [lsearch $types TETRA_10] >= 0 || \
            [lsearch $types PENTA_6] >= 0 || \
            [lsearch $types PENTA_15] >= 0 || \
            [lsearch $types PENTA_18] >= 0 || \
            [lsearch $types PYRA_5] >= 0 || \
            [lsearch $types PYRA_13] >= 0 || \
            [lsearch $types PYRA_14] >= 0} {
            set volume_ele 1
        }
    }

    if {$surface_ele && !$quad_ele} {
        mess "There are no quad elements in the mesh, using Laplace for surface elements.\n"
    }

    if {$volume_ele && !$hexa_ele} {
        mess "There are no hexa elements in the mesh, using Laplace for volume elements.\n"
    }
    aie_rebunch_edge_active 0
    if ![info exists env(AI_ENV_ALPHA)] {
        if {([info exists smoothTypeSOESTFaVal] && [info exists smoothTypeSOESTVlVal])} {
            if {$surface_ele && !$quad_ele} {
                 smoothSOEDEZ set smoothTypeSOESTFaVal 1
            }
            if {$volume_ele && !$hexa_ele} {
                 smoothSOEDEZ set smoothTypeSOESTVlVal 1
            }
        }
        foreach n "smoothTypeSOESTFaVal smoothTypeSOESTVlVal" {
            if {[trace vinfo $n] != ""} {
                trace vdelete $n w aie_trace_smoothType
            }
            trace variable $n w aie_trace_smoothType
        }
        aie_trace_smoothType
    }
    
    aie_treat_unstruct_active 0
    set freezeCriterion 1
   
    if {[trace vinfo partFixList] != ""} {
        trace vdelete partFixList w aie_trace_partFixList
    }
    trace variable partFixList w aie_trace_partFixList
    if {[trace vinfo partFirstList] != ""} {
        trace vdelete partFirstList w aie_trace_partFirstList
    }
    trace variable partFirstList w aie_trace_partFirstList
    # 500 should be enough time to get the DEZ settings from the project file and to set the test_smooth array
    after 500 {
        catch { unset test_smooth }
        set test1 [smoothSOEDEZ get fix_layers_settings]
        set test2 [smoothSOEDEZ get layer_distance_settings]
        if {$test1 != ""} {
            foreach item $test1 {
                set var [lindex $item 0]
                set val [lindex $item 1]
                set test_smooth($var) $val
            }
        }
        if {$test2 != ""} {
            foreach item $test2 {
                set var [lindex $item 0]
                set val [lindex $item 1]
                set test_smooth($var) $val
            }
        }
    }
  
    aie_smooth_clear_histogram
    ic_uns_subset_create smooth_do_map 0
    ic_uns_subset_create smooth_show_map 1 "" 0
    ic_uns_subset_configure smooth_do_map -list_type 1
    ic_uns_subset_configure smooth_show_map -shade flat_wire -color white -dont_change_color_or_shade 1
    
    switch $activePartsOnlyFlag {
	    0 {
	        foreach f [ic_uns_list_families] { lappend fams $f }
	            ic_uns_update_family_type smooth_do_map $fams $types update 1
	    }
	    1 {
	        foreach f [array names fam_visible] {
		        if {$f == "VORFN" || $f == "ORFN"} continue
		        if $fam_visible($f) { lappend fams $f }
	        }
	        ic_uns_update_family_type smooth_do_map $fams $types update 1
	    }
	}
    set smooth(histogram) smooth
    set smooth(eval) 0
	set smooth(criterion) Quality
	if ![aie_histo_warn_too_many_elements] {
	    aie_smooth_update_histogram Quality
	}
}

proc smooth_update_hexahedral_subset {} {
    global smooth_do_map fam_visible smooth

    aie_smooth_clear_histogram
    ic_uns_subset_create smooth_do_map 0
    ic_uns_subset_create smooth_show_map 1 "" 0
    ic_uns_subset_configure smooth_do_map -list_type 1
    ic_uns_subset_configure smooth_show_map -shade flat_wire -color white -dont_change_color_or_shade 1
    
    set fams ""
    set types [ic_uns_list_types]
    switch $activePartsOnlyFlag {
        0 {
            foreach f [ic_uns_list_families] { lappend fams $f }
            ic_uns_update_family_type smooth_do_map $fams $types update 1
        }
        1 {
            foreach f [array names fam_visible] {
                if {$f == "VORFN" || $f == "ORFN"} continue
                if $fam_visible($f) { lappend fams $f }
            }
            ic_uns_update_family_type smooth_do_map $fams $types update 1
        }
    }
    set smooth(histogram) smooth
    set smooth(eval) 0
    set smooth(criterion) Quality
    aie_smooth_update_histogram Quality
}

proc onsmoothSOEDEZUnLoad {} {
    global beta_mode
    if {[trace vinfo partFixList] != ""} {
        trace vdelete partFixList w aie_trace_partFixList
    }
    if {[trace vinfo partFirstList] != ""} {
        trace vdelete partFirstList w aie_trace_partFirstList
    }
    foreach n "smoothTypeSOESTFaVal smoothTypeSOESTVlVal" {
        if {[trace vinfo $n] != ""} {
            trace vdelete $n w aie_trace_smoothType
        }
    }
}

proc aie_trace_partFixList {{name ""} {element ""} {op ""}} {
    global test_smooth
    if {[smoothSOEDEZ get partFixList] == ""} {
        foreach item [array names test_smooth freeze_surfaces,*] {
            unset test_smooth($item)
        }
        foreach item [array names test_smooth fams_attr,1,*] { 
            unset test_smooth($item)
        }
        smoothSOEDEZ set fix_layers_settings ""
    }
}

proc aie_trace_partFirstList {{name ""} {element ""} {op ""}} {
    global test_smooth
    if {[smoothSOEDEZ get partFirstList] == ""} {
        foreach item [array names test_smooth release_ortho,*] {
            unset test_smooth($item)
        }
        foreach item [array names test_smooth fams_attr,0,*] { 
            unset test_smooth($item)
        }
        smoothSOEDEZ set layer_distance_settings ""
    }
}

proc aie_trace_smoothType {{name ""} {element ""} {op ""}} {
    if {[smoothSOEDEZ get smoothTypeSOESTFaVal] > 0 || [smoothSOEDEZ get smoothTypeSOESTVlVal] > 0} {
        ::AIEnv::GUIManagement::ToggleGrey firstLayerOptionsSOEEll2 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey firstLayerOptionsSOEEll2 0
    }
}

proc ai_global_scale_alphaSurf {num {dez ""}} {}
proc ai_global_scale_alphaVol {num {dez ""}} {}
proc ai_global_scale_critAvrChaSurf {num {dez ""}} {}
proc ai_global_scale_critAvrChaVol {num {dez ""}} {}

proc aie_rebunch_edge_active {{rebunch empty}} {
    if {$rebunch != "empty"} { set rebunchEdges $rebunch }
    if [info exists smoTypeEGVal] {
        switch $smoTypeEGVal {
            0 {
                if {$rebunchEdges != 2} {
                    ::AIEnv::GUIManagement::ToggleGrey selectEdges2SOEGra 1
                } else {
                    ::AIEnv::GUIManagement::ToggleGrey selectEdges2SOEGra 0
                }
            }
            1 {
                if {$rebunchEdges != 2} {
                    ::AIEnv::GUIManagement::ToggleGrey selectEdges2SOEEll 1
                } else {
                    ::AIEnv::GUIManagement::ToggleGrey selectEdges2SOEEll 0
                }
            }
        }
    } else {
        if {$rebunchEdges != 2} {
            ::AIEnv::GUIManagement::ToggleGrey selectEdges2SOEEll 1
        } else {
            ::AIEnv::GUIManagement::ToggleGrey selectEdges2SOEEll 0
        }
    }
}

proc aie_treat_unstruct_active {{treat empty}} {
    if {$treat != "empty" && [string is integer -strict $treat]} { set treatUnstruct $treat }
}

proc onsmoothSOEDEZOK {} {
    global smooth unstruct_diag fam_visible test_smooth env 

    set test_smooth(iter_sf) $itersSurf
    set test_smooth(iter_vl) $itersVol
    if {[info exists env(AI_ENV_ALPHA)] && [info exists env(AI_ENV_BETA)]} {
        set test_smooth(alpha_sf) $alphaSurf
        set test_smooth(alpha_vl) $alphaVol
        set test_smooth(crit_avr_cha_sf) $critAvrChaSurf
        set test_smooth(crit_avr_cha_vl) $critAvrChaVol
        set test_smooth(upddisp) $UpdDispFlag
    }
    set test_smooth(exprate_sf) $expansionSurf
    set test_smooth(exprate_vl) $expansionVol
    set test_smooth(stabilize_sf) $stabilizeSurf
    set test_smooth(stabilize_vl) $stabilizeVol
    set test_smooth(ortho_distance_sf) $useorthoDistSurf
    set test_smooth(ortho_distance_vl) $useorthoDistVol
    set test_smooth(sfit) $SrfFitFlag
    set test_smooth(kpg) $KperGeomFlag
    set test_smooth(niter_post) $niterPost
    set test_smooth(limit_post) $limitPost

    set types_orthogonality ""
    set types_elliptical ""
    set types_str_sor_lapl ""
    set types_str_sor_thm ""
    set types_str_hlg_lapl ""
    set types_str_hlg_thm ""

    switch $smoothTypeSOESTFaVal  {
	    0 { lappend types_orthogonality "Surface" }
	    1 { lappend types_elliptical "Surface" }
	    2 {
		    switch $smoothTypeSOESTFaStrMtVal  {
		        0 { lappend types_str_sor_lapl "Surface" }
		        1 { lappend types_str_sor_thm "Surface" }
		        2 { lappend types_str_hlg_lapl "Surface" }
		        3 { lappend types_str_hlg_thm "Surface" }
	    	    default { lappend types_orthogonality "Surface" }
		    }
	    }
	    default { lappend types_orthogonality "Surface" }
	}
	switch $smoothTypeSOESTVlVal  {
	    0 { lappend types_orthogonality "Volume" }
	    1 { lappend types_elliptical "Volume" }
	    2 {
		    switch $smoothTypeSOESTVlStrMtVal  {
		        0 { lappend types_str_sor_lapl "Volume" }
		        1 { lappend types_str_sor_thm "Volume" }
		        2 { lappend types_str_hlg_lapl "Volume" }
		        3 { lappend types_str_hlg_thm "Volume" }
	    	    default { lappend types_orthogonality "Volume" }
		    }
	    }
	    default { lappend types_orthogonality "Volume" }
	}
	
    foreach item $types_orthogonality {
        if {$item == "Surface"} {
          set stype_sf 2
        }
        if {$item == "Volume"} {
          set stype_vl 2
        }
    }
    foreach item $types_elliptical {
        if {$item == "Surface"} {
          set stype_sf 3
        }
        if {$item == "Volume"} {
          set stype_vl 3
        }
    }
    foreach item $types_str_sor_lapl {
        if {$item == "Surface"} {
          set stype_sf 5
        }
        if {$item == "Volume"} {
          set stype_vl 5
        }
    }
    foreach item $types_str_sor_thm {
        if {$item == "Surface"} {
          set stype_sf 6
        }
        if {$item == "Volume"} {
          set stype_vl 6
        }
    }
    foreach item $types_str_hlg_lapl {
        if {$item == "Surface"} {
          set stype_sf 7
        }
        if {$item == "Volume"} {
          set stype_vl 7
        }
    }
    foreach item $types_str_hlg_thm {
        if {$item == "Surface"} {
          set stype_sf 8
        }
        if {$item == "Volume"} {
          set stype_vl 8
        }
    }
    set test_smooth(stype) [expr {$stype_sf + 100 * $stype_vl}]

    set test_smooth(fix) $fixGeoFlag
    if {$rebunchEdges == 1} {
        set test_smooth(rebunch_edges) 1
    } else {
        set test_smooth(rebunch_edges) 0
    }
    set test_smooth(n_fix_layer) $numLayersFix
    set test_smooth(family_edges) $partBorderList
    set test_smooth(treat_unstruct) $treatUnstruct
    if {$partFirstList != "" && $partFixList != ""} {
        set start 0
        set end 1
    } elseif {$partFirstList != ""} {
        set start 0
        set end 0
        foreach item [array names test_smooth fams_attr,1,*] { unset test_smooth($item) }
        foreach item [array names test_smooth freeze_surfaces,*] { unset test_smooth($item) }
    } elseif {$partFixList != ""} {
        set start 1
        set end 1
        foreach item [array names test_smooth fams_attr,0,*] { unset test_smooth($item) }
        foreach item [array names test_smooth release_ortho,*] { unset test_smooth($item) }
    } else {
        set start -1
        set end -1
        foreach item [array names test_smooth fams_attr,*] { unset test_smooth($item) }
        foreach item [array names test_smooth release_ortho,*] { unset test_smooth($item) }
        foreach item [array names test_smooth freeze_surfaces,*] { unset test_smooth($item) }
    }

    set test_smooth(fams_attr) ""

    if {$start != -1 && $end != -1} {
        foreach item $fix_layers_settings {
            set var [lindex $item 0]
            set val [lindex $item 1]
            set test_smooth($var) $val
        }
        foreach item $layer_distance_settings {
            set var [lindex $item 0]
            set val [lindex $item 1]
            set test_smooth($var) $val
        }
        for {set i $start} {$i <= $end} {incr i} {
            foreach item [array names test_smooth fams_attr,$i,*] {
                set part [lindex [split $item ,] 2]
                set val $test_smooth(fams_attr,$i,$part)
                if {$i == "1"} {
                    if {$freezeCriterion != 1 && $freezeCriterion != 2} continue
                    set idx_srf freeze_surfaces
                    if {[lsearch $partFixList $part] < 0}  continue
                } else {
                    set idx_srf release_ortho
                    if {[lsearch $partFirstList $part] < 0} continue
                }
                if !$test_smooth($idx_srf,$part) {
                    set val 0
                } else {
                    if { $val <= 0 } {
                        set val -1
                    }
                }
                append test_smooth(fams_attr) "$part $i $val "
            }
        }
    }

    if {$freezeCriterion == 0} {
        if {$test_smooth(n_fix_layer) < 0} {
            set test_smooth(n_fix_layer) -1
        }
    } elseif {$freezeCriterion == 1 || $freezeCriterion == 2} {
        set test_smooth(n_fix_layer) -1
    }

    set fams ""
    if $activePartsOnlyFlag {
        foreach f [array names fam_visible] {
            if $fam_visible($f) { append fams "$f " }
        }
    } else {
        set fams all
    }
    set uni_pairs ""
    if {$edgeRebunchList != "" && ($rebunchEdges == 2)} {
        set the_nodes ""
        set node_map $edgeRebunchList
        foreach e [ic_uns_subset_list_elements $node_map] {
            if {[lindex $e 0]== "VERTEX"} {
                lappend the_nodes [lindex $e 1]
            }
        }
        set uni_pairs [unstruct_uniquify_pairs $the_nodes]
    }
    if $fixVolOrient {
        set uns_diag_fix [ic_uns_create_diagnostic_subset]
        ic_uns_create_diagnostic_edgelist 1
        ic_uns_diagnostic subset all diag_type vol_orient fix_fam FIX_VOL_ORIENT disp_subset $uns_diag_fix diag_verb {Volume orientations} fams {}
        ic_uns_fix_volume_orientation $uns_diag_fix
        ic_uns_subset_delete $uns_diag_fix
        ic_uns_create_diagnostic_edgelist 0
    }
    
    set grad_smooth 0
    if [info exists smoTypeEGVal] {
	    if { $smoTypeEGVal == "0" } {
	        if {($test_smooth(iter_sf) > 0 && $test_smooth(alpha_sf) >= 0) || \
		        ($test_smooth(iter_vl) > 0 && $test_smooth(alpha_vl) >= 0)} {
		        set grad_smooth 1
	        }
	    }
    }

    if !$grad_smooth {
	    set sub1 [ic_uns_create_selection_subset 0]
	    ic_uns_subset_visible $sub1 0
	    ic_uns_subset_make_families $sub1 $fams
        ic_uns_uniqify $sub1
        set isimmutable [ic_uns_isimmutable $sub1]
	    if $isimmutable {
	        set immutable [ic_uns_get_immutable_elements $sub1]
            mess "[llength $immutable] locked elements are present in mesh, they will not be moved\n" red
        }
        ic_uns_subset_delete $sub1
    }
    
    if {$grad_smooth && [info exists env(AI_ENV_ALPHA)] && [info exists env(AI_ENV_BETA)]} {
	    ic_unstruct_grad_smooth $test_smooth(iter_sf) \
	        $test_smooth(iter_vl) $test_smooth(alpha_sf) $test_smooth(alpha_vl) \
	        $test_smooth(crit_avr_cha_sf) $test_smooth(crit_avr_cha_vl) \
	        $test_smooth(n_fix_layer) $test_smooth(sfit) \
	        $test_smooth(fams_attr) \
	        $test_smooth(rebunch_edges) $test_smooth(family_edges) $uni_pairs \
	        $fams $test_smooth(upddisp)
    } else {
        ic_unstruct_elliptical_smooth $test_smooth(iter_sf) \
           $test_smooth(iter_vl) $test_smooth(exprate_sf) \
           $test_smooth(exprate_vl) $test_smooth(stabilize_sf) \
           $test_smooth(stabilize_vl) $test_smooth(ortho_distance_sf) \
           $test_smooth(ortho_distance_vl) $test_smooth(stype) \
           $test_smooth(fix) $test_smooth(n_fix_layer) \
           $test_smooth(fams_attr) $test_smooth(rebunch_edges) \
           $test_smooth(sfit) $test_smooth(family_edges) \
           $uni_pairs $fams $test_smooth(treat_unstruct) $test_smooth(kpg) \
	       $test_smooth(niter_post) $test_smooth(limit_post)
    }
    smoothSOEDEZ setdirty
    aie_smooth_update_histogram Quality "" 0 1
}

proc onfreezeLayersSOESelGraFinish {{attr ""}} {
    global test_smooth
    
    if {$attr == ""} {
        set attr [onsmoothSOESetSelectedParts fix_layers]
    }
    set attr2 ""
    if {$attr != ""} {
        set list [smoothSOEDEZ get partFixList]
        set attr2 ""
        foreach item $attr {
            set var [lindex $item 0]
            set what [lindex [split $var ,] 0]
            if {$what == "freeze_surfaces"} {
                set part [lindex [split $var ,] 1]
            } elseif {$what == "fams_attr"} {
                set part [lindex [split $var ,] 2]
            } else {
                continue
            }
            if {[lsearch $list $part] < 0} continue
            lappend attr2 $item
        }
    }
    set attr $attr2
    if {$attr != ""} {
        foreach item [array names test_smooth freeze_surfaces,*] {
            unset test_smooth($item)
        }
        foreach item [array names test_smooth fams_attr,1,*] { 
            unset test_smooth($item)
        }        
        foreach item $attr {
            set var [lindex $item 0]
            set val [lindex $item 1]
            set test_smooth($var) $val
        }
        smoothSOEDEZ set fix_layers_settings $attr
    }
}

proc onfirstLayerSOESelEllFinish {{attr ""}} {
    global test_smooth

    if {$attr == ""} {
        set attr [onsmoothSOESetSelectedParts layer_distance]
    }
    set attr2 ""
    if {$attr != ""} {
        set list [smoothSOEDEZ get partFirstList]
        set attr2 ""
        foreach item $attr {
            set var [lindex $item 0]
            set what [lindex [split $var ,] 0]
            if {$what == "release_ortho"} {
                set part [lindex [split $var ,] 1]
            } elseif {$what == "fams_attr"} {
                set part [lindex [split $var ,] 2]
            } else {
                continue
            }
            if {[lsearch $list $part] < 0} continue
            lappend attr2 $item
        }
    }
    set attr $attr2
    if {$attr != ""} {
        foreach item [array names test_smooth release_ortho,*] {
            unset test_smooth($item)
        }
        foreach item [array names test_smooth fams_attr,0,*] { 
            unset test_smooth($item)
        }
        foreach item $attr {
            set var [lindex $item 0]
            set val [lindex $item 1]
            set test_smooth($var) $val
        }
        smoothSOEDEZ set layer_distance_settings $attr
    }
}

proc onfreezeLayersSOESelGra2Finish {{attr ""}} {
    global test_smooth
    
    if {$attr == ""} {
        set attr [onsmoothSOESetSelectedParts fix_layers]
    }
    set attr2 ""
    if {$attr != ""} {
        set list [smoothSOEDEZ get partFixList]
        set attr2 ""
        foreach item $attr {
            set var [lindex $item 0]
            set what [lindex [split $var ,] 0]
            if {$what == "freeze_surfaces"} {
                set part [lindex [split $var ,] 1]
            } elseif {$what == "fams_attr"} {
                set part [lindex [split $var ,] 2]
            } else {
                continue
            }
            if {[lsearch $list $part] < 0} continue
            lappend attr2 $item
        }
    }
    set attr $attr2
    if {$attr != ""} {
        foreach item [array names test_smooth freeze_surfaces,*] {
            unset test_smooth($item)
        }
        foreach item [array names test_smooth fams_attr,1,*] { 
            unset test_smooth($item)
        }        
        foreach item $attr {
            set var [lindex $item 0]
            set val [lindex $item 1]
            set test_smooth($var) $val
        }
        smoothSOEDEZ set fix_layers_settings $attr
    }
}

proc onfirstLayerSOESelEll2Finish {{attr ""}} {
    global test_smooth

    if {$attr == ""} {
        set attr [onsmoothSOESetSelectedParts layer_distance]
    }
    set attr2 ""
    if {$attr != ""} {
        set list [smoothSOEDEZ get partFirstList]
        set attr2 ""
        foreach item $attr {
            set var [lindex $item 0]
            set what [lindex [split $var ,] 0]
            if {$what == "release_ortho"} {
                set part [lindex [split $var ,] 1]
            } elseif {$what == "fams_attr"} {
                set part [lindex [split $var ,] 2]
            } else {
                continue
            }
            if {[lsearch $list $part] < 0} continue
            lappend attr2 $item
        }
    }
    set attr $attr2
    if {$attr != ""} {
        foreach item [array names test_smooth release_ortho,*] {
            unset test_smooth($item)
        }
        foreach item [array names test_smooth fams_attr,0,*] { 
            unset test_smooth($item)
        }
        foreach item $attr {
            set var [lindex $item 0]
            set val [lindex $item 1]
            set test_smooth($var) $val
        }
        smoothSOEDEZ set layer_distance_settings $attr
    }
}

proc onsmoothSOESetSelectedParts {what {reset 0}} {
    global test_smooth fams_attr_local

    if [winfo exists .test_smooth_set_part] { form_delete .test_smooth_set_part }
    set buttons {
      {accept}
      {dismiss}
    }
    if {$what == "layer_distance"} {
      set partFirstList [smoothSOEDEZ get partFirstList]
      if {$partFirstList == ""} {
          mess "No part(s) selected.\n"
          return ""
      }
      set default_value -1
      set type_attr 0
      set type float
      set idx_srf release_ortho
      set text_srf "Release orthogonality"
      set text_win "Release orthogonality/Initial Height"
      set list $partFirstList
    } else {
      set partFixList [smoothSOEDEZ get partFixList]
      if {$partFixList == ""} {
          mess "No part(s) selected.\n"
          return ""
      }
      set default_value 0
      set type_attr 1
      set type int
      set idx_srf freeze_surfaces
      set text_srf "Freeze surface boundary"
      set text_win "Freeze surface boundary + n layers"
      set list $partFixList
    }
    set w [form_init .test_smooth_set_part "$text_win by part(s)" "" $buttons]
    set i 0
    if {$w != ""} {
        foreach item $list {
	        form_label $w.name$i "$item" "$i 0"; $w.name$i configure -relief ridge
	        if ![info exists test_smooth($idx_srf,$item)] {
	            set test_smooth($idx_srf,$item) 0
	        }
            if {$what == "fix_layers"} {
	            form_checkbutton $w.part$i "$text_srf" fams_attr_local($idx_srf,$item) "$i 1" "" \
	                "aie_configure_smooth_parts_form $w.part$i $w.value$i $type_attr $w.layers$i" "nonbool"
            } else {
	            form_checkbutton $w.part$i "$text_srf" fams_attr_local($idx_srf,$item) "$i 1" "" \
	                "aie_configure_smooth_parts_form $w.part$i $w.value$i $type_attr" "nonbool"
            }
	        $w.part$i configure -onvalue 0 -offvalue 1
	        if {![info exists test_smooth(fams_attr,$type_attr,$item)] || $test_smooth(fams_attr,$type_attr,$item) == ""} {
	            set test_smooth(fams_attr,$type_attr,$item) $default_value
	        }
	        set filter "fams_attr_local($idx_srf,$item) $test_smooth(fams_attr,$type_attr,$item)"
	        set fams_attr_local($type_attr,$item) $test_smooth(fams_attr,$type_attr,$item)
	        form_entry $w.value$i fams_attr_local($type_attr,$item) $type "$i 2" $filter
            if {$what == "fix_layers"} {
	            form_label $w.layers$i "Layers" "$i 4"
	            aie_configure_smooth_parts_form $w.part$i $w.value$i $type_attr $w.layers$i
            } else {
	            aie_configure_smooth_parts_form $w.part$i $w.value$i $type_attr
            }
	        incr i
	    }
	    form_finish +200+200
    }
    if [form_wait .test_smooth_set_part] {
        foreach item $list {
            set test_smooth($idx_srf,$item) $fams_attr_local($idx_srf,$item)
            if {$fams_attr_local($idx_srf,$item) == "1"} {
                set test_smooth(fams_attr,$type_attr,$item) $fams_attr_local($type_attr,$item)
            } else {
                set test_smooth(fams_attr,$type_attr,$item) $default_value
            }
        }
        set the_part_list1 ""
        foreach item [array names test_smooth $idx_srf,*] {
            lappend the_part_list1 "$item $test_smooth($item)"
        }
        set the_part_list2 ""
        foreach item [array names test_smooth fams_attr,$type_attr,*] {
            lappend the_part_list2 "$item $test_smooth($item)"
        }
        if $reset {
            if {$what == "layer_distance"} {
                onfirstLayerSOESelEllFinish "$the_part_list1 $the_part_list2"
            } elseif {$what == "fix_layers"} {
                onfreezeLayersSOESelGraFinish "$the_part_list1 $the_part_list2"
            }
        } else {
            return "$the_part_list1 $the_part_list2"
        }
    } else {
        return ""
    }
}

proc aie_configure_smooth_parts_form {w1 w2 type {w3 ""}} {
     global fams_attr_local
     set on [$w1 cget -variable]
     if ![set $on] {
         if {$type == 0} {
             $w1 configure -text "Release orthogonality"
         } elseif {$type == 1} {
             $w1 configure -text "Surface boundary"
             if {$w3 != ""} {
                 $w3 configure -text "      "
             }
         }
         $w2 configure -state disabled
         $w2 configure -foreground gray
     } else {
         if {$type == 0} {
             $w1 configure -text "Initial Height"
         } elseif {$type == 1} {
             $w1 configure -text "Surface boundary + "
             if {$w3 != ""} {
                 $w3 configure -text "Layers"
             }
         }
         $w2 configure -state normal
         $w2 configure -foreground black
     }
}

proc onqualityMetricsDEZLoad {} {
    if {![info exists distributionList] || $distributionList == ""} {
        set distributionList {Volume "Avg Edgelen" "Min Edgelen" "Max Edgelen"}
        set distributionType Volume
    }
}

proc onqualityMetricsDEZAfterLoad {} {
    global fam_visible beta_mode options 
    
    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        qualityMetricsDEZ hide
        return
    }

    set etypes [ic_uns_list_types]
    set types ""
    foreach et $etypes {
	# Requires for unattached line/bar elemenent
	    if ![regexp NODE $et] {
	        lappend types $et
	    }
    }
    if {(![info exists diagTypes]) || ([join $types] != $diagTypes)} {
        diagMeshMS clear
	    diagMeshMS set -key "rowLabel" $types
	    diagMeshMS set -key "columnLabel" [list "Yes" "No"]
	    diagMeshMS set -key "title" "Mesh types to check"
	    diagMeshMS set -key "rowExclusive" 1
        diagMeshMS build
        set diagTypes [join $types]
	    foreach row $types {
	        if {([regexp LINE $row]) || ([regexp BAR $row])} {
		        diagMeshMS select $row No
	        } else {
		        diagMeshMS select $row Yes
	        }
        }
    }

    if {$checkElems == ""} {
	    set checkElems all
    }
    
    aie_smooth_clear_histogram
    ic_uns_subset_create smooth_do_map 0
    ic_uns_subset_create smooth_show_map 1 "" 0
    ic_uns_subset_configure smooth_do_map -list_type 1
    ic_uns_subset_configure smooth_show_map -shade flat_wire -color white -dont_change_color_or_shade 1
    set fams ""
    if {$checkElems == "active" || $checkElems == "visible"} {
	    foreach f [array names fam_visible] {
	        if $fam_visible($f) { lappend fams $f }
	    }
    } elseif {$checkElems == "all"} {
	    foreach f [ic_uns_list_families] { lappend fams $f }
    }

    set types ""
    foreach row $diagTypes {
	    if [diagMeshMS query $row Yes] {
	        lappend types $row
	    }
    }
    if {$checkElems == "all" || $checkElems == "active"} {
	    ic_uns_update_family_type smooth_do_map $fams $types update 1
    } elseif {$checkElems == "visible"} {
	    ic_uns_subset_delete smooth_do_map
	    ic_uns_subset_create smooth_do_map 0
	    foreach vismap [ic_uns_subset_list_visible] {
	        ic_uns_subset_add_from smooth_do_map $vismap
	    }
    } elseif {$checkElems == "visible_subsets"} {
	    ic_uns_subset_delete smooth_do_map
	    ic_uns_subset_create smooth_do_map 0
	    foreach vismap [ic_uns_subset_list_visible "Selected"] {
            if {[::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $vismap] == "1"} {
                ic_uns_subset_add_from smooth_do_map $vismap
            }
	    }
    }
    if ![info exists qualdiag] return
    set diag [lindex [ic_diagnostic_info] $qualdiag]
    if {$diag == "Mesh Distribution"} {
        mess "No histogram available for \"Mesh Distribution\"\n"
        return
    }
    if {$diag != "Mesh expansion factor"} {
        aie_smooth_clear_histogram
        set smooth(histogram) diag
        set evalDiag 0
        if [info exists options(evaluate_diagnostic)] {
            set evalDiag $options(evaluate_diagnostic)
        }
        set smooth(eval) $evalDiag
        mess "Updating quality type criterion \"$diag\"...\n"
        aie_smooth_update_histogram $diag
    } else {
        qualityMetricsDEZ setdirty
    }
    ::AIEnv::GUIManagement::ToggleGrey smoothRefreshQHisto 0
}


proc onqualityMetricsDEZOK {} {
    global custom_metric_keys custom_metric tdv_default
    global diagTypes fam_visible beta_mode options disp_options

    if ![info exists qualdiag] {
        msg ERROR "No criterion selected for quality metrics"
        return
    }
    set diag [lindex [ic_diagnostic_info] $qualdiag]
    if {$diag == "Custom quality"} {
        foreach k $custom_metric_keys {
	        if [info exists custom_metric($k,name)] {
	            set custom_metric($k,active) [set qual${k}GGVal]
	            foreach t {quad tri} {
		            foreach v {acc_min des_min id des_max acc_max} {
		                set custom_metric($k,$t,$v) [set ${t}_${k}_${v}]
                    }
		        }
	        }
	    }
        unstruct_diag_custom_metric_set $diag
    }
    if {$diag == "Mesh Distribution"} {
        if {[llength $ptStart] != 3 || [llength $ptEnd] != 3} {
            msg ERROR "Need to select start and end points"
        } else {
            aie_smooth_clear_histogram
            aie_mesh_distribution $ptStart $ptEnd $distributionType
        }
        return
    }
    # work-a-round for colors to be updated -- jka
    if [info exists tdv_default] {
        $tdv_default redraw
    }
    set fams ""
    if {$checkElems == "active" || $checkElems == "visible"} {
	    foreach f [array names fam_visible] {
	        if $fam_visible($f) { lappend fams $f }
	    }
    } elseif {$checkElems == "all"} {
	    foreach f [ic_uns_list_families] { lappend fams $f }
    }
    set types ""
    foreach row $diagTypes {
	    if [diagMeshMS query $row Yes] {
	        lappend types $row
	    }
    }
    aie_smooth_clear_histogram
    ic_uns_subset_create smooth_do_map 0
    ic_uns_subset_configure smooth_do_map -list_type 1
    set all_vismaps ""
    if {$checkElems == "all" || $checkElems == "active"} {
	    ic_uns_update_family_type smooth_do_map $fams $types update 1
	    if {$checkElems == "all" && $disp_options(uns_color_by_quality)} {
	        foreach vismap [ic_uns_subset_list_visible "Selected"] {
	            if {$vismap == ""} continue
	            if {[::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $vismap] == "1"} {
	                lappend all_vismaps $vismap
	            }
	        }
	    }
    } elseif {$checkElems == "visible"} {
	    ic_uns_subset_delete smooth_do_map
	    ic_uns_subset_create smooth_do_map 0
	    foreach vismap [ic_uns_subset_list_visible] {
	        if {$vismap == ""} continue
	        ic_uns_subset_add_from smooth_do_map $vismap
	        if !$disp_options(uns_color_by_quality) continue
	        if {[::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $vismap] == "1"} {
                lappend all_vismaps $vismap
	        }
	    }
    } elseif {$checkElems == "visible_subsets"} {
	    ic_uns_subset_delete smooth_do_map
	    ic_uns_subset_create smooth_do_map 0
	    foreach vismap [ic_uns_subset_list_visible "Selected"] {
	        if {$vismap == ""} continue
            if {[::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $vismap] == "1"} {
                ic_uns_subset_add_from smooth_do_map $vismap
                if !$disp_options(uns_color_by_quality) continue
                lappend all_vismaps $vismap
            }
	    }
    }
    set evalDiag 0
    if [info exists options(evaluate_diagnostic)] {
        set evalDiag $options(evaluate_diagnostic)
    }
    set smooth(histogram) diag
    set smooth(eval) $evalDiag

    foreach vismap $all_vismaps {
        # refresh the active subset(s), maybe the criterion changed
        ic_uns_subset_visible $vismap 1
    }
    mess "Updating quality type criterion \"$diag\"...\n"
    aie_smooth_update_histogram $diag
    ::AIEnv::GUIManagement::ToggleGrey smoothRefreshQHisto 0
}

foreach idiag {diagQuality diagQuality43 diagDeterminant diagAspectratio diagMidnode \
	       diagMidnodeAngle diagTetra diagMaxWarp diagMaxWarpgls diagSkew diagTGridSkew \
	       diagOrientation diagMaxortho diagMaxorthogls diagMinortho diagTaper \
	       diagMaxdihedralangle diagSurfacedev diagQuadev diagMaxangle \
	       diagMinangle diagMaxlength diagMaxside diagMinside diagMaxratio \
	       diagXsize diagYsize diagZsize diagVolume diagVolumeChange \
	       diagSurface diagDistortion diagOppFaceArea diagDistortion diagOppFaceArea \
	       diagOppFacePar diagPrismTh diagElementStr diagEqSkew \
	       diagTacAspR diagTacDist diagVolumeAreaLength MshExpansionFactor \
	       maxSectorVolume minSectorVolume diagWorkbenchShape diagOrthogonalQuality} {
    proc on${idiag}Load {} {
	    global histo_minv histo_maxv 
	    set diag [lindex [ic_diagnostic_info] $qualdiag]
	    set histo_minv ""
	    set histo_maxv ""
    }
}

proc ondiagCustomLoad {} {
    global custom_metric_keys env have_set_defaults

    busy 1
    mess "Please wait: computing custom quality defaults...\n" blue
    # First set form based off custom_metric settings
    foreach k $custom_metric_keys {
	if [info exists custom_metric($k,active)] {
	    set qual${k}GGVal $custom_metric($k,active)
	}
	foreach t {quad tri} {
	    foreach v {acc_min des_min id des_max acc_max} {
		if [info exists custom_metric($k,$t,$v)] {
		    set ${t}_${k}_${v} $custom_metric($k,$t,$v)
		}
	    }
	}
    }
    # Assume nothing reasonable has been set for min edge and deviation, so compute these.
    if ![info exists have_set_defaults] {
	set ave_edge_len [ic_uns_subset_average_edge_length All]
	if {([string is double $ave_edge_len] || [string is integer $ave_edge_len]) && \
		(0 < $ave_edge_len)} {
	    set quad_minside_acc_min [expr $ave_edge_len *  .70]
	    set quad_minside_des_min [expr $ave_edge_len *  .85]
	    set quad_minside_des_max [expr $ave_edge_len * 1.15]
	    set quad_minside_acc_max [expr $ave_edge_len * 1.30]
	    set tri_minside_acc_min $quad_minside_acc_min
	    set tri_minside_des_min $quad_minside_des_min
	    set tri_minside_des_max $quad_minside_des_max
	    set tri_minside_acc_max $quad_minside_acc_max
	}
	set ave_surf_dev [ic_uns_subset_average_surface_deviation All]
	if {([string is double $ave_surf_dev] || [string is integer $ave_surf_dev]) && \
		(0 < $ave_surf_dev)} {
	    set quad_surfdev_acc_min 0
	    set quad_surfdev_des_min 0
	    set quad_surfdev_des_max [expr $ave_surf_dev * 1.15]
	    set quad_surfdev_acc_max [expr $ave_surf_dev * 1.30]
	    set tri_surfdev_acc_min $quad_surfdev_acc_min
	    set tri_surfdev_des_min $quad_surfdev_des_min
	    set tri_surfdev_des_max $quad_surfdev_des_max
	    set tri_surfdev_acc_max $quad_surfdev_acc_max
	}
	set have_set_defaults 1
    }

    # If custom metrics have already been defined, such in aienv/med/globals.tcl or in batch mesher
    # this will reassign values to the existing values.
    set existing_custom_metrics [ic_uns_get_metric_weights "Custom quality"]
    foreach metric $existing_custom_metrics {
	# e.g. a metric = {{Max warp} QUAD_4 acc_min 0 des_min 0 ideal 0 des_max 10 acc_max 30}
	set verbose_name [lindex $metric 0]
	if {[string equal $verbose_name "Min angle"] || [string equal $verbose_name "Max angle"]} {
	    set verbose_name "Angle"
	}
	if {[string equal $verbose_name "Min side"] } {
	    set custom_metric(minside,active) 1
	    set qualminsideGGVal 1
	}
	if {[string equal $verbose_name "Surface dev"] } {
	    set custom_metric(surfdev,active) 1
	    set qualsurfdevGGVal 1
	}
	set got_key ""
	foreach key $custom_metric_keys {
	    if {[info exists custom_metric(${key},name)] && [string equal $verbose_name $custom_metric(${key},name)]} {
		set got_key $key
		break
	    }
	}
	if {"" == $got_key} {
	    mess "Warning: could not get internal key for $verbose_name...\n" red
	    continue
	}

	set element_type [lindex $metric 1]
	if {"QUAD_4" == $element_type} { set eltype "quad" } elseif {"TRI_3" == $element_type} {set eltype "tri" } else {
	    mess "Warning: ignoring element type $element_type for $verbose_name in user interface...\n" red
	    continue
	}

	# finally, set the vars
	foreach {n v} [lrange $metric 2 end] {
	    set ${eltype}_${got_key}_${n} $v
	}
    }
    foreach k $custom_metric_keys {
	set var qual${k}GGVal
	if { [set $var] == 0 } {
	    ::AIEnv::GUIManagement::ToggleGrey qual${k} 1
	} else {
	    ::AIEnv::GUIManagement::ToggleGrey qual${k} 0
	}
    }
    busy 0
}

proc onqualityMetricsDEZUnLoad {} {
    global disp_options plot_window
    
    if !$disp_options(uns_color_by_quality) {
        aie_delete_colorband
    }
    if {[ic_uns_subset_exists smooth_do_map] && ([info exists plot_window] && ![winfo exists $plot_window])} {
        ic_uns_subset_delete smooth_do_map
    }
}

proc aie_mesh_distribution {pt1 pt2 {what Volume}} {
    switch [lindex $what 0]  {
        1 - Avg {set type 1; set ylab "Avg Edgelen"}
        2 - Min {set type 2; set ylab "Min Edgelen"}
        3 - Max {set type 3; set ylab "Max Edgelen"}
        default {set type 0; set ylab Volume}
    }
    set dist [ic_uns_mesh_distribution $pt1 $pt2 $type]
    if {$dist == ""} {
        mess "No volume element(s) detected between start point and end point\n"
        return
    }
    set specs {}
    foreach {x y n} $dist {
      lappend specs [list $x $y]
    }
    curve_viewer .meshdist "Mesh Distribution" +0+0 Distance [list $ylab] \
        [list $specs] aie_mesh_distribution_done "" "" 0 1 1 ""
}

proc aie_mesh_distribution_done {} {
    catch {destroy .meshdist}
    catch {ic_uns_subset_delete diagnostic_distribution}
}

proc onrepairMeshDEZLoad {} {
    global beta_mode

    set BTMeshVal 0
    set createBuilTopoAngBarVal 0
    if {$topoang == ""} {set topoang 30}
    set topo_bar_fam 0
    set mergetol 0.1
    set smoothIters 6
    set smoothAcc 0.025
    set smoothW 0
    set smoothB 0
    set debug 0
    set upto 0.8
    set makeRemPerGrVal 0
    set makePerButGrVal 0
    set maxSteps 100
    if {$repairSurfCompEdgeFlag == ""} {
        set repairSurfCompEdgeFlag 0
    }
    set offsetLayerFlag 0
    if {$offsetHeightFlag == ""} {
        set offsetHeightFlag 1.0
    }
    set OffsetList {
        "Standard"
        "Simple"
        "Forced simple"
    }
    set offsetSimpleFlag "Standard"

    set repairMeshdb 0
    if [ic_geo_is_loaded] {
        set surfProjFlag 1
    } else {
        set surfProjFlag 0
    }
    set resolvetypeg 0
    set typeList {
        "All Quad"
        "Quad w/one Tri"
        "Quad Dominant"
        "All Tri"
        "Tri (STL like)"
        "Tetra"
    }
    set resolvedb 0
    set enforceNodeMethodVal 0

    # the following should actually, probably be set from Quad, if the mesh was generated in quad.
    if {$elType == ""} {
        if {[meshQuadDEZ get elType] != ""} {
            set elType [meshQuadDEZ get elType]
        } else {
	        if [ ic_count_elements TETRA_4 ] {
		        set elType [lindex $typeList 5]
	        } else {
		        set elType [lindex $typeList 3]
	        }
        }
    }
    set qualityList {
        "Angle error"
        "Quality"
        "Aspect ratio"
        "Custom quality"
        "Ford"
    }
    if {$qualityMetric == ""} {
        set qualityMetric [lindex $qualityList 0]
	    # work-a-round
	    aie_update_keep_consistent
    }
    
    if $beta_mode {
        set qualityList2 {
            "Angle error"
            "Squared angle error"
            "Quality"
            "Aspect ratio"
            "Custom quality"
            "Ford"
            "Workbench shape"
            "Mid-nodes by determinant"
        }
        if {$qualityMetric2 == ""} {
            set qualityMetric2 [lindex $qualityList2 5]
        }
        set upto2 0.8
        set smooth_opt_method 1
    }

    # these are for remesh subset

    set SubsetList [ic_uns_subset_list]
    set subset [lindex $SubsetList 0]
    set PartList [aie_list_parts 0]
    set family ""
    if [ic_geo_is_loaded] {
	    foreach i [ic_geo_get_objects body] {
	        if {[ic_geo_get_family body $i] != "ORFN"} {
	            set family [ic_geo_get_family body $i]
                break
	        }
	    }
    }
    set onlyVolumeFlag 1
}

proc onrepairMeshDEZAfterLoad {} {
    global ExecuteUserProcAfterLoad
    
    set Name "repairMeshDEZ"
    set project_restored 1
    set ExecuteUserProcAfterLoad 0
    
    if [info exists ::AIEnv::GUIManagement::DEZ::${Name}_data] {
        set project_restored 0
    }
    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        repairMeshDEZ hide
        return
    }
    if ![ic_geo_is_loaded] {
        set enforceNodeMethodVal 0
        ::AIEnv::GUIManagement::ToggleGrey enforceByPoint 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey enforceByPoint 0
    }
    aie_update_keep_consistent
    if {!$project_restored} {
        set ExecuteUserProcAfterLoad 1
    }

    if ![info exists repairMeshRGVal] {
        set repairMeshRGVal 0
    }
    set types [ic_uns_list_types]
    if {[lsearch $types TETRA_4] >= 0} {
        ::AIEnv::GUIManagement::ToggleGrey consistentChk10 0
        ::AIEnv::GUIManagement::ToggleGrey KeepConsistSurfChk4 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey consistentChk10 1
        ::AIEnv::GUIManagement::ToggleGrey KeepConsistSurfChk4 1
        set KeepConsistentFlag 0
    }
}

#-----------------------------------Start of Auto Pick procedures for Repair-----------------------------

proc onrepairMeshRMLoad {} {
    set typeList {
        "All Quad"
        "Quad w/one Tri"
        "Quad Dominant"
        "All Tri"
        "Tri (STL like)"
	"Tetra"
    }
    set remeshPartList [aie_list_parts 0]
    append remeshPartList " Inherited"
    set remesh_part "Inherited"
    if $auto_pick_mode {repairMeshElemsPick pick}
}

proc onrepairMeshRMBLoad {} {
    set typeList {
        "All Quad"
        "Quad w/one Tri"
        "Quad Dominant"
        "All Tri"
        "Tri (STL like)"
    }
    # remesh bad elements with tetra (tri2tet) not yet supported
    if {$elType == "Tetra"} { set elType "All Tri" }
    if $auto_pick_mode {repairMeshBadElemsPick pick}
}

proc onfixHoleMeshLoad {} {
    set typeList {
        "All Quad"
        "Quad w/one Tri"
        "Quad Dominant"
        "All Tri"
        "Tri (STL like)"
    }
    if {$elType == "Tetra"} { set elType "All Tri" }
    if $auto_pick_mode {fixHoleMeshElemsPick pick}
}

proc oncloseHoleMeshLoad {} {
    set typeList {
        "All Quad"
        "Quad w/one Tri"
        "Quad Dominant"
        "All Tri"
        "Tri (STL like)"
    }
    if {$elType == "Tetra"} { set elType "All Tri" }
    if $auto_pick_mode {closeHoleMeshElemsPick pick}
}

proc onenforceNodeLoad {} {
    set typeList {
        "All Quad"
        "Quad w/one Tri"
        "Quad Dominant"
        "All Tri"
        "Tri (STL like)"
    }
    if {$elType == "Tetra"} { set elType "All Tri" }
}

proc onstitchEdgeMeshLoad {} {
    if $auto_pick_mode {stitchEdgeMeshElemsPick pick}
}

proc onsmoothLocalMeshLoad {} {
    global smooth

    if $auto_pick_mode {smoothLocalMeshElemsPick pick}
    if ![ic_uns_subset_exists smooth_do_map] {
	    ic_uns_subset_create smooth_do_map 0
	    ic_uns_subset_create smooth_show_map 1 "" 0
	    ic_uns_subset_configure smooth_do_map -list_type 1
	    ic_uns_subset_configure smooth_show_map -shade flat_wire -color white -dont_change_color_or_shade 1
	    set etypes [ic_uns_list_types]
	    set types ""
	    foreach et $etypes {
	        if {(![regexp NODE $et]) && (![regexp LINE $et]) && (![regexp BAR $et])} {
		        lappend types $et
	        }
	    }
	    ic_uns_update_family_type smooth_do_map [ic_uns_list_families]  $types update 1
    }
    set smooth(histogram) smooth
    set smooth(eval) 0
    aie_smooth_update_histogram Quality
}

proc onMakeRemPeriodicLoad {} {
    global beta_mode
    
    if $auto_pick_mode {
	    if $makeRemPerGrVal {
	        RemPeriodicPick pick
	    } else {
	        if $beta_mode {
	            if {$makePerButGrVal == "2"} {
		            makeAutPeriodicPick pick
	            } elseif {$makePerButGrVal == "1"} {
		            makeManPeriodicPick2 pick 
	            } else {
		            makeManPeriodicPick pick
		        }
	        } else {
	            if $makePerButGrVal {
		            makeAutPeriodicPick pick
	            } else {
		            makeManPeriodicPick pick
		        }
	        }
	    }
    }
}

proc onMarkBoundedVolumeLoad {} {
    if $auto_pick_mode {
	    EnclosedSurfsPick pick
    }
}

#-----------------------------------End of Auto Pick procedures for Repair-----------------------------
#----------------------------------- Procedures for AutoApply for Repair------------------------------

proc onrepairMeshElemsPickPick {} {
    if {$remeshList != ""} {
  	    ic_uns_subset_delete $remeshList
    }
}

proc onrepairMeshBadElemsPickPick {} {
    if {$remeshList != ""} {
        ic_uns_subset_delete $remeshList
    }
}

proc onfixHoleMeshElemsPickPick {} {
    if {$remeshList != ""} {
        ic_uns_subset_delete $remeshList
    }
}

proc oncloseHoleMeshElemsPickPick {} {
    if {$remeshList != ""} {
        ic_uns_subset_delete $remeshList
    }
}

proc onstitchEdgeMeshElemsPickPick {} {
    if {$remeshList != ""} {
        ic_uns_subset_delete $remeshList
    }
}

proc onsmoothLocalMeshElemsPickPick {} {
    if {$remeshList != ""} {
        ic_uns_subset_delete $remeshList
    }
}

proc onmakeManPeriodicPickPick {} {
    if {$nodeList != ""} {
        ic_uns_subset_delete $nodeList
    }
}

proc onmakeManPeriodicPick2Pick {} {
    if {$elemList2 != ""} {
        ic_uns_subset_delete $elemList2
    }
}

proc onmakeAutPeriodicPickPick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
}

proc onrepairMeshElemsPickFinish {} {
    if {($remeshList != "") && $auto_pick_mode } {
  	    repairMeshDEZ apply
	    repairMeshElemsPick pick
    }
}

proc onrepairMeshBadElemsPickFinish {} {
    if {($remeshList != "") && $auto_pick_mode } {
  	    repairMeshDEZ apply
	    repairMeshBadElemsPick pick
    }
}

proc onfixHoleMeshElemsPickFinish {} {
    if {($remeshList != "") && $auto_pick_mode } {
  	    repairMeshDEZ apply
	    fixHoleMeshElemsPick pick
    }
}

proc oncloseHoleMeshElemsPickFinish {} {
    if {$remeshList != ""} {
        if {[ic_uns_subset_count_nodes $remeshList] == 2} {
            mess "Not enough edges selected\n" red
            set remeshList ""
            return
        }
    }
    if {($remeshList != "") && $auto_pick_mode } {
  	    repairMeshDEZ apply
	    closeHoleMeshElemsPick pick
    }
}

proc onstitchEdgeMeshElemsPickFinish {} {
    if {($remeshList != "") && $auto_pick_mode } {
  	    repairMeshDEZ apply
	    stitchEdgeMeshElemsPick pick
    }
}

proc onsmoothLocalMeshElemsPickFinish {} {
    if {($remeshList != "") && $auto_pick_mode } {
  	    repairMeshDEZ apply
	    smoothLocalMeshElemsPick pick
    }
}

proc onmakeManPeriodicPickFinish {} {
    if {($nodeList != "") && $auto_pick_mode} {
  	    repairMeshDEZ apply
	    makeManPeriodicPick pick
    }
}

proc onmakeManPeriodicPick2Finish {} {
    if {($elemList2 != "") && $auto_pick_mode} {
  	    repairMeshDEZ apply
	    makeManPeriodicPick2 pick
    }
}

proc onmakeAutPeriodicPickFinish {} {
    if {($elemList != "") && $auto_pick_mode} {
        repairMeshDEZ apply
        makeAutPeriodicPick pick
    }
}

proc onEnclosedSurfsPickFinish {} {
    if $auto_pick_mode {
	    MarkMatlsPick pick
    }
}

proc onMarkMatlsPickFinish {} {
    if {$auto_pick_mode && $bodyList != ""} {
	    repairMeshDEZ apply
    }
}

proc onsetProjPartLoad {} {
    if $auto_pick_mode {
	    setAssocElemsPick pick
    }
}

proc onsetAssocElemsPickFinish {} {
    if {$setAssocElemList != "" && $auto_pick_mode} {
	    repairMeshDEZ apply
	    setAssocElemsPick pick
    }
}

#----------------------------------- End of Procedures for AutoApply for Repair------------------------------

proc aie_update_keep_consistent {} {
    if [repairMeshDEZ get KeepConsistentFlag] {
        ::AIEnv::GUIManagement::ToggleGrey keepConsTypeGG 0
	    if [repairMeshDEZ get keepConsTypeGGVal] {
            ::AIEnv::GUIManagement::ToggleGrey keepConsSelPick 0
	    } else {
            ::AIEnv::GUIManagement::ToggleGrey keepConsSelPick 1
	    }
    } else {
        ::AIEnv::GUIManagement::ToggleGrey keepConsTypeGG 1
    }
}

proc onrepairMeshDEZOK {} {
    global smooth beta_mode options is_win file_name
    
    # maybe the user works with a subset only
    set parts_visible [aie_is_group_type_visible part]
    switch $repairMeshRGVal {
        1 - 2 - 3 - 4 - 5 - 6 {
            if {$remeshList == ""} {
                if {$repairMeshRGVal != 2 && $repairMeshRGVal != 6 && \
                    (!$repairMeshdb || $repairMeshRGVal != 1) && \
                    $repairMeshRGVal != 7 && $repairMeshRGVal != 12} {
                    msg ERROR "No elements selected."
                    return
                }
                set remeshList all
            }
            set args ""
            set geo_active [ic_geo_is_loaded]
            if {$repairMeshRGVal < 5} {
                switch $elType {
                    "All Quad"        { set etype 4 }
                    "Quad w/one Tri"  { set etype 1 }
                    "Quad Dominant"   { set etype 2 }
                    "All Tri"         { set etype 3 }
                    "Tri (STL like)"  { set etype 5 }
                    "Tetra"  { set etype 6 }
                    default {
                        mess "Invalid element type: $elType...using Quad Dominant\n" red
                        set etype 2
                    }
                }
                append args "element $etype "
            }
        }
    }
    set mess_done ""

    switch $repairMeshRGVal {
	    0 {
	        if {$BTMeshVal == 1} {
		        if {$BTMeshList == ""} {
		            mess "Warning: No mesh selected for Build Topo.\n" red
		            return
		        }
		        set map $BTMeshList
	        } else {
	            set map all
	        }
		    if {$createBuilTopoAngBarVal == 0} {
		        ic_uns_build_mesh_topo $map -angle [expr 180 - $topoang]  -uncovered_element_family UNCOVERED
		    } else {
		        ic_uns_build_mesh_topo $map -angle [expr 180 - $topoang]  -uncovered_element_family UNCOVERED "-create_bars_family_intersection"
		    }
	        aie_create_initial_assemblies
	        set BTMeshList ""
	        mess "Done build mesh topology\n" blue
	        return
	    }
	    1 {
	        if {$etype == 6} {
		        set subset $remeshList
		        set subset_vol_part [lindex [ic_uns_subset_list_volume_families $subset] 0]
		        set tempfile [cmd_tempfile tri2tet_temp .uns]
		        ic_save_unstruct $tempfile
		    
		        if $is_win {
		            set cmd [list ic_run_tri2tet [win_shortname $tempfile] [win_shortname $tempfile]]
		        } else {
		            set cmd [list ic_run_tri2tet $tempfile $tempfile]
		        }
		        append cmd " subset $subset keepall 1"
                if {$remesh_part != "" && $remesh_part != "Inherited"} {
		            regsub -all " " [string toupper $remesh_part] _ fam
		            append cmd " family $fam"
		        } elseif {$subset_vol_part != ""} {
		            append cmd " family $subset_vol_part"
		        } else {
		            msg Warning "No volume part defined for re-meshing!\n"
		        }
		        append cmd " use_tg_tri2tet 1"
#		        append cmd " verbose 1"
#		        append cmd " output 4"
		        if {[eval $cmd] && [file exists $tempfile]} {
		            set domain $file_name(domain)
		            aie_close_Mesh 0
		            set file_name(domain) $tempfile
		            aie_open_Mesh 0
		            aie_afterStuffLoaded 0
		            set nelems [expr [ic_count_elements quad] + [ic_count_elements pyra] + [ic_count_elements penta] + [ic_count_elements hexa]]
		            if {$nelems > 0 && [ic_create_pyramids]} {
			            aie_updateMeshVis
			            unstruct_consistent "" 0
		            }
		            set file_name(domain) $domain
		        }
		        cmd_rm $tempfile
		        mess "Done remesh elements\n" blue
		        return
            } else {
                # Remesh Elements
                if {$offsetLayerFlag == ""} { set offsetLayerFlag 0 }
                if {$offsetHeightFlag == ""} { set offsetHeightFlag 1.0 }
                append args "how 0 "
                append args "iters 20 "
                append args "conver 0.025 "
                append args "proj $repairSurfProjFlag "
                append args "offset $offsetLayerFlag "
                append args "offset_h $offsetHeightFlag "
                switch $offsetSimpleFlag {
                    "Standard" {set use_simple_offset 0}
                    "Simple" {set use_simple_offset 1}
                    "Forced simple" {set use_simple_offset 2}
                    default {set use_simple_offset 0}
                }
                append args "simple_offset $use_simple_offset "
                set keep_fixed_nodes 1
                if {$ignoreDimFlag} {
                    set keep_fixed_nodes 0
                }
                append args "keep_fixed_nodes $keep_fixed_nodes "
                append args "debug $repairMeshdb "
                if {$remesh_part != "" && $remesh_part != "Inherited"} {
                    set remesh_part [aie_new_part $remesh_part]
                    append args "material $remesh_part "
                }
                set mess_done "remesh elements"
            }
        }
        2 {
           if {$etype == 6} {
                mess "Remeshing bad elements does not currently support Tetra mesh\n"
                return
           }
            # Remesh Bad Elements
            if {$upto == ""} { set upto 0.8 }
            if {$maxSteps == ""} { set maxSteps 100 }
            append args "how 7 "
            append args "proj $repairSurfProjFlag "
            append args "all_dim $ignoreDimFlag "
            append args "max_steps $maxSteps "
            append args "quality $upto "
            append args "diagnostic {$qualityMetric} "
            set mess_done "remesh bad elements"
        }
        3 {
            # Find/Close Hole
            if {$etype == 6} {
                mess "Remeshing bad elements does not currently support Tetra mesh\n"
                return
            }
            append args "how 1 "
            append args "surf $repairInterPolFlag "
            append args "proj $repairSurfProjFlag "
            append args "geo_id $repairGeoIdFlag "
            set mess_done "find/close holes"
        }
        4 {
            if {$etype == 6} {
                mess "Remeshing bad elements does not currently support Tetra mesh\n"
                return
            }
            # Mesh from Edges
            append args "how 2 "
            append args "surf $repairInterPolFlag "
            #
            #   complete_edges = 0 = make one loop from all selected edges
            #   complete_edges = 1 = make one loop from all selected edges
            #                        and close gaps
            #   complete_edges = 2 = make as many loops as possible from all
            #                        selected edges
            #
            if {$repairSurfCompEdgeFlag == 1} {
                set complete_flag 1
            } elseif {$repairSurfCompEdgeFlag == 2} {
                set complete_flag 0
            } else {
                set complete_flag 2
            }
            append args "complete_edges $complete_flag "
            append args "proj $repairSurfProjFlag "
            append args "improvement 2 "
            append args "make_consistent $KeepConsistentFlag "
            append args "debug $debug "
            set mess_done "mesh from edges"
        }
        5 {
            # Stitch Edges
            if [ic_uns_isimmutable all] {
                mess "Locked elements are present in mesh, please unlock them before using \"Stich Edges\"\n" red
                return
            }
            append args "how 3 "
            append args "merge_tol $mergetol "
            append args "merge_ends $mergeEndNodesFlag "
            append args "debug $debug "
            set mess_done "stitch edges"
        }
        6 {
            # Smooth Surface Mesh
            append args "how 5 "
            append args "iters -$smoothIters "
            append args "conver $smoothAcc "
            append args "proj $surfProjFlag "
            if !$beta_mode {
                append args "w $smoothW "
            } else {
                if $smooth_opt_method {           
                    if {$upto2 == ""} { set upto2 0.8 }
                    append args "w 2 "
                    if {$qualityMetric2 == "Mid-nodes by determinant"} {
                        append args "diagnostic Determinant "
                    } else {
                        append args "diagnostic {$qualityMetric2} "
                    }
                    append args "quality $upto2 "
                } else {
                    append args "w $smoothW "
                }
            }
            append args "b_smooth $smoothB "
            append args "debug $debug "
            if {[info exists options(n_processors)] && $options(n_processors) > 1 } {
                append args "n_threads $options(n_processors) "
            }
            set mess_done "smooth surface mesh"
        }
        7 {
            if $KeepConsistentFlag {
                # don't do the flood fill here.
                if $keepConsTypeGGVal {
                    set what $keepConsElemList
                } else {
                    set what all
                }
                unstruct_consistent "" 0 $what
                set keepConsElemList ""
            }
            if $FloodFillFlag {
                set ff_arg no_repair
                if {[ic_geo_list_families 1] == ""} {
		            set res [tk_dialog .autovol "Auto Volumes" "No material points are defined.\
                        Do you want to run with autovol ?" "" \
                        -1 Yes No Cancel]
                    if {$res == -1} { if [winfo exists .autovol] { top_destroy .autovol; return } }
                    if {$res == 2} return
                    if {$res == 0} {set ff_arg autovol}
                }
                if {[ic_count_elements 3d] != [ic_count_elements TETRA_4]} {
                    ic_flood_fill_mesh
                } else {
                    unstruct_flood_fill $ff_arg
                    if {$ff_arg == "autovol"} {
                        aie_delete_materials
                    } else {
                        aie_show_materials
                    }
                    set aie_meshDisplay(single_edges) 1
#                   set aie_meshDisplay(multiple_edges) 1
                    aie_show_leaks
                }
            }
            aie_create_initial_assemblies
            mess "Done flood fill/make consistent\n" blue
            return
        }

	    8 {
	        if {![info exists setAssocElemList] || $setAssocElemList == ""} {
	            mess "Warning: No elements selected.\n" red
	            return
	        }
	        ic_uns_set_projected_family $setAssocElemList
	        set setAssocElemList ""
	        mess "Done associate mesh with geometry\n" blue
	        return
	    }

        9 {
            switch $enforceNodeMethodVal {
                0 {
                    if {![info exists nodeList] || $nodeList == ""} {
                        mess "Warning: No node selected for \"Enforce Node\".\n" red
                        return
                    }
                    set vertex "-1"
                    set elems [ic_uns_subset_list_elements $nodeList]
                    if {[llength $elems] > 1} {
                        ic_uns_subset_delete $nodeList
                        mess "Warning: Number of nodes > 1. Only 1 node is allowed\
                              for \"Enforce Node\".\n" red
                        set nodeList ""
                        return
                    }
                    foreach item $elems {
                        if {[lindex $item 0] == "VERTEX"} {
                            set vertex [lindex $item 1]
                            break
                        }
                    }
                }
                1 {
                    if {![info exists pointList] || $pointList == ""} {
                        mess "Warning: No point selected for \"Enforce Node\".\n" red
                        return
                    }
                    if {![info exists partList] || $partList == ""} {
                        mess "Warning: No surface mesh part selected for \"Enforce Node\".\n" red
                        return
                    }
                    set nodeList [ic_uns_subset_create]
                    ic_uns_create_vertex $nodeList [ic_geo_get_point_location $pointList] 0
                    if {([ic_uns_subset_count_nodes $nodeList] != 1) || \
                        ([ic_uns_create_element NODE $partList $nodeList 1 visible 0 0])} {
                        mess "Error: Node creation by point failed.\n" red
                        ic_uns_subset_delete $nodeList
                        return
                    }
                    set vertex [lindex [lindex [ic_uns_subset_list_elements $nodeList] 0] 1]
                }
            }
            set args "how 8 "
            switch $elType {
                "All Quad"        { set etype 4 }
                "Quad w/one Tri"  { set etype 1 }
                "Quad Dominant"   { set etype 2 }
                "All Tri"         { set etype 3 }
                "Tri (STL like)"  { set etype 5 }
                "Tetra"           { set etype 3 }
                default {
                    mess "Invalid element type: $elType...using Quad Dominant\n" red
                    set etype 2
                }
            }
            set make_consistent 1
            append args "element $etype "
            append args "proj $repairSurfProjFlag "
            append args "all_dim $ignoreDimFlag "
            append args "vertex $vertex "
            append args "make_consistent $KeepConsistentFlag "
            set mess_done "enforce node, remesh"
        }
	    10 {
	        set make_auto 0
	        if $beta_mode {
	            if {$makeRemPerGrVal} {
		            set makerem "remove"
	            } else {
		            set makerem "make"
		            if {$makePerButGrVal == "2"} {
		                set make_auto 1
		            }
	            }
	        } else {
	            if {$makeRemPerGrVal} {
		            set makerem "remove"
	            } else {
		            set makerem "make"
		            if {$makePerButGrVal} {
		                set make_auto 1
		            }
	            }
	        }
	        if {$beta_mode && $makePerButGrVal == "1" && $make_auto == "0" && $makeRemPerGrVal == "0"} {
		        if {$elemList2 == ""} {
		            mess "Error: Please select at least 2 elements to $makerem periodic\n" red
		            return
	            }
	            if [catch {ic_uns_${makerem}_periodic $elemList2} res] {
		            mess "Error: $res\n" red
		            return
		        }
		        ic_uns_subset_delete $elemList2
		        set elemList2 ""
		        mess "Done make/remove periodic\n" blue
		        return
	        } else {
	            if {$makeRemPerGrVal && !$make_auto} {
		            if {$nodeList == ""} {
		                if { $makeRemPerGrVal } {
			                set n_sel 1
		                } else {
			                set n_sel 2
		                }
		                msg ERROR "Please select at least $n_sel nodes to $makerem periodic"
		                return
		            }
	            }
	            if {!$makeRemPerGrVal && !$make_auto && [ic_uns_subset_count_nodes $nodeList] == 1} {
		            switch -- [tk_dialog .makeper "Make nodes periodic" "Do you really want to make the selected node periodic to itself" "" -1 Yes No] {
		                1 - -1 {
		                    if [winfo exists .makeper] { top_destroy .makeper }
		                    ic_uns_subset_delete $nodeList
		                    set nodeList ""
		                    return
		                }
		            }
		            set vertex [lindex [ic_uns_subset_list_elements $nodeList] 0]
		            set type [lindex $vertex 0]
		            set num [lindex $vertex 1]
		            ic_uns_subset_add_node_numbers $nodeList $num 0
	            }
	        }
	        if {$make_auto} {
		        set smap [ic_uns_subset_create ""]
		        if [catch {ic_uns_make_auto_periodic $elemList $smap} res ] {
		            msg ERROR $res
		        }
		        ic_geo_define_geom_objects
		        aie_create_parts_in_tree_if_needed 
		        aie_update_parts_in_tree_if_needed 
		        aie_updateMeshVis 
		        set fams ""
		        set sparts [ic_geo_list_families]
		        foreach i [array names fam_visible] {
		            if {$fam_visible($i)} {
			            if {[lsearch $sparts $i] != -1} {
			                append fams " $i"
			            }
		            }
		        }
		        # delete unattached dormant curves and points
		        ic_geo_delete_unattached $fams 0 1
		        set topoang 30
		        set args "$::geo_cad(toler) -angle $topoang  -new_family TMP_TOPO_PART_NAME"
		        eval ic_build_topo $args
		        ic_geo_delete_unattached $fams 0 1
		        ic_geo_delete_family "TMP_TOPO_PART_NAME"
		        if {$smap != ""} {
		            ic_uns_subset_delete $smap
		        }
	        } else {
		        if [catch {ic_uns_${makerem}_periodic $nodeList} res ] {
		            msg ERROR $res
		        }
	        }
	        ic_uns_subset_delete $nodeList
	        if [info exists elemList] {
		        if {$elemList != ""} {
		            ic_uns_subset_delete $elemList
		            set elemList ""
		        }
	        }
	        set nodeList ""
            mess "Done make/remove periodic\n" blue
	        return
	    }
	    11 {
	        set matlList ""
	        foreach body $bodyList {
		        lappend matlList [ic_geo_get_body_matlpnt $body]
	        }
	        if $onlyVolumeFlag {
                set sub [ic_uns_subset_create]
                ic_uns_subset_copy $sub all 3
                set only_vol 1
            } else {
                set sub all
                set only_vol 0
            }
	        ic_uns_mark_enclosed_elements $sub $enclSurfs $matlList $only_vol
	        if $onlyVolumeFlag {
                ic_uns_subset_delete $sub
            }
            mess "Done mark enclosed elements\n" blue
	        return
	    }
    }
    set active_subsets ""; set new_elems ""
    if {$repairMeshRGVal == "1" || $repairMeshRGVal == "2" || $repairMeshRGVal == "3" || \
        $repairMeshRGVal == "4" || $repairMeshRGVal == "9"} {
        catch { unset active_subsets_types; unset active_subsets_parts }
        foreach sub [ic_uns_subset_list_visible Selected] {
            set vis [expr [::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $sub 1] == 1]
            if !$vis continue
            lappend active_subsets $sub
            set active_subsets_types($sub) [ic_uns_subset_list_types $sub]
            set active_subsets_parts($sub) [ic_uns_subset_list_families $sub]
        }
        if {$repairMeshRGVal == "9"} {
            set new_elems [eval ic_uns_quad_remesh $nodeList $args]
            if {$KeepConsistentFlag && [ic_uns_count_in_families LIVE]} {
                aie_refresh_parts
                set color [family_color_for_name LIVE]
                aie_tree add_group part LIVE 1 0 $color
                aie_refresh_parts
                aie_color_part LIVE $color
                aie_delete_empty_parts
            }
            ic_uns_subset_delete $nodeList
            set nodeList ""
            aie_updateMeshVis
            mess "Done $mess_done\n" blue
        } else {
            global plot_window smooth prev_qual_criterion
            set recreate_histo 0
            set w $plot_window
            if {[info exists plot_window] && [winfo exists $w] && [info exists smooth(criterion)] && \
                ($repairMeshRGVal == "1" || $repairMeshRGVal == "4")} {
                set children [winfo children $w]
                if {[lsearch $children ".v.plot.graph"] >= 0} {
                    set recreate_histo 1
                }
            }
            set new_elems [eval ic_uns_quad_remesh $remeshList $args]
            if $recreate_histo {
                set criterion [lindex $smooth(criterion) 0]
                set prev_qual_criterion $criterion
                aie_smooth_update_histogram $criterion
            }
            mess "Done $mess_done\n" blue
        }
    } else {
        eval ic_uns_quad_remesh $remeshList $args
        mess "Done $mess_done\n" blue
        busy reset
    }
    if {($repairMeshRGVal == "1" || $repairMeshRGVal == "2" || $repairMeshRGVal == "3" || \
         $repairMeshRGVal == "4" || $repairMeshRGVal == "9") && $active_subsets != "" && $new_elems != ""} {
        set stop 0
        foreach n $new_elems {
            if ![string is integer $n] {
                set stop 1
                break
            }
        }
        if !$stop {
            foreach sub $active_subsets {
                set types $active_subsets_types($sub)
                set parts $active_subsets_parts($sub)
                # recreate the (deleted or new) elements in that subset(s) again
                if {$repairMeshRGVal == "1" || $repairMeshRGVal == "2" || $repairMeshRGVal == "9"} {
                     aie_mesh_subset_update_elements $sub $new_elems $types $parts "0 1"
                } else {
                    ic_uns_subset_add_number $sub $new_elems 1 MIXED
                    mess "Updated subset $sub\n"
                }
            }
        }
    }
    if {$repairMeshRGVal == 4} {
        if {($KeepConsistentFlag == 1) && ([ic_count_elements TETRA_4 ] > 0)} {
            set ff_arg no_repair
            if {[ic_geo_list_families 1] == ""} {
                set res [tk_dialog .autovol "Auto Volumes" "No material points are defined.\
                        Do you want to run with autovol ?" "" -1 Yes No Cancel]
                if {$res == -1} { if [winfo exists .autovol] { top_destroy .autovol; return } }
                if {$res == 2} return
                if {$res == 0} {set ff_arg autovol}
            }
            unstruct_flood_fill $ff_arg
            if {$ff_arg == "autovol"} {
                aie_delete_materials
            } else {
                aie_show_materials
            }
            set aie_meshDisplay(single_edges) 1
            aie_show_leaks
        }
    }
    if {$repairMeshRGVal != "9"} {
        if $parts_visible {
            aie_create_initial_assemblies
        }
        if  {$repairMeshRGVal == 6} {
            if ![ic_uns_subset_exists smooth_do_map] {
                ic_uns_subset_create smooth_do_map 0
                ic_uns_subset_create smooth_show_map 1 "" 0
                ic_uns_subset_configure smooth_do_map -list_type 1
                ic_uns_subset_configure smooth_show_map -shade flat_wire -color white -dont_change_color_or_shade 1
                set etypes [ic_uns_list_types]
                set types ""
                foreach et $etypes {
                    if {(![regexp NODE $et]) && (![regexp LINE $et]) && (![regexp BAR $et])} {
                        lappend types $et
                    }
                }
                ic_uns_update_family_type smooth_do_map [ic_uns_list_families]  $types update 1
            }
            set smooth(histogram) smooth
            set smooth(eval) 0
            aie_smooth_update_histogram Quality
        }
        if {$remeshList != "all"} {
            ic_uns_subset_delete $remeshList
        }
        set remeshList ""
    }
}

proc aie_show_leaks {} {
    # create empty subset
    # add triangles
    # restrict to manifold
    # display it
    # turn on triangles

    set ta [tdv_active 0]

    ic_uns_subset_create LeakLocation
# I don't think we want to include multiple edges when trying
# to repair leaks - Bruce
#    ic_uns_update_family_type LeakLocation __same__ TRI_3 update 1
#    ic_uns_subset_remove_manifold_elements LeakLocation
    ic_uns_subset_clear LeakLocation
    ic_uns_diagnostic diag_type single disp_subset LeakLocation quiet 1
    if [ic_uns_subset_count_elements LeakLocation TRI_3] {
#	::AIEnv::GUIManagement::Tree::ToggleGroupVisibility part * 0
	::AIEnv::GUIManagement::Tree::ToggleUnsMeshVisible All meshNode 0
	aie_subset_put_in_tree mesh LeakLocation
    } else {
#	ic_uns_subset_delete LeakLocation
        aie_delete_mesh_subset LeakLocation
    }
    tdv_active $ta
    update_uns_visible
}

proc onrepairMeshDEZCancel {} {
    if {$remeshList != ""} {
	    ic_uns_subset_delete $remeshList
	    set remeshList ""
    }
    foreach subset [ic_uns_subset_list] {
	    # Don't delete them all!
	    if [string match uns_sel_* $subset] {
	        ic_uns_subset_delete $subset
	    }
    }
    ic_uns_subset_set_current Selected
    aie_updateMeshVis
}

proc onrepairMeshDEZUnLoad {} {
    aie_smooth_clear_histogram
    aie_delete_materials
    erase_flood_fill_lines
}

proc onsmoothLocalMeshUnLoad {} {
    aie_smooth_clear_histogram
}

proc oncheckMeshDEZLoad {} {
    if {$checkElems == ""} {
        aie_check_mesh_defaults
        set checkElems "all"
        set checkMode "fix"
    }
#    set quietFlag 0
    checkMeshDEZ setdirty
}

proc oncheckMeshDEZAfterLoad {} {
    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        checkMeshDEZ hide
        return
    }
}

proc aie_check_mesh_defaults {} {

    if {[ic_uns_dimension] > 2} {
	checkMeshCMS select "Duplicate element" "Error"
	checkMeshCMS select "Volume orientations"  "Error"
	checkMeshCMS select "Surface orientations"  "Error"
	checkMeshCMS select "Hanging elements" "Error"
	checkMeshCMS unselect "Penetrating elements" "Error"
	checkMeshCMS unselect "Disconnected bar elements" "Error"

	checkMeshCMS select "Multiple edges" "Possible Problems"
	checkMeshCMS select "Triangle boxes" "Possible Problems"
	checkMeshCMS select "Single edges" "Possible Problems"
	checkMeshCMS select "Non-manifold vertices" "Possible Problems"
	checkMeshCMS select "Unconnected vertices" "Possible Problems"
	checkMeshCMS unselect "2 single edges" "Possible Problems"
	checkMeshCMS unselect "Single-multiple edges" "Possible Problems"
	checkMeshCMS unselect "Stand-alone surface mesh" "Possible Problems"
	    checkMeshCMS unselect "Delaunay violation" "Possible Problems"
	checkMeshCMS unselect "Overlapping elements" "Possible Problems"
	checkMeshCMS select "Missing internal faces" "Error"
	checkMeshCMS select "Uncovered faces"  "Error"
    } else {
	checkMeshCMS select "Duplicate element" "Error"
	checkMeshCMS select "Multiple edges" "Possible Problems"
	checkMeshCMS select "Single edges" "Possible Problems"
	checkMeshCMS select "Unconnected vertices" "Possible Problems"
	checkMeshCMS select "Overlapping elements" "Possible Problems"
	checkMeshCMS select "Missing internal faces" "Error"
	checkMeshCMS select "Uncovered faces"  "Error"

	checkMeshCMS unselect "Volume orientations"  "Error"
	checkMeshCMS unselect "Surface orientations"  "Error"
	checkMeshCMS unselect "Hanging elements" "Error"
	checkMeshCMS unselect "Periodic problems" "Error"
	checkMeshCMS unselect "Penetrating elements" "Error"
	checkMeshCMS unselect "Disconnected bar elements" "Error"
	checkMeshCMS unselect "Triangle boxes" "Possible Problems"
	checkMeshCMS unselect "Non-manifold vertices" "Possible Problems"
	checkMeshCMS unselect "2 single edges" "Possible Problems"
	checkMeshCMS unselect "Single-multiple edges" "Possible Problems"
	checkMeshCMS unselect "Stand-alone surface mesh" "Possible Problems"
	checkMeshCMS unselect "Delaunay violation" "Possible Problems"
#	checkMeshCMS unselect "Missing internal faces" "Error"
#	checkMeshCMS unselect "Uncovered faces"  "Error"
    }

    set pdata [ic_geo_get_periodic_data]
    if {[lindex $pdata 1] != "none"} {
	    checkMeshCMS select "Periodic problems" "Error"
    } else {
	    checkMeshCMS unselect "Periodic problems" "Error"
    }

}

proc oncheckMeshDEZOK {} {
    set keys ""
    lappend keys [list duplicate [checkMeshCMS query \
	    "Duplicate element" "Error"]]
    lappend keys [list uncovered [checkMeshCMS query \
	    "Uncovered faces"  "Error"]]
    lappend keys [list missing_internal [checkMeshCMS query \
	    "Missing internal faces" "Error"]]
    lappend keys [list vol_orient [checkMeshCMS query \
	    "Volume orientations"  "Error"]]
    lappend keys [list vol_orient [checkMeshCMS query \
	    "Volume orientations"  "Error"]]
    lappend keys [list surf_orient [checkMeshCMS query \
	    "Surface orientations"  "Error"]]
    lappend keys [list hanging [checkMeshCMS query \
	    "Hanging elements" "Error"]]
    lappend keys [list periodic_problem [checkMeshCMS query \
	    "Periodic problems" "Error"]]
    lappend keys [list penetrating [checkMeshCMS query \
	    "Penetrating elements" "Error"]]
    lappend keys [list disconnbars [checkMeshCMS query \
	    "Disconnected bar elements" "Error"]]
    lappend keys [list multiple [checkMeshCMS query \
	    "Multiple edges" "Possible Problems"]]
    lappend keys [list triangle_box [checkMeshCMS query \
	    "Triangle boxes" "Possible Problems"]]
    lappend keys [list single [checkMeshCMS query \
	    "Single edges" "Possible Problems"]]
    lappend keys [list nmanvert [checkMeshCMS query \
	    "Non-manifold vertices" "Possible Problems"]]
    lappend keys [list single_2 [checkMeshCMS query \
	    "2 single edges" "Possible Problems"]]
    lappend keys [list single_multiple [checkMeshCMS query \
	    "Single-multiple edges" "Possible Problems"]]
    lappend keys [list standalone [checkMeshCMS query \
	    "Stand-alone surface mesh" "Possible Problems"]]
    lappend keys [list delaunay [checkMeshCMS query \
	    "Delaunay violation" "Possible Problems"]]
    lappend keys [list overlap [checkMeshCMS query \
	    "Overlapping elements" "Possible Problems"]]
    lappend keys [list disconnected_vert [checkMeshCMS query \
	    "Unconnected vertices" "Possible Problems"]]

	if {$checkMode == "fix_quiet"} {
	    set check fix
	    set quiet 1
	} else {
	    set check $checkMode
	    set quiet 0
	}
    aie_mesh_diag_check $keys $checkElems $check $quiet
    checkMeshDEZ setdirty
}

proc aie_mesh_diag_check { keys which mode {quiet 0}} {
    global diagnostic_data options aie_meshDisplay
    global diag_fix_mode diag_fix_is_fixed

    if {$mode == "fix"} {set mode ""}
    set options(diag_which) $which

    set num_checks 0
    foreach key $keys {
        if [lindex $key 1] { incr num_checks }
    }
    if $num_checks {
        set percent [expr 100.0 / $num_checks]
        set percent_check 0.0
        if [batch_interp eval info exists interrupt_pending] {
            batch_interp eval unset interrupt_pending
        }
        interrupt begin "Check Mesh" "" 100.0 "batch_interp eval set interrupt_pending 1" no_grab
    }
    foreach key $keys {
        set name [lindex $key 0]; set val [lindex $key 1]
        if {$name == "vol_orient" && $val == 1} {
            if {$mode == "subset"} {
                if [info exists run_twice] {
                    unset run_twice
                    continue
                }
            } else {
                if ![info exists run_twice] {
                    set run_twice 0
                } else {
                    incr run_twice
                }
                if {![info exists diag_fix_is_fixed] && $run_twice == "1"} {
                    unset run_twice
                    continue
                }
            }
        } else {
            catch { unset run_twice; unset diag_fix_is_fixed }
        }
        set diagnostic_data($name,check) $val
        if $val {
            interrupt check $percent_check 100.0 "check $name"
            if {[info exists run_twice] && $run_twice && $name == "vol_orient"} {
                mess "Trying to fix volume orientation a second time\n" blue
                set nsub [unstruct_diag_check $name $mode 1 1 $quiet]
            } else {
                set nsub [unstruct_diag_check $name $mode 1 0 $quiet]
            }
            if [batch_interp eval info exists interrupt_disable] {
                batch_interp eval unset interrupt_disable
            }
            set percent_check [expr $percent_check + $percent]
            interrupt check $percent_check 100.0 "check $name"
            if {[batch_interp eval info exists interrupt_pending] && [batch_interp eval set interrupt_pending]} {
                mess "\nCheck Mesh interrupted -- only partial results obtained\n" red
                break
            }
            if {$nsub != ""} {
                aie_new_mesh_subset $nsub
            }
        }
    }
    if $num_checks {
        catch { interrupt finish }
        catch { ::AIEnv::GUIManagement::ConfigureConsoleZone 0 }
    }
    catch { unset run_twice; unset unset diag_fix_is_fixed }
    set aie_meshDisplay(single_edges) 1
    set aie_meshDisplay(multiple_edges) 1
    aie_create_parts_in_tree_if_needed
    aie_updateMeshVis
}

proc onrepairMeshDEZCancel {} {
    foreach subset [ic_uns_subset_list] {
	# Don't delete them all!
	if [string match uns_sel_* $subset] {
	    ic_uns_subset_delete $subset
	}
    }
    ic_uns_subset_set_current Selected
    aie_updateMeshVis
}

proc onadjustMeshDEZLoad {} {
    set refSteps 1

    if ![ic_uns_is_loaded] { return }

    if {$refinemaxDev == ""} {
        set min_tri_val [expr [ic_uns_min_tri_size visible] * 0.25]
        set min_quad_val [expr [ic_uns_min_quad_size visible] * 0.25]
        set refinemaxDev [expr { ($min_tri_val <= $min_quad_val) \
                    ? $min_tri_val : $min_quad_val}]
    }
    if {$refinemaxLen == ""} {
        set refinemaxLen 0.0
    }
    if {![info exists refinemaxAsp] || $refinemaxAsp == ""} {
        set refinemaxAsp 0.0
    }
    set refineMeshNobound 0
    if {$coarsMinAsp == ""} {
        set coarsMinAsp 0.2
    }
    set coarsNumIter 1
    if {$coarsmaxDev == ""} {
        set coarsmaxDev 0.1
    }
    if ![info exists adjustMeshTypeGGVal] {
        set adjustMeshTypeGGVal 0
    }
    set PartList [aie_list_parts 1]
    if ![info exists adjustMeshTypeGGVal] {
        adjustMeshDEZ setclean
    }
    if [ic_geo_is_loaded] {
        set refineMeshProjFlag 1
    } else {
        set refineMeshProjFlag 0
    }

    if [info exists refMeshDistGGVal] {
        set numProcs [aie_refine_dist_init]
    }
    set onlyTriFlag 0
    set byMidSideFlag 1
}

proc onadjustMeshDEZAfterLoad {} {
    if ![ic_uns_is_loaded] {
        msg ERROR "No mesh available"
        adjustMeshDEZ unload
    }
    aie_set_refinement_only_by midside
}

proc oncoarsenMeshLoad {} {
    set ntotal [ic_count_elements]
    set nothers [expr [ic_count_elements NODE] +  [ic_count_elements LINE_2]]
    set ntritetraquad [expr [ic_count_elements TETRA_4] +  [ic_count_elements TRI_3] + [ic_count_elements QUAD_4] ]
    if {[expr $ntotal - $nothers] != $ntritetraquad} {
	    set msg "Warning: Can coarsen the whole mesh only for linear TRI / TETRA or Quad dominant mesh"
	    tk_messageBox -message $msg -title "Coarsen Mesh Warning"
#	::AIEnv::GUIManagement::ToggleGrey coarsenMesh 1
#    } else {
#	::AIEnv::GUIManagement::ToggleGrey coarsenMesh 0
    }
}

proc oncoarsenSelectedMeshLoad {} {
    if {[ic_count_elements TETRA_4] == 0 && [ic_count_elements QUAD_4] == 0 &&  [ic_count_elements TRI_3] == 0} {
	    set msg "Warning: Can coarsen only linear TETRA/TRI or Quad dominant mesh"
	    tk_messageBox -message $msg -title "Coarsen Mesh Warning"
	    ::AIEnv::GUIManagement::ToggleGrey coarsenSelectedMesh 1
    } else {
	    if {[ic_count_elements TETRA_4] == 0 && [ic_count_elements QUAD_4] == 0 && [ic_count_elements TRI_3] > 0} {
	        set msg "Warning: Mesh contain only triangles. Can coarsen only for all mesh"
	        tk_messageBox -message $msg -title "Coarsen Mesh Warning"
	    }
	    ::AIEnv::GUIManagement::ToggleGrey coarsenSelectedMesh 0
    }
}

proc aie_set_refinement_only_by {what} {
    if {$what == "midside"} {
        if [adjustMeshDEZ get byMidSideFlag] {
            adjustMeshDEZ set onlyTriFlag 0
        }
    } elseif {$what == "trionly"} {
        if [adjustMeshDEZ get onlyTriFlag] {
            adjustMeshDEZ set byMidSideFlag 0
        }
    }
}

proc onadjustMeshDEZOK {} {
    set geo_active [ic_geo_is_loaded]
    if {$refineMeshProjFlag == 1 && $geo_active == 1} {
        set pl 1
    } else {
        set pl 0
    }
    if { ($adjustMeshTypeGGVal == 1 && $RefineMethod == 0) \
        || ($adjustMeshTypeGGVal == 0 && $Refine2Method == 0) } {
            set dev -1
            set len -1
            set asp -1
    }
    if {$refinemaxDev > 0 && ( ($adjustMeshTypeGGVal == 1 && $RefineMethod == 1) || ($adjustMeshTypeGGVal == 0 && $Refine2Method == 1) )  && $geo_active == 1 } {
        set dev $refinemaxDev
    } else {
        set dev -1
    }
    if {$dev > 0} {
        set pl 1
    }
    if {$refinemaxLen >= 0 && ( ($adjustMeshTypeGGVal == 1 && $RefineMethod == 2) || ($adjustMeshTypeGGVal == 0 && $Refine2Method == 2) ) } {
        set len $refinemaxLen
    } else {
        set len -1
    }
    if {[info exists refinemaxAsp] && $refinemaxAsp >= 0 && (($adjustMeshTypeGGVal == 1 && $RefineMethod == 3) || ($adjustMeshTypeGGVal == 0 && $Refine2Method == 3) ) } {
        set asp $refinemaxAsp
    } else {
        set asp -1
    }
    if { $adjustMeshTypeGGVal == 0 || $adjustMeshTypeGGVal == 1 } {
        if {[ic_count_elements TETRA_4] + [ic_count_elements TRI_3] + [ic_count_elements QUAD_4] == 0 } {
            user_error "Can only refine linear tetra/Quad/triangle mesh"
            return
        }
    }
    if {$adjustMeshTypeGGVal == 0 || $adjustMeshTypeGGVal == 2} {
        if {[ic_uns_isimmutable all]} {
            mess "Locked elements are present in mesh, please unlock them to adjust mesh density\n" red
            return
        }
    } else {
        if {($elemList != "") && [ic_uns_isimmutable $elemList]} {
            mess "Locked elements are present in selected mesh, please unlock them to adjust mesh density\n" red
            return
        }
    }
    if {$adjustMeshTypeGGVal == 0 &&
        [info exists refMeshDistGGVal] &&
        $refMeshDistGGVal == 1} {
        adjustMeshDEZ aie_refine_dist_run
        return
    }
    set tris_exist 0
    set quads_exist 0
    set tetras_exist 0
    switch $adjustMeshTypeGGVal {
        0 {
            mess "Before Refining: [ic_count_elements] elements, [ic_count_nodes] nodes\n"
            if {$dev > 0} { set pl 1 }
            if $byMidSideFlag {
                ic_undo_group_begin 
                for {set i 0} {$i < $refSteps} {incr i} {            
                    ic_uns_refine_by_midside_nodes name all project $pl calc_projection 1 calc_projection_tol 0.01
                    if {$refSteps > 1} { mess "Refining step [expr $i + 1] : [ic_count_elements] elements, [ic_count_nodes] nodes\n" }
                }
                ic_undo_group_end
            } else {
                ic_uns_refine_surface all $dev $refSteps $pl $onlyTriFlag $len $asp $refineMeshNobound
            }
            mess "After Refining: [ic_count_elements] elements, [ic_count_nodes] nodes\n"
            aie_updateMeshVis
            return
        }
        1 {
            if {$dev > 0} { set pl 1 }
            if {$elemList == ""} return
            set active_subsets ""; set new_elems ""
            catch { unset active_subsets_types; unset active_subsets_parts }
            foreach sub [ic_uns_subset_list_visible Selected] {
                set vis [expr [::AIEnv::GUIManagement::Tree::NodeVisibleStatus mesh_subset $sub 1] == 1]
                if !$vis continue
                lappend active_subsets $sub
                set active_subsets_types($sub) [ic_uns_subset_list_types $sub]
                set active_subsets_parts($sub) [ic_uns_subset_list_families $sub]
            }
            set new_elems [ic_uns_refine_surface $elemList $dev $refSteps $pl $onlyTriFlag $len $asp $refineMeshNobound]
            ic_uns_subset_delete $elemList
            set elemList ""
            foreach sub $active_subsets {
                set types $active_subsets_types($sub)
                set parts $active_subsets_parts($sub)
                aie_mesh_subset_update_elements $sub $new_elems $types $parts "0 1 2 3"
            }
            aie_updateMeshVis
            return
        }
        2 {
            set selmap1 all
            if {[ic_count_elements TRI_3] == 0} {
              set tris_exist 0
            } else {
              set tris_exist 1
            }
            if {[ic_count_elements QUAD_4] == 0} {
              set quads_exist 0
            } else {
              set quads_exist 1
            }
            if {[ic_count_elements TETRA_4] == 0} {
              set tetras_exist 0
            } else {
              set tetras_exist 1
            }
        }
        3 {
            if {$elemList == ""} {
                mess "No elements selected\n" red
                return
            }
            set freezeParts ""
            set selmap1 $elemList
            set list_types [ic_uns_subset_list_types $elemList]
            if {[lsearch $list_types TRI_3] < 0} {
              set tris_exist 0
            } else {
              set tris_exist 1
            }
            if {[lsearch $list_types QUAD_4] < 0} {
              set quads_exist 0
            } else {
              set quads_exist 1
            }
            if {[lsearch $list_types TETRA_4] < 0} {
              set tetras_exist 0
            } else {
              set tetras_exist 1
            }
        }
    }

    if {!$tetras_exist && !$quads_exist && !$tris_exist} {
        mess "Warning: Can coarsen only TETRA/TRI or QUAD dominant mesh\n" red
        return
    }
    if {!$coarsmaxDev} {
        mess "Please enter a maximum surface deviation.\n" red
        return
    }
    if {$adjustMeshTypeGGVal == 3} {
        if {![ic_uns_subset_count_nodes $elemList] && \
            ($tris_exist && !$quads_exist && !$tetras_exist) && \
            [ic_uns_subset_count_elements $selmap1 TRI_3] == \
            [ic_count_elements TRI_3]} {
            ic_uns_subset_configure $selmap1 -list_type 0
        }
    }
    mess "Before Coarsening: [ic_count_elements] elements, [ic_count_nodes] nodes\n"
    if {$tetras_exist || !$quads_exist} {
        ic_uns_coarsen $selmap1 $coarsMinAsp $freezeParts $coarsmaxDev \
            $coarsNumIter $coarseSurfFlag $checkSizeFlag $coarsMaxSize
    } else {
        if {$coarsMaxSize == " "} {
            mess "Please enter a preferred max size.\n" red
            return
        }
        ic_uns_coarsen_quad $selmap1 -1 -1 $coarsNumIter
    }
    mess "After Coarsening: [ic_count_elements] elements, [ic_count_nodes] nodes\n"
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
        set elemList ""
    }
    ic_uns_renumber_nodes all 1
}

proc onrenumberMeshDEZLoad {} {
    if {$renumVec == ""} {
	set renumVec "1 0 0"
	set startEnum 1
	set startNnum 1
	set doElems 1
	set doNodes 1
	set renumList ""
	set renumSelVal 0
	set renumberMeshEGVal 0
    }
    set skip0Flag 1
    set type 0
    set iterations 5
    set rangee ""
    set rangen ""
}

proc onrenumberMeshDEZAfterLoad {} {
    if ![ic_uns_is_loaded] {
	msg ERROR "No mesh available"
	renumberMeshDEZ hide
	return
    }
    if {[trace vinfo doElems] != ""} {
        trace vdelete doElems w aie_trace_renumber_mesh
    }
    trace variable doElems w aie_trace_renumber_mesh
    if {[trace vinfo doNodes] != ""} {
        trace vdelete doNodes w aie_trace_renumber_mesh
    }
    trace variable doNodes w aie_trace_renumber_mesh
    aie_trace_renumber_mesh "" "" ""
    if {[trace vinfo renumberMeshEGVal] != ""} {
        trace vdelete renumberMeshEGVal w aie_trace_renumber_count
    }
    trace variable renumberMeshEGVal w  aie_trace_renumber_count
    aie_trace_renumber_count "" "" ""
}

proc aie_trace_renumber_count {name element op} {
    if [renumberMeshDEZ get renumberMeshEGVal] return

    set numbers [ic_uns_subset_elements_range all]
    set firste [lindex $numbers 0]; set laste [lindex $numbers 1]
    set firstn [lindex $numbers 2]; set lastn [lindex $numbers 3]
    renumberMeshDEZ set rangee "$firste -> $laste"
    renumberMeshDEZ set rangen "$firstn -> $lastn"
}

proc aie_trace_renumber_mesh {name element op} {
    if [renumberMeshDEZ get doElems] {
        ::AIEnv::GUIManagement::ToggleGrey renumStartE 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey renumStartE 1
    }
    if [renumberMeshDEZ get doNodes] {
        ::AIEnv::GUIManagement::ToggleGrey renumStartN 0
    } else {
        ::AIEnv::GUIManagement::ToggleGrey renumStartN 1
    }
}

proc onrenumberMeshDEZUnLoad {} {

    if {$renumList != ""} {
        ic_uns_subset_delete $renumList
    }
    if {[trace vinfo doElems] != ""} {
        trace vdelete doElems w aie_trace_renumber_mesh
    }
    if {[trace vinfo doNodes] != ""} {
        trace vdelete doNodes w aie_trace_renumber_mesh
    }
    if {[trace vinfo renumberMeshEGVal] != ""} {
        trace vdelete renumberMeshEGVal w aie_trace_renumber_count
    }
}

proc onrenumSelPickFinish {} {
    if {$renumSelVal == 2 && ($renumList != "") && $auto_pick_mode } {
        renumberMeshDEZ apply
        renumSelPick pick
    }
}

proc onrenumSelPick2Finish {} {
    if {$renumSelVal == 3 && ($renumList != "") && $auto_pick_mode } {
        renumberMeshDEZ apply
        renumSelPick2 pick
    }
}

proc onrenumberMeshDEZOK {} {
    switch $renumberMeshEGVal {
	0 {
	    if {$renumSelVal == 0} {
		set parts ""
		foreach p [lsort [ic_geo_list_parts]] {
		    set fs [ic_geo_list_families_in_part $p]
		    set ss [ic_uns_subset_create_family_type $fs __all__ 0 0]
		    if {$ss != ""} { lappend parts $ss $p }
		}
	    } elseif {$renumSelVal == 1} {
		set parts [list all "Whole mesh"]
	    } elseif {$renumSelVal == 2} {
	        set parts [list $renumList "Selected elements"]
	    } elseif {$renumSelVal == 3} {
	        set parts [list $renumList "Selected nodes"]
	    }
	    set startn $startNnum
	    set starte $startEnum
	    foreach {part partn} $parts {
            set direct "0 0 0"
            if $renumDirVal {
                if {[llength $renumVec] != "3"} {
                    user_error "Direction vector needs 3 values"
                    return
            }
		    set direct $renumVec
		}		
		if {$renumSelVal == 0 || $renumSelVal == 1} {
		    set map $part
		} elseif {$renumSelVal == 2 || $renumSelVal == 3} {
            set map $renumList
            if {$map == ""} {
                user_error "No elements or nodes selected"
                return
		    }
        }
        if {$renumSelVal == 3} {
            set tmap [ic_uns_subset_create]
            set fam [lindex [ic_uns_subset_list_families $map] 0]
            ic_uns_create_element NODE $fam $map 0 $tmap 0 0 0
            ic_uns_subset_delete $map
            set map $tmap
        }
		mess "$partn:"
		if $doNodes {
		    set endn [ic_uns_renumber_nodes $map $startn $skip0Flag $direct]
		    mess " nodes $startn -> $endn"
		    if $skip0Flag {
		        set rangen "$startn -> $endn"
		    } else {
		        set rangen "$startNnum -> $endn"
		    }
		    set startn [expr $endn + 1]
		    if {$renumSelVal == 3} {
		        ic_delete_elements subset $map type NODE
            }
		}
		if {$doElems && $renumSelVal != 3} {
		    set ende [ic_uns_renumber_elements $map $starte $skip0Flag $direct]
		    mess " elems $starte -> $ende"
		    if $skip0Flag {
                set rangee "$starte -> $ende"
		    } else {
		        set rangee "$startEnum -> $ende"
		    }
		    set starte [expr $ende + 1]
		}
		mess "\n"
		
		if {$renumSelVal == 0} {
		    ic_uns_subset_delete $part
		} else {
		    ic_uns_subset_delete $renumList
		}
	    }
	    set renumList ""
	}
	1 {
            mess "Warning: the bandwidth operation cannot be undone\n" red
	    if {$bandwidthtype == "profile"} {
		set type 0
            } else {
		set type 1
 	    }
	    set p [ic_uns_bandwidth visible $iterations $type]
	    if {$bandwidthtype == "profile"} {
	        mess "The profile is $p.\n"
	    } else {
	        mess "The bandwidth is $p.\n"
	    }
	}
    }
}

proc onthicknessMeshDEZLoad {} {
    set AMTVal 2
    set doSolidGGVal 0
    set piercingFlag 0
    set partsurfList ""
}

proc onthicknessMeshDEZOK {} {

    switch $AMTVal {
        0 {
            if $piercingFlag {
                aie_thickness create 2 $partsurfList
            } else {
                aie_thickness create $doSolidGGVal $partsurfList
            }
        } 
        1 { aie_thickness clear } 
        2 {
            if {$nodes == ""} {
                mess "Error: No nodes selected\n" red
                return
            }
            if {$thickness != "" && ([string is integer $thickness] || [string is double $thickness]) && $thickness > 0} {
                ic_uns_thickness_at_node $nodes $thickness
                mess "Applied thickness\n"
                ic_uns_subset_delete $nodes
                set nodes ""
            } else {
                if {([string is integer $thickness] || [string is double $thickness]) && $thickness <= 0} {
                    mess "Error: thickness must be > 0\n" red
                } else {
                    mess "Error: missing value for thickness\n" red
                }
            }
        }
    }
}

proc onreorientConsistentLoad {} {
    global auto_pick_mode

    if $auto_pick_mode {
	reorientConsElemPick pick
    }
}

proc onreorientConsElemPickFinish {} {
    if {$auto_pick_mode && $elemList != ""} {
	    reorientMeshDEZ apply
	    reorientConsElemPick pick
    }
}

proc onreorientReverseLoad {} {
    global auto_pick_mode
    if $auto_pick_mode {
	    reorientElemsPick pick
    }
}

proc onreorientElemsPickFinish {} {
    global auto_pick_mode
    if {$auto_pick_mode && $elemList != ""} {
	    reorientMeshDEZ apply
	    reorientElemsPick pick
    }
}	

proc onreorientMeshDEZLoad {} {
    global aie_meshDisplay aie_meshStyle aie_meshTypeVis set_by_user

    foreach style [array names aie_meshStyle] {
	    if {$aie_meshStyle($style) != 0} {
	        set prev_mesh_style $style
	    }
    }
    set reorientDir "0 0 1"
    set reorientConsFlag 0
    set reorientConsVis 0
    if {![info exists aie_meshDisplay(normals)] || !$aie_meshDisplay(normals)} {
        if {![info exists aie_meshDisplay(normals_colored)] || !$aie_meshDisplay(normals_colored)} {
            set reset_normals_style 1
        }
    }
    set shells_on [::AIEnv::GUIManagement::Tree::NodeVisibility meshShellNode]
    if {$prev_mesh_style == "Wire" && $shells_on} {
        set aie_meshStyle(Wire) 0
        set aie_meshStyle(Solid/wire) 1
        aie_changeMeshDisplay style Solid/wire
    }
    if {![info exists reorientVolIJKHowVal] || $reorientVolIJKHowVal == ""} {
        set reorientVolIJKHowVal 0
    }
    if {$prev_mesh_style == "Wire" && $shells_on || [info exists reset_normals_style]} {
        if [info exists reset_normals_style] {
            set aie_meshDisplay(normals_colored) 1
            set aie_meshDisplay(normals) 0
        }
        update_uns_visible
        if [info exists reset_normals_style] {
            set aie_meshDisplay(normals) 0
        }
    }
}

proc aie_reorient_IJKMS0 {name element op} {
    aie_reorient_IJKMS "I"
}

proc aie_reorient_IJKMS1 {name element op} {
    aie_reorient_IJKMS "J"
}

proc aie_reorient_IJKMS2 {name element op} {
    aie_reorient_IJKMS "K"
}

proc aie_reorient_IJKMS {idx} {
    foreach c {I J K} {
        if [setVolumeIJKMS query "Set $idx" $c] {
            foreach r {I J K} {
                if {$r == $idx} continue;
                if [setVolumeIJKMS query "Set $r" $c] {
                    set c1 ""
                    foreach p {I J K} {
                        if {$p != $r && $p != $idx} {
                            foreach q {I J K} {
                                if [setVolumeIJKMS query "Set $p" $q] {
                                   set c1 $q
                                   break
                                }
                            }
                            break
                        }
                    }
                    if {$c1 != ""} {
                        foreach q {I J K} {
                            if {$q != $c && $q != $c1} {
                                setVolumeIJKMS select "Set $r" $q
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            break;
        }
    }
}

proc onreorientMeshDEZAfterLoad {} {
    if ![ic_uns_is_loaded] {
	    mess "No mesh available\n" red
	    reorientMeshDEZ hide
	    return
    }
}

proc onreorientLineLoad {} {
    global auto_pick_mode
    ic_uns_subset_configure "" -draw_directions 1
    if $auto_pick_mode {
        reorientLinesPick pick
    }
}

proc onreorientLineUnLoad {} {
    ic_uns_subset_configure "" -draw_directions 0
}

proc onreorientLinesPickFinish {} {
    if {$auto_pick_mode && $elemList != ""} {
        reorientMeshDEZ apply
        reorientLinesPick pick
    }
}

proc onreorientMeshDEZOK {} {
    global fam_visible
    
    set args ""
    switch $reorientElemsEGVal {
	0 {
	    set how vol
	    set smap visible
	    set args [expr !$reorientOutwardFlag]
	}
	1 {
	    set how consistent
	    set smap visible
	    set args $elemList
#	    if {$elemList == ""} {
#		mess "Error: No reference element selected\n" red
#		return
#	    }
	}
	2 {
	    set how flip
	    set smap $elemList
	    
	    if {[info exists filterflag] && $filterflag} {
		set how dir
		set args $reorientDir
		set screen_norm [lindex [$tdv_default screen2world 100 100] 1]
		set args $screen_norm
	    }

	    if 0 {
	    #This is for MeshProtyper
	    #Adding filtering of the selection, flipping only the grey elements on the screen
	    if {[info exists filterflag] && $filterflag} {
	    	set screen_norm [lindex [$tdv_default screen2world 100 100] 1]
			set elmlist [ic_uns_subset_list_elements $elemList]
	    	if {[llength $elmlist] > 500} {
				switch -- [ tk_dialog .flip_warn "Warning" \
			 	"You have selected more than 500 elements.  This could take some time.\n  Do you wish to Continue." \
			 		"" -1 Yes No ] {
			 		    -1 { if [winfo exists .flip_warn] { top_destroy .flip_warn; return 0 } }
			     		0 {}
			     		1 { return 0 }
		     	}			
			}
			ic_undo_stop
			tdv_active 0
			busy 1

			foreach e $elmlist {
    			set el_type [lindex $e 0]
    			set el_num [lindex $e 2]
    			set subset [ic_uns_subset_create]
    			ic_uns_subset_add_number $subset $el_num 2 $el_type
    			set normal [ic_uns_subset_normal $subset]
    			set ang [ic_geo_vec_dot $screen_norm $normal]
    			set to_flip [ic_uns_subset_create]
    			if {$ang < 0} {
	    			ic_uns_reorient $subset flip 
    			}
				
    			ic_uns_subset_delete $subset
			}

			tdv_active 1
			ic_undo_start
			busy reset
			return 
			}
	}
	
	}
	3 {
	    set how dir
	    set smap visible
	    set args $reorientDir
            if {[llength $args] != 3} {
                mess "Error: Unknown direction. Please enter the direction vector\n" red
                return
            }

	}
	4 {
	    set how flip
	    set smap $elemList
	}
	5 {
	    set smap $elemList
	}
    }

    if {$smap != ""} {
        switch $reorientElemsEGVal {
            1 {
                if {$args != ""} {
                    if $reorientConsFlag {
                        ic_uns_reorient $elemList flip
                    }
                    set e [ic_uns_subset_list_elements $args]
                    set reference [lindex $e 0]
                    set type [lindex $reference 0]
                    set num [lindex $reference 1] 
                    set part [lindex $reference 4]
                    aie_reorient_mesh_consistent "" "$type" "$num" $reorientConsVis
                } else {
                    set t "TRI_3 TRI_3_X TRI_6 TRI_6_X QUAD_4 QUAD_4_X QUAD_8 QUAD_8_X QUAD_9"
                    foreach f [ic_uns_list_families] {
                        if {(![ic_uns_check_family $f]) || ($reorientConsVis && \
                             ([info exists fam_visible($f)]) && (!$fam_visible($f)))} continue
                        set sourcemap [ic_uns_subset_create]
                        ic_uns_subset_add_families_and_types $sourcemap $f $t
                        if {[ic_uns_subset_count_elements $sourcemap] > 0} {
                            set e [ic_uns_subset_list_elements $sourcemap]
                            set reference [lindex $e 0]
                            set type [lindex $reference 0]
                            set num [lindex $reference 1] 
                            set part [lindex $reference 4]               
                            mess "Reorient part $part..."
                            aie_reorient_mesh_consistent "$part" "$type" "$num" 0
                            mess "done\n"
                        }
                        ic_uns_subset_delete $sourcemap
                    }
                }
            }         
            5 {
		reorientVolume $smap $reorientVolIJKHowVal $vert
		set vert ""
	    }
            default {
	        ic_uns_reorient $smap $how $args
	    }
	}
	ic_uns_subset_delete $elemList
	set elemList ""
    }

}

proc aie_reorient_mesh_consistent {part type_orig num_orig visib} {
    global fam_visible
    
    set num $num_orig
    set type $type_orig
    set sourcemap [ic_uns_subset_create]
#   ic_uns_subset_add_families_and_types $sourcemap $part $type
    if {$part == ""} {
	    if $visib {
	        set parts ""
	        foreach f [array names fam_visible] {
		        set vis [get_fam_visible $f]
		        if $vis { lappend parts $f }
	        }
	    } else {
	        set parts all
	    }
    } else {
	    set parts "$part"
    }
    ic_uns_subset_add_families_and_types $sourcemap $parts {TRI_3 TRI_3_X TRI_6 TRI_6_X QUAD_4 QUAD_4_X QUAD_8 QUAD_8_X QUAD_9}
    set reference_elems [ic_uns_subset_list_elements $sourcemap]
    while [ic_uns_subset_count_elements $sourcemap] {
	    set smap [ic_uns_subset_create]
	    ic_uns_subset_add_number $smap $num 1 $type
	    set consmap [ic_uns_subset_create]
	    ic_uns_subset_add_number $consmap $num 1 $type
	    ic_uns_subset_add_attached $consmap $sourcemap fam
	    ic_uns_reorient $consmap consistent $smap
	    ic_uns_subset_subtract_from $sourcemap $consmap
	    ic_uns_subset_delete $consmap
	    ic_uns_subset_delete $smap
	    set elems [ic_uns_subset_list_elements $sourcemap]
	    if {$elems == ""} break
	    set reference [lindex $elems 0]
	    if {$reference == ""} break
	    set type [lindex $reference 0]
	    set num  [lindex $reference 1]
	    if {($type == "") || ($num == "")} break
    }
    ic_uns_subset_delete $sourcemap
}

proc onreorientMeshDEZUnLoad {} {
    global aie_meshDisplay aie_meshStyle 

    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
    }
    if {$aie_meshStyle($prev_mesh_style) != 1} {
        aie_changeMeshDisplay style $prev_mesh_style
    }
    if [info exists reset_normals_style] {
        set aie_meshDisplay(normals) 0
        set aie_meshDisplay(normals_colored) 0
        unset reset_normals_style
    }
    update_uns_visible
}

proc onreorientVolIJKLoad {} {    
    global aie_meshDisplay
    foreach v {I J K} {
	setVolumeIJKMS select "Set $v" $v
        set aie_meshDisplay(trace_IJKMS_${v}) $v
    }

    if $auto_pick_mode {
	switch $reorientVolIJKHowVal {
	    0 {reorientVolIJKM1Pick pick}
	    1 {reorientVolIJKM2Pick pick}
	    2 {reorientVolIJKM3Pick pick}
	    3 {reorientVolSetIJKPick pick}
	}
    }    
    set row 0
    while { $row < 3 } {
        set var ::AIEnv::GUIManagement::MultiSelect::MultiSelectData(setVolumeIJKMS,SelectData,Row${row})
        if {[trace vinfo $var] != ""} {
            trace vdelete $var w aie_reorient_IJKMS${row}
        }
        trace variable $var w aie_reorient_IJKMS${row}
        aie_reorient_IJKMS${row} "" "" ""
        incr row
    }
}

proc onreorientVolIJKUnLoad {} {
    global aie_meshDisplay
    set row 0
    while { $row < 3 } {
        set var ::AIEnv::GUIManagement::MultiSelect::MultiSelectData(setVolumeIJKMS,SelectData,Row${row})
        if {[trace vinfo $var] != ""} {
            trace vdelete $var w aie_reorient_IJKMS${row}
        }
        incr row
    }
}

proc onreorientVolIJKM1PickFinish {} {
    if {$elemList != "" && $auto_pick_mode} {
	reorientVolume $elemList $reorientVolIJKHowVal $vert
	reorientVolIJKM1Pick pick
	ic_uns_subset_delete $elemList
	set elemList ""
	set vert ""
    }
}

proc onreorientVolIJKM2PickFinish {} {
    if {$elemList != "" && $auto_pick_mode} {
	reorientVolVertexPick pick
	if {$vert != ""} {
	    reorientVolume $elemList $reorientVolIJKHowVal $vert
	    reorientVolIJKM2Pick pick
	    ic_uns_subset_delete $elemList
	    set elemList ""
	    set vert ""
	}
    }
}

proc onreorientVolIJKM3PickFinish {} {
    if {$elemList != "" && $auto_pick_mode} {
	reorientVolume $elemList $reorientVolIJKHowVal $vert
	reorientVolIJKM3Pick pick
	ic_uns_subset_delete $elemList
	set elemList ""
	set vert ""
    }
}

proc reorientVolume {map how_reorient {vert ""}} {
    if {$map == ""} {
	msg ERROR "No volume element selected"
	return
    }
    set how "ijk"
    set args {}
    lappend args $how_reorient
    switch $how_reorient {
	0 {
#	    foreach vol $map {
#		hex_command "rotate_super_block $vol"
#	    }
	}
	1 {
	    if {$vert == ""} {
		msg ERROR "No node selected"
		return
	    }
	    lappend args $vert
#	    hex_command "change_origin $map $vert"
	}
	2 {
	    if {$map == ""} {
		msg ERROR "No reference volume element selected"
		return
	    }
#	    hex_command "align_superblocks $map"
	}
	3 {
	    foreach r {I J K} {
		foreach c {I J K} {
		    if [setVolumeIJKMS query "Set $r" $c] {
			lappend args [string tolower $c]
		    }
		}
	    }
#	    foreach vol $map {
#		hex_command "set_super_block_ijk $vol $ijk"
#	    }
	}
    }
    ic_uns_reorient $map $how $args
    update_uns_visible
}

#################### parametric mesh update ########################

proc onparaMeshDEZOK {} {
    if ![ic_geo_is_loaded] {
        msg ERROR "No geometry loaded"
        return
    }
    switch $paramesh_action {
        associate {
            ic_uns_associate_geometry
            mess "Mesh associated with geometry parametrically\n" blue
        }
        update {
            if [catch {eval ic_uns_update_paramesh} res] {
                msg ERROR "Parametric mesh update failed"
                return
            }
	        mess "Parametric mesh update successfull\n" blue
        }
    }
}

# Stuff for distributed data (debugging mostly)

proc onmodifyDistributedDEZLoad {} {
    set fieldNames [ic_uns_bcfield_list]
    mess "Found [llength $fieldNames] attribute(s) in mesh: $fieldNames\n"
    set field ""
    set value ""
    set default ""
}

proc onmodifyDistributedDEZAfterLoad {} {
    if {[trace vinfo field] != ""} {
        trace vdelete field w aie_modify_distribute_attribute_name
    }
    trace variable field w aie_modify_distribute_attribute_name
}

proc onmodifyDistributedDEZUnLoad {} {
    if {[trace vinfo field] != ""} {
        trace vdelete field w aie_modify_distribute_attribute_name
    }
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
        set elemList ""
    }
}

proc just_one_bcfield_val {field elemList} {
    set val0 ""
    set differ 0
    if {($elemList != "") && ($field != "")} {
	    set vals [ic_uns_bcfield_get $field $elemList 0]
	    foreach v $vals {
	        if {$val0 == ""} {
		        set val0 $v
	        } elseif {$val0 != $v} {
		        set val0 ""
		        mess "Values differ for attribute $field on the selected elements\n"
		        set differ 1
		        break
	        }
	    }
    }
    if {$val0 == "" && $v == "" && !$differ} {
        mess "Nothing defined for attribute $field on the current selected elements\n"
    }
    return $val0
}

proc onmodifyDistributedPickPick {} {
    if {$elemList != ""} {
        ic_uns_subset_delete $elemList
        set elemList ""
    }
}

proc onmodifyDistributedPickFinish {} {
    set elemList [modifyDistributedDEZ get elemList]
    if {$elemList != ""} {
        foreach v [ic_uns_bcfield_list] {
            set n [just_one_bcfield_val $v $elemList]
            if {$n != ""} {
                modifyDistributedDEZ set field $v
                modifyDistributedDEZ set value $n
                break
            }
        }
    }
}

proc aie_modify_distribute_attribute_name {{name ""} {element ""} {op ""}} {
    set f [modifyDistributedDEZ get field]
    if {$f == ""} return
    set e [modifyDistributedDEZ get elemList]
    if {$e == ""} return
    set v [just_one_bcfield_val $f $e]
    if {$v == ""} return
    set d [ic_uns_bcfield_default $f]
    modifyDistributedDEZ set value $v
    modifyDistributedDEZ set default $d
}

proc onmodifyDistributedDEZOK {} {
    if {$elemList == ""} {
        mess "No elements selected\n" red
        return
    }
    if {$field == ""} {
        mess "Missing \"Attibute\"\n" red
        return
    }
    if {$value == ""} {
        mess "Missing \"Value\"\n" red
        return
    }
	if ![ic_uns_bcfield_exists $field] {
	    mess "Creating new distributed property value \"$field\"..."
	} else {
	    mess "Updating distributed property value \"$field\"..."
	}
	# Do this no matter what because the default might have changed
	ic_uns_bcfield_define $field $default
	ic_uns_bcfield_set $field $elemList $value
	set fieldNames [ic_uns_bcfield_list]
	mess "done\n"
}

proc aie_optms_smooth {} {
    global optms_vals

    if ![ic_uns_is_loaded] {
        msg ERROR "Need to create or load a mesh first."
        return
    }
    set w .optms_opts
    if [winfo exists $w] {destroy $w}

    set buts [list [list Apply   "aie_optms_smooth_apply $w"] \
		   [list Dismiss "form_done $w"] \
		   [list Defaults "aie_optms_smooth_defaults"]]
    set d [form_init $w "Opt-MS Options" "" $buts ]
    if {$d != ""} {
	set bg [$w cget -background]

        form_label $d.la "Overall Smoothing Passes" "0 0"
        form_entry $d.ea optms_vals(p) float_blank "0 1"

        set ff [form_label_frame $d.s "Surface Mesh" "1 0 -columnspan 3"]
        set f [form_label_frame $ff.t Technique "0 0 -columnspan 3"]
        set ln 0
        set col 0
        foreach {i j} {\
            1 "Laplacian Only" \
            2 "Smart Laplacian Only" \
            3 "Optimization Only" \
            5 "Combined Method 1" \
            6 "Combined Method 2" \
            7 "Combined Method 3" \
            4 "Combined Method 4" \
            8 "Floating Threshold"} {
            form_radiobutton $f.f$i $j optms_vals(t2) $i "$ln $col"
            incr col
            if {$col == 2} {
              set col 0
              incr ln
            }
        }

        set f [form_label_frame $ff.f Function "1 0 -columnspan 3"]
        set ln 0
        set col 0
        foreach {i j} {\
            1 "Max Min Angle" \
            2 "Min Max Cos" \
            3 "Max Min Cos" \
            4 "Max Min Sin" \
            5 "Min Max Angle" \
            6 "Min Max Jacobian Diff" \
            7 "Max Min Scaled Jacobian" \
            8 "Max Min Area Length Ratio" \
            9 "Min Max Length Area Ratio" \
            10 "Max Min Interior Angle" \
            11 "Max Min Interior Sin" \
            12 "Min Max Interior Cos" \
            13 "Max Min Interior Scaled Jacobian" \
            14 "Min Max Norm Jacobian" \
            15 "Min Max Condition Number"} {
            form_radiobutton $f.f$i $j optms_vals(f2) $i "$ln $col"
            incr col
            if {$col == 2} {
              set col 0
              incr ln
            }
        }

        form_label $ff.la "Threshold Value" "2 0"
        form_entry $ff.ea optms_vals(a2) float_blank "2 1"

        set ln 3
        foreach {i j} {\
            l2 "Initial Laplacian Pases" \
            u2 "Untangle Mesh Passes" \
            s2 "Number of Smoothing Passes"} {
            form_label $ff.l$i $j "$ln 0"
            form_entry $ff.e$i optms_vals($i) int_blank "$ln 1"
            incr ln
        }

        set ff [form_label_frame $d.v "Volume Mesh" "1 3"]

        set f [form_label_frame $ff.t Technique "0 0 -columnspan 3"]
        set ln 0
        set col 0
        foreach {i j} {\
            1 "Laplacian Only" \
            2 "Smart Laplacian Only" \
            3 "Optimization Only" \
            5 "Combined Method 1" \
            6 "Combined Method 2" \
            7 "Combined Method 3" \
            4 "Combined Method 4" \
            8 "Floating Threshold"} {
            form_radiobutton $f.f$i $j optms_vals(t3) $i "$ln $col"
            incr col
            if {$col == 2} {
              set col 0
              incr ln
            }
        }

        set f [form_label_frame $ff.f Function "1 0 -columnspan 3"]
        set ln 0
        set col 0
        foreach {i j} {\
            21 "Min Max Dihedral" \
            22 "Max Min Dihedral" \
            23 "Min Max Cos Dihedral" \
            24 "Max Min Cos Dihedral" \
            25 "Max Sin Dihedral" \
            26 "Max Min Scaled Jacobian" \
            27 "Min Max SRMS Volume Ratio" \
            28 "Min Max Condition Number" \
            29 "Min Max Norm Jacobian"} {
            form_radiobutton $f.f$i $j optms_vals(f3) $i "$ln $col"
            incr col
            if {$col == 2} {
              set col 0
              incr ln
            }
        }

        form_label $ff.la "Threshold Value" "2 0"
        form_entry $ff.ea optms_vals(a3) float_blank "2 1"

        set ln 3
        foreach {i j} {\
            l3 "Initial Laplacian Pases" \
            u3 "Untangle Mesh Passes" \
            s3 "Number of Smoothing Passes"} {
            form_label $ff.l$i $j "$ln 0"
            form_entry $ff.e$i optms_vals($i) int_blank "$ln 1"
            incr ln
        }

	form_finish +300+300
    }
}

proc aie_optms_smooth_defaults {} {
    global optms_vals
    array set optms_vals {
        p 1
        t2 4
        f2 4
        a2 ""
        l2 0
        s2 5
        u2 10
        t3 4
        f3 25
        a3 ""
        l3 0
        s3 5
        u3 10
    }
}

aie_optms_smooth_defaults

proc aie_optms_smooth_apply {w} {
    global env optms_vals file_name

    form_done $w
    if {[info exists env(OPTMS_BIN)] && $env(OPTMS_BIN) != ""} {
        set prog [join [split $env(OPTMS_BIN) \\] /]
    } else {
        set prog optms
    }
    if {![file exists $prog] && [catch {get_program icemcfd $prog} prog]} {
        mess "Can't find optms program\n" red
        return
    }
    set cmd [list $prog]
    foreach i [array names optms_vals] {
        if {$optms_vals($i) != ""} {
            lappend cmd -$i $optms_vals($i)
        }
    }

    set tempfile ""
    set meshIN $file_name(domain)
    if {$meshIN == "" || ![file exists $meshIN] || [ic_uns_is_modified]} {
        set tempfile [cmd_tempfile optms_temp .uns]
        ic_save_unstruct $tempfile
        set meshIN $tempfile
    }
    set meshOUT [file join $file_name(project_dir) optms_mesh.uns]

    lappend cmd $meshIN $meshOUT
    mess "\n$cmd\n"

    if [catch {open |$cmd "r"} fp] {
        mess "Error: $fp\n" red
        if {$tempfile != ""} {cmd_rm $tempfile}
        return
    }
    while {[gets $fp line] >= 0} {
        mess "$line\n" blue
        update idletasks
    }
    if [catch {close $fp} msg] {
        mess "Error: $msg\n" red
        if {$tempfile != ""} {cmd_rm $tempfile}
        return
    }

    aie_close_Mesh 0
    set file_name(domain) $meshOUT
    aie_open_Mesh 0
    aie_afterStuffLoaded 0
    if {$tempfile != ""} {cmd_rm $tempfile}
}

proc aie_refine_dist_init {} {
    global refine_dist
    set refine_dist(hostfile) [aie_hosts_hostfile refine]
    return [aie_hosts_nprocs $refine_dist(hostfile)]
}

proc aie_refine_dist_hosts {} {
    global refine_dist
    aie_hosts_setup $refine_dist(hostfile) aie_refine_dist_update
}

proc aie_refine_dist_update {hostfile} {
    adjustMeshDEZ set numProcs [aie_hosts_nprocs $hostfile]
    adjustMeshDEZ setdirty
}

proc aie_refine_dist_run {} {
    global env is_win file_name refine_dist

    if {[info exists env(REFINE_DIST_BIN)] && $env(REFINE_DIST_BIN) != ""} {
        if $is_win {
            set prog [join [split $env(REFINE_DIST_BIN) \\] /]
        } else {
            set prog $env(REFINE_DIST_BIN)
        }
    } else {
        if [catch {get_program icemcfd refine_dist} prog] {
            mess "Error:$prog\n" red
            return
        }
    }
    if {[catch {expr int($numProcs)} nprocs] || $nprocs < 1} {
        mess "Error: number of partitions must be greater then 0\n" red
        return
    }
    set nb 0
    set dev ""
    set len ""
    set proj [ic_geo_is_loaded]
    switch $Refine2Method {
        0 {set proj $refineMeshProjFlag}
        1 {
            if [catch {expr double($refinemaxDev)} dev] {
                mess "Error:bad valid for surface deviation\n" red
                return
            }
            if {!$proj} {
                mess "Error:can't do surface deviation - geometry not loaded\n" red
                return
            }
        }
        2 {
            if [catch {expr double($refinemaxLen)} len] {
                mess "Error:bad valid for edge length\n" red
                return
            }
            set nb $refineMeshNobound
            set proj $refineMeshProjFlag
        }
        default {
            mess "Error:refinement method not supported for distributed\n" red
            return
        }
    }
    set load 0
    set verbose 0
    if [info exists distLoad] {set load $distLoad}
    if [info exists distVerbose] {set verbose $distVerbose}

    set hostfile $refine_dist(hostfile)
    if {$hostfile == "" || ![file exists $hostfile]} {
        mess "Error: need to define hosts\n" red
        return
    }
    if $is_win {
        set hostfile [win_shortname $hostfile]
        set cmd [win_shortname [file dirname $prog]]/[file tail $prog]
    } else {
        set cmd $prog
    }
    if {$verbose} {lappend cmd -v}
    if {$distOneProc} {lappend cmd -1}
    if {[info exists waitTimeout] && $waitTimeout != ""} {
        lappend cmd -w$waitTimeout
    }
    lappend cmd -n$nprocs -f$hostfile --

    if {![catch {expr $refSteps > 1} ok] && $ok} {
        lappend cmd -s$refSteps
    }
    if {$nb} {lappend cmd -b}
    if {$dev != ""} {lappend cmd -d$dev}
    if {$len != ""} {lappend cmd -e$len}
    if {$load} {lappend cmd -r}
    if {$verbose} {lappend cmd -v}

    set temp_uns ""
    set modified [ic_uns_is_modified]
    set meshIN $file_name(domain)
    if {$meshIN == "" || ![file exists $meshIN] || $modified} {
        set temp_uns [cmd_tempfile refine_dist_temp .uns]
        ic_save_unstruct $temp_uns
        set meshIN $temp_uns
        ic_uns_set_modified $modified
    }
    lappend cmd $meshIN

    set temp_tin ""
    if {$proj && [ic_geo_is_loaded]} {
        set modified [ic_geo_is_modified]
        set tetinIN $file_name(tetin)
        if {$tetinIN == "" || ![file exists $tetinIN] || $modified} {
            set temp_tin [cmd_tempfile refine_dist_temp .tin]
            ic_save_tetin $temp_tin
            set tetinIN $temp_tin
            ic_geo_set_modified $modified
        }
        lappend cmd $tetinIN
    }

    if {$load} {
        for {set n 1} {$n <= $nprocs} {incr n} {
            catch {file delete "partition_$n.uns"}
        }
    }

    mess "\n$cmd\n"
    set error ""
    if [catch {open |$cmd "r"} fp] {
        set error $fp
    } else {
        while {[gets $fp line] >= 0} {
            mess "$line\n" blue
            update idletasks
        }
        if [catch {close $fp} msg] {
            set error $msg
        }
    }
    if {$temp_uns != ""} {cmd_rm $temp_uns}
    if {$temp_tin != ""} {cmd_rm $temp_tin}
    if {$error != ""} {mess "$error\n" red}
    if {!$load} return
    set uns_files ""
    for {set n 1} {$n <= $nprocs} {incr n} {
        if {![file exists "partition_$n.uns"]} {
            mess "Error:not all meshes recovered - can't load\n" red
            return
        }
        lappend uns_files "partition_$n.uns"
    }

    aie_close_Mesh 0
    aie_open_Mesh 0 "" "" $uns_files
    aie_afterStuffLoaded 0
}
