#
# Modif. 10/27/06: "inherit" usage
# - aie_check_inherit_fam without parameters return "inherit" value
# - part_name on...Load Point,Curve,Surf,Repair,Faceted set "Grey" if "inherit"
# - alternative set "inherit" On/Off is available on RightClick on window "above" Part  
#
proc aie_rename_geometry {type} {
    # types: 0 -point 1 -curve 2 -surface 3 - density 4 - entity
    rename_geometryDEZ show
    set d ::AIEnv::DEZ::rename_geometryDEZ::rename_geometry
    if {![info exists ${d}Name] || ([llength [set ${d}Name]] !=1)} {
	set c [string toupper [string index $type 0]]
	set ${d}Name ${c}_00
    }
    set ${d}List ""
    set stype [lsearch "point curve surface density entity" $type]
    set ${d}Type $stype
}
#----------------------
proc onrename_geometryDEZOK {} {
    global va_set
    set rename_geometryChk 1
    # types: 0 -point 1 -curve 2 -surface 3 - density 4 - entity
    set stype [lindex "point curve surface density entity" $rename_geometryType]
    set type $stype
    if {[llength $rename_geometryName] != 1} {
       set rename_geometryName [string toupper [string index $type 0]]_00
    }
    set nn [llength $rename_geometryList]
    set count 0 
    if !$nn return
    foreach word $rename_geometryList {
	if {[lsearch "point curve surface density" $word] >= 0} {
	    set type $word
	    continue
	}
	ic_geo_set_name $type $word $rename_geometryName $rename_geometryChk 0
	incr count
	
    }
    status_message "Renamed $count ${stype}(s)\n"  
    set rename_geometryList ""
}
#---------------------
proc va_check_data_set_points {List {outtype keep} {fam GEOM} {name P_001}} {
    global vid_options
    #=======
    # VG: Next 2 procedures use input: point(name) or xyz
    # Output depends on "outtype": "point" -> all points; xyz -> all xyz; keep -> keep
    # Note 1: if something wrong - return "". 
    # Note 2: List must be list (not single point): { {} {} ...}
    #       For single point use va_check_data_set_point
    # Note 3: Output is a list of valid names and/or locations (expressions)
    #=======
    set out ""
    # Next loop may create geo point if outtype== "point" and data is not valid point
    if {[info exists vid_options(auxiliary)] && $vid_options(auxiliary)} {
		set outtype "point"
    }
    foreach p $List {
	lappend out [va_check_data_set_point $p $outtype $fam $name]
    }
    return $out
}
#========
proc va_check_data_set_point {Point {outtype keep} {fam GEOM} {name P_001}} {
global vid_options
if ![info exists vid_options(vid_mode)] {set vid_options(vid_mode) 0}
set vid_mode $vid_options(vid_mode)
#Next command checks all possibilities: triplet, virtual, med
# IF NOT A NAME or triplet return "xyz" in LCS (07/1/06)
#valid triplet?
    if [ic_is_triplet $Point] {
		if {$outtype == "point"} {
			set name [ic_vset -new_name $name all]
			if $vid_mode {
				ic_vset -vec $name $Point
				ic_image vidpoint_im $name $Point		
				return $name
			} else {
				return [ic_point "" $fam $name $Point]
			}
		}
		return $Point
	}	
#valid name?
	# return Point if Point is a name
	if {[llength $Point] == 1} {
		set xyz [ic_vset -pnt_any $Point]
		if {$xyz != ""} {
		# valid name. return xyz only if "xyz" format; or return name
			if {$outtype == "xyz"} {return $xyz}
		return $Point
	}	
	}
#valid expression? may be 1 or more words
    set xyz [ic_vset -vec - $Point]
	if {$xyz == ""} {return ""}
# return xyz if "xyz" format; return expression!	
	if {$outtype == "xyz"} {
		return $xyz
	}
	if {$outtype != "point"} {
	# valid expression; return expression; do not convert into global CSYS!
	# Note on LCS usage: slim differences
	# if outtype = "xyz" ->result converted in global if triplet or expression
	# if outtype = "point" ->result converted in global if triplet or expression
	#	triplet "1 2 3" will be converted into global
			return $Point
		}
	# expression: outtype = "point", create new med or virtual.
	set name [ic_vset -new_name $name all]
	if $vid_mode {
		ic_vset -vec $name $Point
		ic_image vidpoint_im $name $xyz		
		return $name
	} else {
		return [ic_point "" $fam $name $xyz]
	}
}
#================================================= 
proc oncreatePointsDEZOK {}  {
    global fam_visible va_set geom_visible param vid_info aie_geoTypeVis vid_options beta_mode

    if [string match $::geo_part_name "From screen"] {
        mess "Error: wrong part name: \"$::geo_part_name\"\n" red
        return
    }
    if {![aie_check_inherit_fam] && [ic_hex_subset_named_selection $::geo_part_name]} {
        mess "Error: a named selection subset with name \"$::geo_part_name\" already exists; use some other part name\n" red
        return
    }
    
    set part_name [aie_geo_set_part_name $::geo_part_name] 
    set part_is_new [expr 1 - [info exists fam_visible($part_name)]]
    set part_name [aie_new_part $part_name]
    # Modified for 11.0:
    # All points function use ic_point where name will be set if necessary
    #  
    if { [ic_geo_is_loaded] == 0 } {
	ic_empty_tetin
    }
    
    set nnames ""
    set force_new_name 0   
    set fam $part_name   
    #
    # 38362: fam may be reset if $inherit + "parent" family found
    # Note: if $inherit ->first valid family set inherit = 0.
    # see aie_check_inherit_fam 

    set vid_info(dez_result) ""
    switch -- $createPointsEXGVal {	
	0 {
		if {[llength $pickScreenList] > 1} {set force_new_name 1}	
		foreach p $pickScreenList {
			if $force_new_name {set name [ic_vset -new_name $name all]}
			set res [ic_point "" $part_name $name $p]
			if {$res == ""} continue
			lappend nnames $res
		}
	}
	1 {
	    oncreatePntExpresLoad	
	    switch -- $createPntExplicitVal {
		0 {
			set nnames [ic_point "" $part_name $name "$x,$y,$z"]	    
		}
		1 {
		    set params [va_check_get_params $crePntParamList]
		    set nn [llength $params] 
		    if !$nn {
			status_message "Errror m value(s). Use list or loop \n" red
			return
		    }
		    if {$nn > 99} {
			ic_mess "Note: Only first 100 values will be used\n"
		    }	
		    if {$nn > 1} {set force_new_name 1}	
		    foreach m0 $params {
			ic_vdefine m variable $m0
			if $force_new_name {set name [ic_vset -new_name $name all]}
			lappend nnames [ic_point "" $part_name $name "$Xexpress,$Yexpress,$Zexpress"]	   
			}
		}
	    }
	}
	2 {
	    # create point by a base point + dx,dy,dz.
		# base point may be a vector expression, Delta x,y,z are scalar expressions   
		set bp $pickBasePnt
		# validation: may be MED point (only case for inherit), or  Vector names 
		# may be also: triplet, expression.... .
		# 	
			if [aie_check_inherit_fam fam point $bp] {
				set nnames [ic_point "" $fam $name "$bp+vector($dx,$dy,$dz)"]
			} elseif {[ic_vset -pnt_any $bp] != ""} {
				# may be vector (ViPoint) name
				set nnames [ic_point "" $fam $name "$bp+vector($dx,$dy,$dz)"]
			} else {
				# may be scalar expressions. Base point will not be created.
				set xyz [ic_vset -vec - $bp]
				if {$xyz == ""} {
					status_message "Base point not defined"
		            return
	            }
				foreach "x y z" $xyz ""
				set nnames [ic_point "" $fam $name "$x+($dx),$y+($dy),$z+($dz)"]
			}		
		}		
	3 {
	    # create point between 3 locations.
	    if !$createPointsCentFRVal {
		aie_check_inherit_fam fam point $pickCenterList
	    set nnames [ic_point center $fam $name $pickCenterList]
	    } else {
	      aie_check_inherit_fam fam curve $pickCenterCrv
	      set nnames [ic_point arc_center $fam $name $pickCenterCrv]	    
	      set pickCenterCrv ""	 
	   }
	}
	4 {
	    # create point OR SET OF POINTS between two points as a function of parameter. 
		# check: p1 & p2 must be a names of med or ViPor create new
		aie_check_inherit_fam fam point $pickBetweenList	
		#50082: create start-end points (if no med points!):
		# if auxiliary is On, - MED points, if Off - Virtual poins
		# Start/End point may be expression, XYZ, or MED point; each "between" point is an expression.
		foreach ind {0 1} { 
		  set data [lindex $pickBetweenList $ind]
		  incr ind
		  set xyz [ic_vset -vec - $data]
		  if {$xyz == ""} {
            status_message "Invalid start/end point definition" red
			return
		  }		
		  if {[ic_vset -med_entity $data] == "point"} {	  
		      set p$ind $data
		  } else {
		       	set pname [ic_vset -new_name $name all]
		       	set p$ind $pname	     
						if {[info exists vid_options(auxiliary)] && $vid_options(auxiliary)} {
						    ic_geo_cre_pnt $fam $pname $xyz
						} else {
						    ic_vset -vector $pname $xyz 
						}
			}
		}						
		set vec_incr [ic_vset -vec - $p2-$p1]
		if {$vec_incr == "" || $vec_incr == "0 0 0"} {
			status_message "Select 2 different \"points\"" red
			return
		}							     
		if $createPnt2LocMethodVal {
			set params [va_check_get_params $ratio]
			if {[llength $params] > 1} {set force_new_name 1}
			set i 0
			foreach par $params {
				if $force_new_name {set name [ic_vset -new_name $name all]}
				lappend nnames [ic_point "" $fam $name $p1+($p2-$p1)*([lindex $ratio $i])]
				incr i
			} 
		} else {
			if ![va_is_int_or_real $nPnt2Loc] {
				set nPnt2Loc 1
			}
			set nPnt2Loc [expr int($nPnt2Loc)]
			if {$nPnt2Loc > 100} {
				ic_mess "number of points set 100\n"
			}
			set n_pts_between $nPnt2Loc
			if {$n_pts_between > 0} {
			    set d [expr 1.0/($n_pts_between+1)]
			    set par $d
			    for {set i 0} {$i < $n_pts_between} {incr i} {
				    set name [ic_vset -new_name $name all]
				    lappend nnames [ic_point "" $part_name $name $p1+($p2-$p1)*($par)]				
				    set par [expr $par+$d]
			    } 
			}
		} 
		# delete (if any) virtual points p1,p2
		ic_vset -delete $p1
		ic_vset -delete $p2		
	}
	
	5 {
		# For multiply curves check inherit family for each one 
		if {[llength $pickEndList] > 1} {set force_new_name 1}  
		foreach crv $pickEndList {
			aie_check_inherit_fam fam curve $crv
			if $force_new_name {set name [ic_vset -new_name $name all]}
			switch $ptExtEGVal {
			    0 {
				lappend nnames [ic_point curve_end $fam $name "$crv $which_end"]
			    }
			    1 {
				lappend nnames [ic_geo_extract_points $crv $fangle]
			    }
			}
			set fam $part_name
			set name [ic_vset -new_name $name all]						

		}
	}
	
	6 {
	    #create a point by intersecting two curves.
	  	aie_check_inherit_fam fam curve $pickIntList
	    set nnames [ic_point intersect $fam $name $pickIntList tol $toler]
	}
	
	7 {
	    # create point on a curve at param.
	    # here pickParList may be a list
	    # 

		if !$createPntCrvParMethodVal {
			if {[catch "format %d $nPnt2Loc"] || ($nPnt2Loc <= 0)} {
				set nPnt2Loc 1
			}
			set dp [expr 1.0/($nPnt2Loc + 1)]
			set params ""
			for {set i 1} {$i <= $nPnt2Loc} {incr i} {
				lappend params [expr $i*$dp]
			}
		} else {
	    set params [va_check_get_params $crePnts3param]
		}
		set np [llength $params]
	    if !$np {
			status_message "Error: wrong parameter: \"$crePnts3param\"\n" red
			return
	    } 
	    if {([lindex $params 0] < 0.0) || ([lindex $params end] > 1.000001)} {
			status_message "Error: wrong parameter(s): $params" red
		return
	    } 
	    if {![info exists pickParList] || $pickParList == ""} {
		ic_mess "Error: No curve selected\n" red
		return
	    }
	    if {$np > 1} {set force_new_name 1} 
	    aie_check_inherit_fam fam curve $pickParList
	    foreach par $params {
			if $force_new_name {set name [ic_vset -new_name $name all]}
			lappend nnames [ic_point crv_par $fam $name "$pickParList $par"] 
	    }
	}
	
	8 {
	    # create a point by projecting an existing point on a curve/surface.             
	    if {$pickProjCrv == ""} {
			status_message "No curve" red
			return
		}
		aie_check_inherit_fam fam curve $pickProjCrv
		set nnames ""
		set plist ""
	    if $movePointPrjFlag {
		    foreach p $pickPoint {
		        set pp [ic_geo_project_and_move_point curve $pickProjCrv $p "0 0 0" 0 $fam]
		        if {$pp == ""} {
                    mess "Error: unable to project and move point $p\n" red 
		            continue
		        }
		        append nnames "$pp "
		   }
		} else {
		    set pickPoint [va_check_data_set_points $pickPoint keep $fam $name.01]
		    if {[llength $pickPoint] > 1} { set force_new_name 1 }
		    foreach pt $pickPoint {
			    if $force_new_name { set name [ic_vset -new_name $name all] }
			    foreach crv $pickProjCrv {
                    set ret [ic_point projcurv $fam $name [list $pt $crv]]
                    if {$ret != ""} {
			            lappend nnames $ret
			        }
                }
		    }
		}
		if {$trimCrvPrjFlag && [llength $nnames]} {
			if [catch {ic_geo_split_curve $pickProjCrv $nnames} ret] {
			    return
			}
		}
	}
	9 {
	    if {$pickProjSrf == ""} {
			status_message "No surface" red
			return
		}
		aie_check_inherit_fam fam surface $pickProjSrf
		set nnames ""
		set plist ""
		if $movePointPrjFlag {
		    foreach p $pickPoint2 {
		        set pp [ic_geo_project_and_move_point surface $pickProjSrf $p "0 0 0" 0 $fam]
		        if {$pp == ""} {
                    mess "Error: unable to project and move point $p\n" red 
		            continue
		        }
		        append nnames "$pp "
		    }
		} else {
		    set pickPoint2 [va_check_data_set_points $pickPoint2 keep $fam $name.01]
		    if {[llength $pickPoint2] > 1} {set force_new_name 1}		
		    foreach pt $pickPoint2 {
			    if $force_new_name {set name [ic_vset -new_name $name all]}
			    lappend nnames [ic_point projsurf $fam $name [list $pt $pickProjSrf]]
		    }
		}			
		if $embedPntOnSurfFlag {
			foreach pt $nnames { 
			    ic_geo_add_embedded_pnt $pickProjSrf $pt
			}
		}
    }
    }
    aie_updateGeoVis point 0 1
    # Force Visible
      if [llength $nnames] {
		status_message "Done:points $nnames"
		if $part_is_new {
			set aie_geoTypeVis(point) 2
			aie_updateGeoVis point 1 1
		}
	}  else {
		set ::select_action cancel
	}  
    set vid_info(dez_result) $nnames
    if { $nnames != "" && [info exists fam_visible($part_name)] && \
    !($fam_visible($part_name) && $geom_visible(point))} {
	ic_show_geo_selected point $nnames 1 white 1
	mess "Part is not visible\n" red
	ic_show_geo_selected point $nnames 0
    }
	aie_update_curve_color_if_on
	#
	# Point name Rules:
	# 1. Point may be created as virtual point if vid_mode is On
	# 2. If "Replace" is On - delete item with name if exists
	# 3. If multiply points will be created - No replacement on the set
    set name [ic_vset -new_name $name all]	
}
#-----------------------------------------------------------
proc oncreatePointsDEZAfterOK {} {
    aie_create_parts_in_tree_if_needed 
    aie_update_icons geom
}
#--------------------------------------
proc onCreatePointsFamModify {dez val} {
    if {$val == "From screen"} {
		set p [geo_select_part_from_screen 1]
		set ::geo_part_name [aie_geo_set_part_name $p]
    }
}

proc oncreatePointsDEZLoad {} {
	global vid_options
	aie_default_topo_tolerance
	set show_name [aie_gui_get vid_options(show_item_name)]

	aie_show_name createPointsName $show_name
# do not select on first load: set invalid selection value
	if ![info exists createPointsEXGVal] {
	    set createPointsEXGVal 999
# Set some default dropdowns
	    if ![info exists createPnt2LocMethodVal] {set createPnt2LocMethodVal 1}
	    if ![info exists createPntCrvParMethodVal] {set createPntCrvParMethodVal 1}		
		
		
# * * * * * * * * * * * * * * *
# one-time settings:
# 		

	    set x 0; set y 0; set z 0
	    set dx 0; set dy 0; set dz 0
	    set ratio 0.5
	    set toler 0.1
	    set nPnt2Loc 1
	    set embedPntOnSurfFlag 0
	    set trimCrvPrjFlag 0
	    set crePnts3param 0.5
	    set which_end both
	    set how_select_end "both xmin xmax ymin ymax zmin zmax" 		
	    set fangle 30
	}
# * * * * * * * * * * * * * * * 
# settings for each PointsDEZLoad (usually - selection):
    
    set pickBasePnt ""
    set pickBetweenList ""
    set pickArcList ""
    set pickEndList ""
    set pickParList ""
    set pickIntList ""
    set pickParList ""
    set pickProjCrv ""
    set pickPoint ""
    set pickPoint2 ""
    set pickProjSrf ""
    set pickCircleList ""
    set pickSurf ""
    set pickSurfs ""
    set pickSurfsProj ""
    set pickCurvesProj ""
    set pickCurveConcat ""
    
    set movePointPrjFlag 0
    
    #---------------10
    
    set PartList [aie_list_parts 1]
    set ::geo_part_name [aie_geo_set_part_name]
    if {$name == ""} {set name pnt.00}
    set name [ic_vset -new_name $name all]	
    ::AIEnv::GUIManagement::ToggleGrey createPointsFam [aie_check_inherit_fam]
}

proc oncreatePointsDEZAfterLoad {} {
    ::AIEnv::GUIManagement::ToggleGrey movCrvPrjCk 0
}

proc oncreatePointsScrnLoad {} {
    if $auto_pick_mode {createPointsScrnWdgt pick}
}
 
proc oncreatePntExpresLoad {} {
    # Just an example
    if {![info exists crePntParamList] || ![llength $crePntParamList]} {
	set crePntParamList "-1, 1, 0.1"
	set Xexpress "2*sin(m*180)"
	set Yexpress "2*cos(m*180)"
	set Zexpress " m / 2"
    }
    #
    set cs [ic_csystem_get_current]
    set cstype car
    if {$cs != "global"} {
	set cstype [string range [ic_csystem_get $cs] 0 2] 
    }
    switch -- $cstype {
	car {set x_label X; set y_label Y;     set z_label Z}
	cyl {set x_label R; set y_label Theta; set z_label Z}
	sph {set x_label R; set y_label Theta; set z_label Phi}
	default { error "bad csystem type $cstype" }
    }		 
    aie_try_change_entry_label createPntExpres Xexpress F(m)->$x_label
    aie_try_change_entry_label createPntExpres Yexpress F(m)->$y_label
    aie_try_change_entry_label createPntExpres Zexpress F(m)->$z_label
    aie_try_change_entry_label createPntExpres x $x_label
    aie_try_change_entry_label createPntExpres y $y_label
    aie_try_change_entry_label createPntExpres z $z_label
    
}
#-----
proc oncreateCurvePickPick {} {
    global va_set coords vid_options
    set va_set(fam) $part_name
    if $::vid_options(replace) {
    set va_set(name) $name
    } else {
      set va_set(name) [va_auto_name curve $name $va_set(fam)]
    }  
    createCurvesDEZ set  name $va_set(name)
    set va_set(unset_list) do_when_create_xyz
    set va_set(do_when_create_xyz_start) ""	
    set va_set(do_when_create_xyz_continue) ""		
    set va_set(do_when_create_xyz_end) {
    {aie_temporary_reset_record off}
	{aie_check_inherit_fam va_set(fam) point $va_set(pnt_or_coords)}
	{ic_delete_geometry curve names $va_set(name) 0}
	{if {[llength $coords] > 1} {ic_curve points $va_set(fam) $va_set(name) $va_set(pnt_or_coords)}}			
	{createCurvesDEZ set pickList $va_set(pnt_or_coords)}		
	{aie_temporary_reset_record resume}		
    }
}
#-----
proc onmodFaceCrvPick_P0Pick {} {
    global va_set coords
    set entname [createFacetedDEZ get name]
    set va_set(fam) $::geo_part_name	
    if $::vid_options(replace) {
      set va_set(name) $name 
    } else {
    set va_set(name) [va_auto_name curve $entname $va_set(fam)]
    }
    createFacetedDEZ set name $va_set(name)
    set va_set(unset_list) do_when_create_xyz
    set va_set(do_when_create_xyz_start) ""	
    set va_set(do_when_create_xyz_continue) ""		
    set va_set(do_when_create_xyz_end) {
  	{aie_check_inherit_fam va_set(fam) point $va_set(pnt_or_coords)} 
	{ic_delete_geometry curve names $va_set(name) 0}
	{if {[llength $coords] > 1} {ic_geo_create_unstruct_curve_from_points $va_set(name) $va_set(fam) $va_set(pnt_or_coords)}}			
	{createFacetedDEZ set FacePtsList $va_set(pnt_or_coords)}
    }
    #    if $auto_pick_mode {createPoints3Base pick}
}
proc onmodFaceCrvPick_C1Finish {} {
    set FaceCrvList [aie_set_faceted 1 curve $FaceCrvList]
    if {$FaceCrvList == ""} return
    ic_highlight color "" names $FaceCrvList 
}

proc onmodNURBCrvPick_C3Finish {} {
    set NURBCrvList [aie_set_faceted 0 curve $NURBCrvList]
    if {$NURBCrvList == ""} return
    ic_highlight color "" names $NURBCrvList 
}
proc onmodNURBCrvPick_P3Finish {} {
    global va_set
    if {$NURBCrvList == ""} return
    if {$NURBPtsList == ""} return
    va_move_crvs_selected $NURBCrvList $NURBPtsList
    if $auto_pick_mode {modNURBCrvPick_P3 pick}	
}
proc onmodFaceCrvPick_P0Finish {} {
	if ![llength $FacePtsList] return
    if $auto_pick_mode {
	ic_delete_geometry curve names $name 0
	createFacetedDEZ apply
	modFaceCrvPick_P0 pick
    }
}
proc oncreatePointsDeltLoad {} {
		set cstype [lindex [ic_csystem_get [ic_csystem_get_current]] 0]
		switch $cstype {
			cylindrical  {
				aie_reset_picker "" createPoints0DX label "DR" 
				aie_reset_picker "" createPoints0DY label "DTheta"
			}
			cartesian {
				aie_reset_picker "" createPoints0DX label "DX"
				aie_reset_picker "" createPoints0DY label "DY"
			}
		} 
    if $auto_pick_mode {createPoints3Base pick}
}
#------
proc oncreatePointsCenLoad {} {
    if !$auto_pick_mode return
    if !$createPointsCentFRVal {
      createPointsCentWdgt pick
    } else {
        createPointsCentArcWdgt pick
    } 
}
#------
proc oncreatePointsVectLoad {} {
    if $auto_pick_mode {createPointsParamWdgt pick}
}
#------
proc oncreatePointCurvEndLoad {} {
    if $auto_pick_mode {createCurveEndsPick pick}
}
#---------------------------------5
proc oncreatePointInterLoad {} {
    if $auto_pick_mode {createCurveIntersecPick pick}
}
#----------------------------------------6
proc oncreatePointCurvParLoad {} {
    if $auto_pick_mode {createPointCurvePar pick}
}
#----------------------------------------7
proc oncreatePointCurvProjLoad {} {
    ::AIEnv::GUIManagement::ToggleGrey movCrvPrjCk 0
    if $auto_pick_mode {createCurveProjPick pick}
}
#----------------------------------------8
proc oncreatePointprojSurfLoad {} {
    if $auto_pick_mode {createPntOnSurfPick pick}
}
#----------------------------------------9

#-----------------------------------End of Auto Pick procedures in Point Creation-----------------------------

#------------------------------------Start of Auto Apply procedures in Point Creation--------------------------
proc oncreatePointsScrnWdgtFinish {} {
    if {($pickScreenList != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createPointsScrnWdgt pick
    }
}
#---------------------------------------------------------
proc oncreatePoints3BaseFinish {} {
    if {($pickBasePnt != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createPoints3Base pick
    }
}
#---------------------------------------------------------
proc oncreatePointsCentWdgtFinish {} {
    if {($pickCenterList != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createPointsCentWdgt pick
    }
}
#---------------------------------------------------------
proc oncreatePointsCentArcWdgtFinish {} {
    if {($pickCenterCrv != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createPointsCentArcWdgt pick
    }
}

#----------------------------------------------------------
proc oncreatePointsParamWdgtFinish {} {
    if {($pickBetweenList != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createPointsParamWdgt pick
    }
}
#----------------------------------------------------------
proc oncreateCurveEndsPickFinish {} {
    if {($pickEndList != "") && $auto_pick_mode } {
	createPointsDEZ apply
	createCurveEndsPick pick
    }
}
#----------------------------------------------------------
proc oncreateCurveIntersecPickFinish {} {
    if {($pickIntList != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createCurveIntersecPick pick
    }
}
#----------------------------------------------------------
proc oncreatePointCurveParFinish {} {
    if {($pickParList != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createPointCurvePar pick
    }
}
#---------------------------------------------------------
proc onpointPickFinish {} {
    if {($pickPoint != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createCurveProjPick pick
    }
}
#---------------------------------------------------------
proc oncreateCurveProjPickFinish {} {
    if {$pickProjCrv != ""} {
        if {[llength $pickProjCrv] > 1 } {
            ::AIEnv::GUIManagement::ToggleGrey movCrvPrjCk 1
            set movePointPrjFlag 0
        } else {
            ::AIEnv::GUIManagement::ToggleGrey movCrvPrjCk 0
        }
        if $auto_pick_mode { pointPick pick }
    } else {
        ::AIEnv::GUIManagement::ToggleGrey movCrvPrjCk 0
    }
}
#---------------------------------------------------------
proc onpointPick2Finish {} {
    if {($pickPoint2 != "") && $auto_pick_mode } {
        createPointsDEZ apply
        createPntOnSurfPick pick
    }
}
#---------------------------------------------------------
proc oncreatePntOnSurfPickFinish {} {
	set ::va_set(selected) $pickProjSrf
    if {($pickProjSrf != "") && $auto_pick_mode } {
	    pointPick2 pick
    }
}


proc onmodFaceCrv2PPickFinish {} {
	set modFaceVector [ic_vcalc dir [lindex $modFaceVector 0] [lindex $modFaceVector 1]]
}
proc onmodFaceSrf2PPickFinish {} {
	set modFaceVector [ic_vcalc dir [lindex $modFaceVector 0] [lindex $modFaceVector 1]]
}
#----------Invert-----------------
proc onmodCrvPick_0Finish {} {
	global va_set
	if ![llength $modCrv_crv0] return
	if ![info exists va_set(names_for_coords)] return
	# Exclude duplicated names 
	set modCrv_crv0 "" 
	foreach crv $va_set(names_for_coords) {
		if {[lsearch $modCrv_crv0 $crv] < 0} {
			lappend modCrv_crv0 $crv
		}
	}
	if $auto_pick_mode {
		createCurvesDEZ apply
		modCrvPick_0 pick
	}	
}
#--------Extend-----------
proc onmodCrvPick_1Finish {} {
	global va_set
	if [info exists va_set(names_for_coords)] {
		set modCrv_crv1 $va_set(names_for_coords)
	}
	if [info exists va_set(ends_for_coords)] {
		set modCrvExtEnd $va_set(ends_for_coords)
	}
	if {$auto_pick_mode && [llength $modCrv_crv1]} {
		# if location screen selection, select first
		switch $modCrvExtEndEGVal {
			0 {modCrvExtEndPick pick}
			1 {modCrvPick_C pick}
			2 {
			createCurvesDEZ apply
			modCrvPick_1 pick
		}
	}
	}
}
proc onmodCrvPick_CFinish {} {
	if {!$auto_pick_mode || ($CrvExtTo == "")} return
	createCurvesDEZ apply
	modCrvPick_1 pick
}
proc onmodCrvExtEndPickFinish {} {
	if {$auto_pick_mode && ($modCrvExtEndPnt != "")} {
		createCurvesDEZ apply
		modCrvPick_1 pick
	}
}	
#-------Fillet/Match--------	
proc onmodCrvPick_2Finish {} {
	global va_set
	if [info exists va_set(names_for_coords)] {
		set modCrv_crv2 $va_set(names_for_coords)
	}
	if [info exists va_set(ends_for_coords)] {
		set modCrvMatchEnd ""
		foreach e $va_set(ends_for_coords) {
			lappend modCrvMatchEnd [incr e]
		}
	}
	if {$auto_pick_mode && ([llength $modCrv_crv2] == 2)} {
		# if location screen selection, select first
		createCurvesDEZ apply
		modCrvPick_2 pick
	}
}

#----------Bridge-----------	
proc onmodCrvPick_3Finish {} {
	global va_set
	set modCrvBridgeEnd ""
	if [info exists va_set(names_for_coords)] {
		set modCrv_crv3_1 $va_set(names_for_coords)
	}
	if [info exists va_set(ends_for_coords)] {
		foreach e $va_set(ends_for_coords) {
			lappend modCrvBridgeEnd [incr e]
		}
	}
	if {$auto_pick_mode && ([llength $modCrv_crv3_1] == 2)} {
		# if location screen selection, select first
		createCurvesDEZ apply
		modCrvPick_3 pick
	}
}		
#=====================================================
# CURVES DEZ OK
#=====================================================
proc oncreateCurvesDEZOK {} {
    global geom_visible  fam_visible vid_options

    if [string match $::geo_part_name "From screen"] {
        mess "Error: wrong part name: \"$::geo_part_name\"\n" red
        return
    }
    if {![aie_check_inherit_fam] && [ic_hex_subset_named_selection $::geo_part_name]} {
        mess "Error: a named selection subset with name \"$::geo_part_name\" already exists; use some other part name\n" red
        return
    }
    
    set part_name [aie_geo_set_part_name $::geo_part_name]
    set part_name [aie_new_part $part_name]
    status_message ""
    set fam $part_name
    if {[ic_geo_is_loaded] == 0} ic_empty_tetin
    
    set nnames ""
    # mess "$radius,$stangle,$enangle" red
    if ![info exists createCurvesEXGVal] return
    switch -- $createCurvesEXGVal {
	0 {
		aie_check_inherit_fam fam point $pickList
		set newlist [va_check_data_set_points $pickList keep $fam $name.01]
		# curve may be created during "pick". Next line try delete such curve. 
		if {[ic_gui_set va_set(name)] == $name} {ic_delete_geometry curve names $name 0}
		set nnames [ic_curve point $fam $name $newlist]
	}
	1 {#create an arc by 3 expressions
		aie_check_inherit_fam fam point $pickArcList
		set list [va_check_data_set_points $pickArcList keep $fam $name.01]		
		if !$createCrvArcMethodVal {	
			set nnames [ic_curve arc $fam $name $list]
		} else {
		    if !$RadiusArcGGVal {
			    # radius will be calculated in ic_curve
			    set radius 0.0
		    }
		    lappend list $radius
		    if $keep_arc {
			    lappend list "" "" 1
		    } else {
			    lappend list "" "" 0
		    } 
			set nnames [ic_curve arc_ctr_rad $fam $name $list] 	
		}
	}
	2 {
			if {[llength $pickCircleList] != 3} return				
			aie_check_inherit_fam fam point $pickCircleList
			if !$RadiusGGVal {
				set radius [ic_vcalc distance [lindex $pickCircleList 0] [lindex $pickCircleList 1]]
			}
			set nnames [ic_curve arc_ctr_rad $fam $name "$pickCircleList $radius $stangle $enangle"] 
	}
	
	3 {
	    #create curve by copying an isoparamateric curve
		aie_check_inherit_fam fam surface $pickSurf
	    set surftype [ic_geo_get_object_type surface $pickSurf]
	    if {$surftype != "param"} {
		ic_mess "Error: Surface $pickSurf is not a BSpline surface\n" red
		return
	    }
	    set do_split 0
		ic_show_geo_selected surface $pickSurf 1
		set name [ic_vset -new_name $name all]
	    switch -- $creCurveEGVal {
		0 {
			if {[llength [va_check_data_set_points $pickCurvCrePnt keep $fam $name.00]] != 2} {
				ic_mess "Select two locations on the surface\n" red
				ic_show_geo_selected surface $pickSurf 0
				return
			}		
			va_set_fam_name_etc $fam $name 		
			set res [va_do_create_2pts_isocurve $pickCurvCrePnt $pickSurf]
			if ![va_is_int_or_real $res] {
				set nnames $res
			}	
		} 
		1 {
			if {[llength $pickEdgePnt] != 2 && [llength $pickEdgePnt2] != 1} return
			if {[llength $pickEdgePnt] == 2} {
			    foreach "u v" $pickEdgePnt ""
			    if {[expr abs($u-0.5)] > [expr abs($v-0.5)]} {
				    set u_or_v 1
			    } else {
				    set u_or_v 0
			    }
			    set isopar [lindex $pickEdgePnt $u_or_v]
			} elseif {[llength $pickEdgePnt2] == 1} {
			    set u_or_v {}
			    set isopar $pickEdgePnt2
			} else {
			    return
			}
			if [catch {ic_geo_cre_crv_iso_crv $fam $name $pickSurf $isopar $u_or_v $do_split 1} res] {
				mess "[lindex $res 0]" red
				busy reset
            } else {
			    set nnames [lindex $res 0]
                set srfs [lindex $res 1]
			}
			::AIEnv::GUIManagement::ToggleGrey pickEdgePnt 0
			::AIEnv::GUIManagement::ToggleGrey pickEdgePnt2 0
		}
		2 {
#		    mess "isopar:$isopar\n" blue
	    if ![va_is_int_or_real $isopar] {
			ic_mess "Error: define parameter\n" red 
			return
	    }	    
			if {$UVChoiceVal == 0} {
			    set u_or_v 1
			    } else {
			    set u_or_v 0
			}
			    if [catch {ic_geo_cre_crv_iso_crv $fam $name $pickSurf\
					   $isopar $u_or_v $do_split 0} res] {
				mess "[lindex $res 0]" red
				busy reset
			    } else {
				set nnames [lindex $res 0]
				set srfs [lindex $res 1]
		    }	    
		}  
	    }
		ic_show_geo_selected surface $pickSurf 0 
	}
	4 {
	    # create curve by Intersecting surfaces
	    # one set - method for 11270; only bsp_mode
	    if {$creCrvIntSetRVal < 2} {
		    busy 1
		    set vid_options(do_intersect_self_part) [expr !$diffPartsFlag]
            set fam_surfaces ""
            set nnames ""
            switch $creCrvIntSetRVal {
                0 {
                    set fam_surfaces $pickSetSurfs
                }
                1 {
                    foreach p $pickSetSurfs {
                        append fam_surfaces "[ic_geo_objects_in_family surface $p] "
                    }
                }
            }
            if {$fam_surfaces != ""} {
                aie_check_inherit_fam fam surface $fam_surfaces 
            }
            if $singleCurveFlag {
                set nnames [ic_geo_intersect_surfaces $fam $pickSetSurfs]
            } else {
		        set nnames [ic_curve intersect $fam $name $pickSetSurfs]
		    }
		    set pickSetSurfs ""
		    busy reset
	    } else { 
	        set mlt_mode ""
	        set bsp_mode ""
	        if {$createCurveIntCTVal == 1} {
		        # create bsplines; create multiple curves
		        set mlt_mode multi_crv
		        set bsp_mode use_bsp
	        }
	        if {$pickSet1Surfs == "" || $pickSet2Surfs == ""} {
		    status_message "Set two groups of surfaces\n" red
		    return		
		}
		set groups [list $pickSet1Surfs $pickSet2Surfs]
	    aie_check_inherit_fam fam surface [lindex $groups 0]
		busy 1
	    set err [catch {ic_geo_intersect_surfs_by_groups $groups $fam $bsp_mode $mlt_mode} res]
		busy reset
		if $err {
		    status_message "Error: $res\n" red
		    return
	    }
		set nnames $res
	    }
	}
	
	5 {
		
		if {$pickSurfsProj == "" || $pickCurvesProj == ""} return
		set nnames ""
		aie_check_inherit_fam fam surface $pickSurfsProj
		switch -- $createCrvProjMethodVal {
			0 {
				if $prTrFlag {
					set nnames [aie_project_crvs_and_trim_srfs $fam $pickCurvesProj $pickSurfsProj $name]
				} else {
					set nnames [ic_geo_project_curve_to_surface $pickCurvesProj $pickSurfsProj $name $fam 0 0]
			}
				if {$nnames == ""} return
				if {$prjOriginCurvFlag == 0} {
					ic_delete_geometry curve names $pickCurvesProj 0	
				}
			}
			1 {
				switch -- $createCrvPrjEGVal {
					0 {
						set vect1 {1 0 0}
					}
					1 {
						set vect1 {0 1 0}
					}
					2 {
						set vect1 {0 0 1}
					}
					3 {
						set vect1 [lindex [$tdv_default screen2world 100 100] 1]	
					}
					4 {
						foreach {p1 p2} $projpointsvec ""
						set vect1 [ic_vcalc diff $p1 $p2]
						if ![llength $vect1] {
	    					status_message "Error: Check Vector start/end points\n" red 
	    					return
    					}
					}
				}
				set bbox [$tdv_default bbox interesting]
			    if {$bbox == ""} return
				busy 1
				ic_undo_group_begin
				tdv_active 0
				# Get bounding box dimmensions
				# We want to transform the curves past the extent of the geometry
				set bboxpnt1 [lindex $bbox 0]
				set bboxpnt2 [lindex $bbox 1]
				set diagdist [ic_geo_pnt_dist $bboxpnt1 $bboxpnt2]
				set vctrscale [expr $diagdist / [ic_vcalc len $vect1]]
				set dscale0 [ic_vcalc smult $vect1 $vctrscale]
				set dscale1 [ic_vcalc smult $vect1 [expr $vctrscale * -1]]
     			set surfs $pickSurfsProj
     			foreach c $pickCurvesProj {
     			    set proj_nm $c
   				    set py_nm [ic_geo_duplicate curve $proj_nm ""]
   				    set py_mm [ic_geo_duplicate curve $py_nm ""]
   				    ic_move_geometry curve names $py_nm translate $dscale0
   				    ic_move_geometry curve names $py_mm translate $dscale1
   				    set newname [ic_geo_new_name surface SURF//]
   				    set intersurf [ic_geo_create_surface_from_curves SURF $newname $::geo_cad(toler) "$py_nm $py_mm"]
   				    ic_geo_object_visible surface $intersurf 0
   				    set intercrv ""
				    set crvinter ""
   				    foreach surf $surfs {
       			        set res [ic_geo_intersect_surfaces $part_name "$intersurf $surf"]
					    foreach nm $res {
						    set n [va_auto_name curve $name]
						    lappend crvinter [ic_geo_set_name curve $nm $n]
					    }		
       			        if {$crvinter != ""} {
	     			        set segmcrvs [ic_geo_create_curve_segment $crvinter connect]
	     				    # 59988: ic_geo_create_curve_segment may return "" if no new curves;
	     				    # In this case append $crvinter
	     				    if {$segmcrvs == ""} {
	     				  	    set segmcrvs $crvinter
	     				    }
         				    append intercrv " $segmcrvs"
         				    lappend intersrf $surf
         			    }
     			    }
     			    if {$intersurf != ""} {
   				        ic_delete_geometry surface names $intersurf 0
   				    }
   				    ic_delete_geometry curve names "$py_nm $py_mm" 0
  				    if {$intercrv != ""} {
	  				    if {$prjOriginCurvFlag == 0} {
						    ic_delete_geometry curve names "$proj_nm"	
					    }
  				    }
				    if $prTrFlag {
					    set nnames [aie_project_crvs_and_trim_srfs $fam $intercrv $pickSurfsProj $name 0]
				    }
        		    if [llength $nnames] {
				        if {$prjOriginCurvFlag == 0} {
					        ic_delete_geometry curve names $c 0	
				        } else {
				  	        ic_delete_geometry curve names $intercrv 0
				        }
			        }
			    }
        		busy 0
				ic_undo_group_end
				tdv_active 1
				mess "Done projecting curve on surface\n"
    		}
		}
	}
	6 {
	    set crvs ""
	    foreach c $pickCurveSeg {
		if {[ic_geo_check_objects_exist curve $c] == ""} {
		    continue
		} else {
		    lappend crvs $c
		}
	    }
	    if ![llength $crvs] return
	    
	    switch -- $modifyCurveSegFRVal {
		0 {
			set nnames [ic_curve split $fam $name "$pickCurveSeg $pickPointSeg"]
		    set pickCurveSeg ""	
		    set pickPointSeg ""			
		}
		1 {
			if {$pickCurveSeg == $pickCurveSegWith} {
					ic_mess "Cannot self-segment curves\n"
					return
				}				
			set crvs "$pickCurveSeg $pickCurveSegWith"
			foreach crv $crvs {
				if ![llength [ic_geo_check_objects_exist curve $crv]] {
					ic_mess "Select curves\n"
					return
				}
			}
			set tol $::geo_cad(toler)
			set p_part [ic_geo_get_family curve [lindex $crvs 0]]
			set p_part2 [ic_geo_get_family curve [lindex $crvs 1]]
			set pts [ic_geo_create_points_curveinter $crvs $tol $p_part]
			if {$pts == ""} {
				foreach "len1 len2" [ic_geo_crv_length $crvs] ""
				if {$len1 > $len2} { set tol $len1} else {set tol $len2}
				set pts [ic_geo_create_points_curveinter $crvs $tol $p_part]
				if {$pts == ""} {
					ic_mess "No intersection found\n"
					return
				}
			}
			set ppts ""
			set ppts2 ""
			foreach pnt $pts {
				set xyz [ic_geo_get_point_location $pnt]
				set p [ic_geo_project_coords curve $pickCurveSeg  $xyz {0 0 0}]
				if ![va_is_triplet $p] continue 
				set pname [ic_vset -new_name $name.00 all]
				lappend ppts [ic_geo_cre_pnt $p_part $pname $p]
				if {$segBothFlag == 1} {
				    set p2 [ic_geo_project_coords curve $pickCurveSegWith  $xyz {0 0 0}]
				    if ![va_is_triplet $p2] continue 
					set pname [ic_vset -new_name $name.01 all]				    
				    lappend ppts2 [ic_geo_cre_pnt $p_part2 $pname $p2]
				}
			}
			set err [catch {ic_geo_split_curve $pickCurveSeg  $ppts} res]
			if !$err {set nnames $res}
			if {$segBothFlag == 1} {
			    set err [catch {ic_geo_split_curve $pickCurveSegWith $ppts2} res]
			    if !$err {append nnames " $res"}
			}
			ic_delete_geometry point names $pts 0	
			if {![info exists vid_options(auxiliary)] || !$vid_options(auxiliary)} {
				ic_delete_geometry point names "$ppts $ppts2" 0
			}	
		}
		2 {
		    #segment by plane
		    if {$modSegmCRVNormEGVal == 3} {
			if {$segVecList == ""} {mess "Warning:Point is not defined!" red;return}
			set SegPlanePList [lindex $segVecList 0]
		    } else {
			if {$SegPlanePntList == ""} {mess "Warning:Point is not defined!" red;return}
			set SegPlanePList $SegPlanePntList
		    }
		    
		    if {[llength $SegPlanePList]==1} {
			set plane_pnt [ic_geo_get_point_location $SegPlanePList]
		    } else {
			set plane_pnt $SegPlanePList
		    }                      
		    #mess "segment by the point: $plane_pnt\n" blue
		    #mess "  SegPlanePntList $SegPlanePntList    segVecList $segVecList  SegPlanePList $SegPlanePList \n"             
		    switch -- $modSegmCRVNormEGVal {
			0 {set plane_n [aie_get_csystem_direction X]}
			1 {set plane_n [aie_get_csystem_direction Y]}
			2 {set plane_n [aie_get_csystem_direction Z]}
			3 {set plane_n [ic_vcalc dir [lindex $segVecList 0] [lindex $segVecList 1]] }
		    }   
		    #mess "plane_p $plane_pnt plane_n $plane_n\n" blue
		    set seg_crvs ""
			busy 1
		    foreach c $crvs {
			switch -- [ic_geo_get_object_type curve $c] {
				param {
		    		set fac [ic_facetize_geometry curve $c]
					set facs [ic_geo_create_curve_segment $fac plane plane_p $plane_pnt plane_n $plane_n keep_old 0]				
					if {$facs == ""} {
						ic_delete_geometry curve names $fac 0
					} else {
						ic_delete_geometry curve names $c 0
					}
					set res ""
					foreach f $facs {
						set faclen [ic_geo_crv_length $f]
						set thetol [expr 0.001*$faclen]
						set newc [ic_geo_modify_curve_reappr $f $thetol 0]
						if {$newc == ""} continue
						set cname [ic_vset -new_name $name.00 all]
						lappend res [ic_geo_set_name curve $newc $cname]	
					}		
				}
			    mesh {
				set res [ic_geo_create_curve_segment $c plane plane_p $plane_pnt plane_n $plane_n keep_old 0]

			    }
			}
				lappend seg_crvs $res
			    }
			busy 0
		    if {$seg_crvs != "" && $seg_crvs != "{}"} {
				set nnames $seg_crvs
			} else {
				mess "Cannot split curve with selected plane\n" red 
			}            
		}
		3 {
		    #segment by connectivity
			busy 1
		    foreach c $crvs {
			set type [ic_geo_get_object_type curve $c]
			if {$type == "param"} {
			    mess "This function is only valid for faceted curves. Skipping $c\n" red
			    continue
			}
			ic_geo_create_curve_segment $c connect keep_old $keepOriginCurvFlag
		    }
			busy 0
		}
		
		4 {
		    #segment by angle
			busy 1
		    foreach c $crvs {
			set type [ic_geo_get_object_type curve $c]
			if {$type == "param"} {
			    mess "This function is only valid for faceted curves. Skipping $c\n" red
			    continue
			}
			ic_geo_create_curve_segment $c angle angle $seg_angle2 minedge $minSeg2 keep_old $keepOriginCurvFlag
		    }
			busy 0
		}
	    }
	}
        
	7 {
		
	    aie_check_inherit_fam fam curve $pickCurveConcat
	    switch -- $modifyReapproxCrvVal {
		0 {
			# concatenate: must be more than one curve
			if {[llength $pickCurveConcat] < 2} {
				status_message "Select 2 or more curves" red
				return
			}
		    aie_check_inherit_fam fam curve $pickCurveConcat
		    set type [ic_geo_get_object_type curve $pickCurveConcat]
		    switch -- $type {
			param { 
				if $creCrvConcatTolGGVal { 
			    if ![va_is_int_or_real $ctol] {
				ic_mess "Error: define tolerance\n" red 
				return
			    }	  	    
			    if [catch {ic_geo_cre_crv_concat $fam $name $ctol $pickCurveConcat} res] {
				busy reset
				mess "$res\n" red
			    } else {		
				mess "Created concatinated curve, $res\n"
				ic_delete_geometry curve names $pickCurveConcat
				mess "Deleted old curves: $pickCurveConcat\n"
				set nnames $res
				set pickCurveConcat ""
			    }
			    } else {
					ic_curve concat $fam $name $pickCurveConcat
				}
			}
			mixed {
			    mess "You have mixed Bspline and Faceted Curves.\n"
			    mess "Please convert all curves to faceted to use this options\n"
			    set pickCurveConcat ""
			    return
			}
			mesh {
			    set master [lindex $pickCurveConcat 0] 
			    set rest [lreplace $pickCurveConcat 0 0]
			    ic_geo_merge_objects curve $master $rest
			    #		    ic_geo_merge_nodes_tol curve $master $ctol
			    ic_delete_geometry curve names $rest
			    ic_geo_finish_edit curve $master
			    ic_geo_set_family curve $fam names $master
			    set pickCurveConcat ""
			    return
			}
		    }
		}
		1 {
		    if {$reappcrvfacetedFlag} {set pickCurveReapp [ic_get_facets curve $pickCurveReapp]}
		    if {$pickCurveReapp == ""} {mess "No curves selected" red; return}
		    if {$ctol1 == ""} {mess "Please enter the tolerance" red; return}
		    ic_geo_modify_curve_reappr $pickCurveReapp $ctol1 0
		    if $auto_pick_mode {set pickCurveReapp ""}
		}
		2 {
		    if {$pickCurveHull == ""} {mess "No curves selected" red; return}
		    set debug 0
		    aie_check_inherit_fam fam curve $pickCurveHull
		    set hull [ic_hull_2d $pickCurveHull $hull_tol $four "curve" $shrink $debug]
	            if {$hull != ""} {ic_geo_set_family curve $fam names $hull}
		    if $auto_pick_mode {set pickCurveHull ""}
		}
	    }
	}
	8 {
	    if {$pickCurveExtract == ""} return
	    set param_surfs ""
	    set mesh_surfs ""
	    foreach i $pickCurveExtract {
		set type [ ic_geo_get_object_type surface $i]
		if { $type == "mesh" } {
		    lappend mesh_surfs $i
		} elseif { $type == "param" } {
		    lappend param_surfs $i
		} else {
		    mess "unhandled surface type $type, skipping\n"
		}
	    }
	    
	    set new_crvs ""
	    if { $mesh_surfs != "" } {
		switch -- $boundary {
		    Both {set bb 2}
		    Interior {set bb 0}
		    Exterior {set bb 1}
		    default {set bb 2}
		}
		foreach obj $mesh_surfs {
		    set new [ic_geo_extract_curves $obj $bb $fangle $MinSeg]
			if {$new == ""} {
				ic_mess "Cannot extract $boundary curve for angle=$fangle\n" red
			} else {
				lappend new_crvs $new
			}
		}
	    }
	    if { $param_surfs != "" } {
			# keep part & names for existing edges!
			if [info exists tmp_arr] {unset tmp_arr}
			foreach srf $param_surfs {
				foreach crv [ic_geo_get_srf_edges $srf] {
					set tmp_arr($crv) $srf
				}
			}
			set crvs [ic_geo_create_surface_edges $param_surfs]
		    foreach crv $crvs {
				if ![info exists tmp_arr($crv)] {
					lappend new_crvs $crv
				}
			}			
			# check topology for new curves if extract_bsp_how == 0
			if {$extract_bsp_how == 0 && [llength $new_crvs]} {
				ic_build_topo $::geo_cad(toler) -surfaces $param_surfs -curves $new_crvs		
				# some curves may be deleted
				set nlist ""
				foreach na $new_crvs {
					if [llength [ic_geo_check_objects_exist curve $na]] {
						lappend nlist $na
					}
				}
				set new_crvs $nlist
			} elseif {$extract_bsp_how == 1} {			
			# copy existing if extract_bsp_how == 1
			    foreach crv [array names tmp_arr] {			
					set cp_name [ic_vset -new_name $crv all]
					set na [ic_geo_duplicate curve $crv $cp_name]
					set sfam [ic_geo_get_family surface $tmp_arr($crv)]
					ic_geo_set_family curve $sfam names $na
					lappend new_crvs $na
				}
			}	
	    }
	    # Note: Edges were inherit. Change if not
	    if ![aie_check_inherit_fam] { 
		set nnames [aie_set_part_and_new_names curve $new_crvs $fam $name]
	    } else {
			set nnames $new_crvs
	    }
	    set pickCurveExtract ""
	}
	9 { # dpar is a "parametrical distance" between additional points on curve 
		# limit radius with, say 10000 pixels
		# Inherit ???
		global va_set tdv_default
		set dpar 0.01
		set Rmax [ic_vcalc len [lindex [$tdv_default screen2world 10000 0] 0]] 

		switch -- $modCrvEGVal {
			0 {
			foreach crv $modCrv_crv0 {
			# check for user wrong input:	
				if {[ic_geo_check_objects_exist curve $crv] == ""} continue 
				ic_geo_reverse_crv	$crv
			}
			status_message "Done reverse: $modCrv_crv0"
			}	
			1 {
				set add_crv ""
				if ![llength $modCrv_crv1] return
				set e $modCrvExtEnd 
				if !$modCrvExtEndEGVal {
				# Method ->2 points on curve + selected
					if ![llength $modCrvExtEndPnt] {
						mess "Select End curve location\n"
						return
					}
					set sel $modCrvExtEndPnt
					set pts [aie_get_locations_on_crv $modCrv_crv1 $e 2 $dpar]
					set p0 [lindex $pts 0]
					set p1 [lindex $pts 1]
					set cent [aie_get_3pnt_center $p0 $p1 $sel]
					if ![llength $cent] {
						ic_mess "Wrong selection\n" red
						return
					}
					set add_pnt [aie_get_3pnt_arc_pnt $cent $sel $p0 $p1]
					set add_crv [ic_geo_cre_arc_from_pnts $fam tmpcrv	$sel $add_pnt $p0]
				} elseif {$modCrvExtEndEGVal == 2} {
				# Method ->3 points on curve + Length
					if ![va_is_int_or_real $modCrvExtLen] {
						mess "Set Length\n"
						return
					}
					#May be "arc" or "line"  
					if {$modCrvExtMethod == "line"} {
					set pts [aie_get_locations_on_crv $modCrv_crv1 $e 2 $dpar]
					set p0 [lindex $pts 0]
					set dir [ic_vcalc dir [lindex $pts 1] $p0]
					set vec [ic_vcalc smult $dir $modCrvExtLen]
					set add_pnt [ic_vcalc sum $p0 $vec]
					set add_crv [ic_geo_cre_bsp_crv_n_pnts $fam tmpcrv [list $p0 $add_pnt] $::geo_cad(toler)]
					} 
					if {$modCrvExtMethod == "arc"} {
					set pts [aie_get_locations_on_crv $modCrv_crv1 $e 3 $dpar]
					set p0 [lindex $pts 0]
					set p1 [lindex $pts 1]
					set p2 [lindex $pts 2]
					set cent [aie_get_3pnt_center $p0 $p1 $p2]
					if ![va_is_triplet $cent] {
						set modCrvExtMethod "line"
						mess "Extending with line\n"
						createCurvesDEZ apply
						return
					} 
					set rad  [ic_vcalc distance $cent $p0]
					# if curve is ~line switch to line 
					if {$rad > $Rmax} {
						set modCrvExtMethod "line"
						mess "Extending with line\n"
						createCurvesDEZ apply
						return
					}
					set dir0 [ic_vcalc dir $cent $p0]
					set dir1 [ic_vcalc dir $cent $p1]
					set nrm  [ic_vcalc nrm [ic_vcalc product $dir0 $dir1]]
					set dir1 [ic_vcalc nrm [ic_vcalc product $dir0 $nrm]]
					ic_csystem_create extcsy cylindrical $cent $dir0 $dir1 $nrm

					set ang  [expr $modCrvExtLen*180/$va_set(M_PI)/$rad]
					if {$ang > 360} {
						set ang 180
						set modCrvExtLen [expr $va_set(M_PI)*$rad]
					}
					set add_pnt [ic_coords_into_global "$rad $ang 0" extcsy]
					set ang [expr $ang/2.0]
					set add_p2 [ic_coords_into_global "$rad $ang 0" extcsy]
					set add_crv [ic_geo_cre_arc_from_pnts $fam tmpcrv $add_pnt $add_p2 $p0]
					ic_csystem_delete extcsy					
					}
				} else {
			return [ic_curve extend_trim $fam $name [list $modCrv_crv1 $CrvExtTo $modCrvExtEnd $allowExtendTargetFlag]]		
				}
				if {$add_crv == ""} return
				set err [catch {ic_geo_cre_crv_concat $fam tmp 0.0 "$add_crv $modCrv_crv1"} nname]
				if $err {
					ic_delete_geometry curve names $add_crv 0
				} else { 
				set c $modCrv_crv1
				ic_delete_geometry curve names "$add_crv $c"
				ic_geo_set_name curve $nname $c
                set len [ic_geo_crv_length $c]
			    set ctol [expr 0.01*$len]
                if {$modCrvExtMethod == "line" && $ctol > [aie_default_topo_tolerance]} {
                    set ctol [aie_default_topo_tolerance]
                }
			    set newn [ic_geo_modify_curve_reappr $c $ctol 0]
				}
				set CrvExtTo ""
			}	
			2 {
			# This is an interface to AWM' ic_geo_mod_crv_match
			# Explicit set of parameters; modify as necessary... 
			if {([llength $modCrv_crv2] != 2) || ([llength $modCrvMatchEnd] != 2)} return
			# 02/08/07 VG: 45191: reapproximate mesh curves (if any) using tolerance = 0.01 of curve length
			foreach c $modCrv_crv2 {
			    if {[ic_geo_get_object_type curve $c] == "mesh"} {
			        set len [ic_geo_crv_length $c]
			        set ctol [expr 0.01*$len] 
					    set newn [ic_geo_modify_curve_reappr $c $ctol 0]
					    ic_geo_set_name curve $newn $c
					}
			}	
			set m0 $modCrvMatchMethodEGVal
			set m1 $modCrvMatchAcc
			set m2 1
			set m3 $modCrvMatchOneOrBoth
			set m4 0
			set e0 [lindex $modCrvMatchEnd 0]
			set e1 [lindex $modCrvMatchEnd 1]
			set c0 [lindex $modCrv_crv2 0]
			set c1 [lindex $modCrv_crv2 1]
			if {$c1 == $c0} {
				mess "One curve, $c0, was selected twice\n" red
				return
			}
			set ee0 [expr $e0-1]
			set ee1 [expr $e1-1]
			set ps [lindex [ic_geo_get_crv_pos $ee0 $c0] 0]
			set pe [lindex [ic_geo_get_crv_pos $ee1 $c1] 0]
			if $modCrvKeepFlag {
				if [catch {ic_geo_duplicate curve $c0} new_crv] {
				    mess "Could not duplicate curve $c0\n" red
				    return
				} else {
				    set c0 $new_crv
				}
				#
				if [catch {ic_geo_duplicate curve $c1} new_crv] {
				    mess "Could not duplicate curve $c1\n" red
				    return
				} else {
				    set c1 $new_crv
				}
			}
			set res [catch {ic_geo_mod_crv_match_crv $c0 $c1 $e0 $e1 "$m0 $m1 $m2 $m3 $m4"} msg]
			if $res {
				mess "Match error: $msg\n"
				return
			}
	# ic_geo_mod_crv_match_crv can create new curves or modify existing (depends on end points status).
	# checking result:
	foreach crv $msg {
	  if {[lsearch "$c0 $c1" $crv] >= 0} continue
	  # replace $c0 OR $c1 with $crv based on names match
	  set ncn [string length $crv]
	  set maybe_c0 1
	  set maybe_c1 1
	  for {set i 0} {$i < $ncn} {incr i} {
	    set c [string index $crv $i]
	    set cc0 [string index $c0 $i]
	    if {$cc0 != $c} {set maybe_c0 0;break}
	    set cc1 [string index $c1 $i]	    
	    if {$cc1 != $c} {set maybe_c1 0;break}
	  }
	  if $maybe_c0 {    
				ic_delete_geometry curve names $c0 0
				ic_geo_set_name curve $crv $c0
		} else {
				ic_delete_geometry curve names $c1 0
				ic_geo_set_name curve $crv $c1
		}
			}				
			set nnames "$c0 $c1"
			
			}
			3 {
			if {([llength $modCrv_crv3_1] != 2) || \
				([llength $modCrvBridgeEnd] != 2) } {
				mess "Press \"Chooser\" button and select 2 curves\n" red
				return
			}
			#  
			set curve1 [lindex $modCrv_crv3_1 0]
			set curve2 [lindex $modCrv_crv3_1 1]		
			set modCrv_crv3_1 ""		
			set end1 [lindex $modCrvBridgeEnd 0] 
			set end2 [lindex $modCrvBridgeEnd 1] 
			
			set ee1 [expr $end1-1]
			set ee2 [expr $end2-1]
			set ps [lindex [ic_geo_get_crv_pos $ee1 $curve1] 0]
			set pe [lindex [ic_geo_get_crv_pos $ee2 $curve2] 0]
			if {[ic_vcalc distance $ps $pe] < 0.001} {
				ic_mess "Selected ends are too close\n" red
				return
			}
			
			global va_set
			set va_set(brcrv) [ic_geo_cre_bridge_crv $fam $name $curve1 $curve2 $end1 $end2 .5 .5 ]
			
			set va_set(prtname) $part_name
			set va_set(crv1) $curve1
			set va_set(crv2) $curve2
			set va_set(end1) $end1
			set va_set(end2) $end2
			
			
				
			}
			4 {
			if {([llength $modCrv_crv4_1] != 2) || \
				([llength $modCrvBridgeEnd] != 2) } {
				mess "Press \"Chooser\" button and select 2 curves\n" red
				return
			}
			foreach "crv1 crv2" $modCrv_crv4_1 ""
			foreach "end1 end2" $modCrvBridgeEnd ""
			set ps [lindex [ic_geo_get_crv_pos $end1 $crv1] 0]
			set pe [lindex [ic_geo_get_crv_pos $end2 $crv2] 0]
			if {[ic_vcalc distance $ps $pe] < 0.001} {
				ic_mess "Selected ends are too close\n" red
				return
			}
			set n 1
# ic_geo_cre_bsp_crv_n_pnts_cons works for one point
			if {$modCrv_pnt4_2 == ""} {
				ic_mess "Select one point\n"
				return
			}
			set pnts [list $ps]
#			foreach p $modCrv_pnt4_2 {
#				lappend pnts $p
#			}
			lappend pnts $modCrv_pnt4_2 
			lappend pnts $pe

			incr n
			set v1 [ic_geo_get_crv_tan $end1 $crv1]
			set v2 [ic_geo_get_crv_tan $end2 $crv2]
			# change direction if necessary to opposite
			if !$end1 {
				set v1 [ic_vcalc smult $v1 -1]
			}
			if $end2 {
				set v2 [ic_vcalc smult $v2 -1]
			}
			set vects [list $v1 $v2]  
			#  
			ic_geo_cre_bsp_crv_n_pnts_cons $fam $name $pnts "all" $vects "0 $n"
			
			}
		}	
	}
        10 {
	        set ctol1 $::geo_cad(toler)
            set param_curves ""
            set mesh_curves ""
            switch -- $createCrvMidMethodVal {
                0 {
                    aie_check_inherit_fam fam curve $pickMidline_crv2
                    if [catch {ic_geo_cre_midline_crv $pickMidline_crv2 $ctol1 0 "" $fam} res] {
                        mess "$res\n" red
                    } else {
                        if {$::vid_options(show_item_name) == "1" && $name != ""} {
                             set name [ic_geo_set_name curve $res "$name" 1 0]
                             set res $name
                        }
                        mess "Created midline curve $res\n"
                        set pickMidline_crv2 ""
                    }
                }
		        1 {
			        aie_check_inherit_fam fam curve $midlineList
			        if [catch {ic_geo_cre_midline_crv $midlineList $ctol1 0 $midlineList2 $fam} res] {
				        mess "$res\n" red
			        } else {
                        if {$::vid_options(show_item_name) == "1" && $name != ""} {
                            set name [ic_geo_set_name curve $res "$name" 1 0]
                            set res $name
                        }
				        mess "Created midline curve $res\n"
				        set midlineList ""
				        set midlineList2 ""
			        }
		        }
	        }
	        
        }

         11 {
               aie_check_inherit_fam fam surface $pickSurfSect
	       switch $sectCurvePlaneEGVal {
                   0 {
                       switch $sectCurvePlaneXYZEGVal {
                           0 {
				set vec {1 0 0} 
				set vindex 0
                           }
			   1 {
				set vec {0 1 0} 
				set vindex 1
			   }
			   2 {
				set vec {0 0 1} 
				set vindex 2
                           }
			}			       
			set start_point {0 0 0}
			if $sectCurveOffsetGGVal {
			    # Create Multiply
			    if {$mpsectstart != ""} {
			        set start_point $mpsectstart
			    }
			    if  {$mpsectend != ""} {
				set end_point $mpsectend
			    } else {
				set end_point $start_point
			    }
			    set cutlist [list $start_point]
			    if ![va_is_int_or_real $mpsectdelta] {
                                set mpsectdelta 0
			    }
			    set distance [ic_vcalc distance $start_point $end_point]	
			    if {($distance > 0) && ($mpsectdelta > 0)} {
				set n [expr int($distance / $mpsectdelta) + 1]
				if {$n > 100} {
				    ic_mess "Reduce offset: too many crossections ($n)\n" red
				    return
				}
				set diff [ic_vcalc diff $start_point $end_point]
				set ratio [expr $mpsectdelta / $distance]
				set add_vector [ic_vcalc smult $diff $ratio]
				for {set i 1} {$i < $n} {incr i} {
				    set start_point [ic_vcalc sum $start_point $add_vector]
				    lappend cutlist $start_point
				}
			    } 
			} else {
			    set cutlist [list "0 0 0"]
			}
			foreach cut $cutlist {	
	   		    foreach surf $pickSurfSect {
                                if {[ic_geo_check_objects_exist surface $surf] == ""} continue
				set na [va_auto_name curve $name] 
	   			ic_geo_cre_surface_section $fam $na $surf 0 $cut $vec
		   	    }
	   		}			       
		    }
		    1 {  
			if {$sectCurveplnpnt1 == "" || $sectCurveplnpnt2 == "" || $sectCurveplnpnt2 == "" } {return}
	   		foreach surf $pickSurfSect {
                            if {[ic_geo_check_objects_exist surface $surf] == ""} continue
	   		    ic_geo_cre_surface_section $fam $name $surf 0 $sectCurveplnpnt1  $sectCurveplnpnt2 $sectCurveplnpnt3
		   	}
		   						       
		    }
		    2 {
			if {$numsect == ""} {
			    mess "Please specify number of sections\n"
			    return
			}
			#If one section specified, create it in the middle.
			#Otherwise, do $number_of_sections - 1 to hit end and begging of curve
     		        set locations ""
			if {$numsect == ""} {return}
			    if {$numsect <= 1} {
			        set locations .5
		    	    } else {
			       	set incrm [expr 1.0 / [expr $numsect -1]]
			       	for {set step 0} {$step <= [expr $numsect-1]} {incr step} {
				    set place [expr $step * $incrm]
				    set locations [linsert $locations end $place]
   			    	}  
			    }
			    set pickcrvexist_exits ""
			    foreach c $pickcrvexist {
			    	if {[ic_geo_check_objects_exist curve $c] == ""} continue
				lappend pickcrvexist_exits $c
			    }
			    set pickcrvexist $pickcrvexist_exits
			    foreach  param $locations {
				set loc [lindex [ic_geo_get_crv_pos $param $pickcrvexist] 0]
				set vec [ic_geo_get_crv_tan $param $pickcrvexist]
				ic_undo_group_begin
				tdv_active 0
	   			foreach surf $pickSurfSect {
                                    if {[ic_geo_check_objects_exist surface $surf] == ""} continue
	   			    ic_geo_cre_surface_section $part_name $name $surf 0 $loc $vec
		   		}	
		   		tdv_active 1		       
 	       			ic_undo_group_end
		   	    }
	   		}
        	}
        
        }       
    }

    # Just flash the curve ...
    if { $nnames != "" && (([info exists fam_visible($fam)] && !$fam_visible($fam)) || !$geom_visible(curve))} {
        ic_show_geo_selected curve $nnames 1 white 1
        mess "Part is not visible\n" red
        ic_show_geo_selected curve $nnames 0
    }
    # update curve color if "On"
	aie_update_curve_color_if_on
    aie_updateGeoVis curve 1 1
    if [llength $nnames] {status_message "Done:curves $nnames"} else {
		set ::select_action cancel
	}
    if {$name == ""} {set name crv.00}
    set name [ic_vset -new_name $name all]	
}
#------------------------------------------------
proc oncreateCurvesDEZAfterOK {} {
    aie_create_parts_in_tree_if_needed 
    aie_update_icons geom
}
#------------------------------------------------
proc onCreateCurvesFamModify {dez val} {
    if {$val == "From screen"} {
		set p [geo_select_part_from_screen 1]
		set ::geo_part_name [aie_geo_set_part_name $p]
    }
}
#----------------------------------------------------------
proc oncreateCurvesDEZLoad {} {
    aie_default_topo_tolerance
    aie_show_name createCurvesName [aie_gui_get vid_options(show_item_name)]	
# do not select on first load: set invalid selection value
    if ![info exists createCurvesEXGVal] {
	    set createCurvesEXGVal 999
# * * * * * * * * * * * * * * *
# one-time settings:
#  (GUI will keep last value)  
	    set prjOriginCurvFlag 1	
        set radius 0
        set stangle 0
        set enangle 360
        set isopar 0.5
	    set UVChoiceVal 0
        set udirFlag 1  
        set vdirFlag 0
		set ctol 0.1
		set ctol1 0.1
		set hull_tol $::geo_cad(toler)
		set shrink 0.2
		set four 0
#  ---- end #9 ----
		set modcurvExatrctEGVal 2; #set default to interior and exterior both
		set crvExtrctAng 20
		set crvExtrctMinSeg 1
		set seg_angle2 20
		set minSeg2 1
		set segrmflag 1
	# for curve projection onto a surface
		set vecdirFlag 0
		set fangle 20								
		set modCrvExtEnd 1							
		set	modCrvEGVal 0
		set modCrvExtMethod line							
	}
# * * * * * * * * * * * * * * * 
# settings for each CurvesDEZLoad (usually - selection):
#	
    set pickList ""
    #---for circle of radius and 3 points
    set pickCircleList ""
    #---3 isopar curves
    set pickEdgePnt ""
    set pickEdgePnt2 ""
    ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt 0
    ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt2 0
    
    if ![info exists creCurveEGVal] {set creCurveEGVal 2}

    set pickSurf ""
    #---2
    set pickSet1Surfs ""
    set pickSet2Surfs ""
    set singleCurveFlag 0
    #----4
    set pickSurfsProj ""
    set pickCurvesProj ""

    #----
    set pickCurveSeg ""
    set pickPointSeg ""
    # 7----
    set pickCurveConcat ""
    set pickCurveReapp ""
    set pickCurveHull ""

    # 9 ---------------modify/create faceted curve
	set modCrvMatchEnd "1 1"
	if ![va_is_int_or_real $modCrvExtLen] {set modCrvExtLen 1}
	if ![info exists modCrvMatchMethodEGVal] {set modCrvMatchMethodEGVal 2}
	set modCrvMatchOneOrBoth 0
	if {![info exists modCrvMatchAcc] || ($modCrvMatchAcc != "2")} {
		set modCrvMatchAcc 1
	}
	set CrvExtTo ""
	set ::va_set(c1mag) .500
	set ::va_set(c2mag) .500	

    # 10 ----
    set pickMidline_crv2 ""
    set midlineList ""
    set midlineList2 ""
    #---
    # for curve projection onto a surface
    set PartList [aie_list_parts 1]
    set part_name [aie_geo_set_part_name]
    if {$name == ""} {set name crv.00}
    set name [ic_vset -new_name $name all]	
    ::AIEnv::GUIManagement::ToggleGrey createCurvesFam [aie_check_inherit_fam]
    set pickSurfSect ""
}

proc oncreateCurvesDEZAfterLoad {} {
    # After windows are created (first time):
    if ![info exists CurvesAfterLoadInit] {
        aie_reset_picker "" modCrvPick_0 image select_curve_dir$icon_size1.gif helptext "Select curves to reverse"
        aie_reset_picker "" modCrvPick_1 image select_curve_dir$icon_size1.gif helptext "Select curve to extend"
        aie_reset_picker "" modCrvPick_2 image select_curve_dir$icon_size1.gif helptext "Select curves to match"
        aie_reset_picker "" modCrvPick_3 image select_curve_dir$icon_size1.gif helptext "Select curves to bridge"
        aie_reset_picker "" modCrvPick_C helptext "Select target curve"
        set CurvesAfterLoadInit 999
    }	
}

proc oncreateSurfsDEZAfterLoad {} {
    # After windows are created (first time):
    if ![info exists SurfsAfterLoadInit] {
        aie_reset_picker "" ExtSrfImageP image select_exclude_extension$icon_size1.gif helptext "exclude from extension"
        aie_reset_picker "" ExtSingleCrv image select_edge_curve_extend$icon_size1.gif helptext "select surface edge curves to include in extension"    
		aie_reset_picker "" StdPlanePick image select_curve_loc$icon_size1.gif helptext "Select location on curve"
		aie_reset_picker "" StdDiscPick image select_curve_loc$icon_size1.gif helptext "Select location on curve"
		aie_reset_picker "" TrimPlaneCurve image select_curve_loc$icon_size1.gif helptext "Select location on curve"
        set SurfsAfterLoadInit 999
    }
    if {[trace vinfo mode] != ""} {
        trace vdelete mode w aie_create_surfs_trace_how_modes
    }
    trace variable mode w aie_create_surfs_trace_how_modes
    aie_create_surfs_trace_how_modes "" "" ""
}

proc aie_create_surfs_trace_how_modes {name element op} {
    switch [createSurfsDEZ get mode] {
        "Confirm" - "Present/Confirm" {
	    ::AIEnv::GUIManagement::ToggleGrey createPartMidPartial 1
	    ::AIEnv::GUIManagement::ToggleGrey createSurfMidPartial 1
	}
	"Quiet" {
	    ::AIEnv::GUIManagement::ToggleGrey createPartMidPartial 0
	    ::AIEnv::GUIManagement::ToggleGrey createSurfMidPartial 0
	}
    }
}

proc aie_create_surfs_trace_partial_offset {name element op} {
    global beta_mode
    if {$beta_mode} {
        switch [createSurfsDEZ get offsetFlag] {
            0 {
	        ::AIEnv::GUIManagement::ToggleGrey createPairMidPartial 0
            }
            1 {
                ::AIEnv::GUIManagement::ToggleGrey createPairMidPartial 1
            }
        }
    }
}
proc oncreateCurvesDEZUnLoad {} {
	global va_set
	set va_set(brcrv) ""
	if [info exists va_set(img)] {
		catch {$va_set(img) delete}
		unset va_set(img)
	}
}

proc oncreCrvIntSet1Finish {} {
    if ![llength $pickSetSurfs] return 
    set surfaces ""
    foreach s $pickSetSurfs {
        if {[ic_geo_check_objects_exist surface $s] == ""} continue
        append surfaces " $s"
    }
    set pickSetSurfs $surfaces
}

#---------------------------------------Start of Auto Pick in Curve Creation Procedure-----------------------
proc oncreateCrvPntsLoad {} {
    if $auto_pick_mode {createCurvePick pick}
}

#-----------------------------0
proc oncreateCrvArcLoad {} {
    if $auto_pick_mode {createArcWdgt0 pick}
}

#------------------------------1
proc oncreateCrvCicleLoad {} {
    if $auto_pick_mode {createPointsCircleWdgt pick}
}

#------------------------------2
proc oncreateCrvMethodsLoad {} {
    if !$auto_pick_mode return 	
	switch $creCurveEGVal {
		0 {pickSrfIsoCurve0 pick}
		1 {pickSrfIsoCurve1 pick}
		2 {pickSrfIsoCurve2 pick}
	}   
}

#-------------------------------3
proc oncreateIsoUVpickPick {} {
    set ::va_set(selected) $pickSurf
	ic_show_geo_selected surface $pickSurf 1
}

proc onpickEdgePntPick {} {
    set ::va_set(selected) $pickSurf
}

proc onpickEdgePnt2Pick {} {
    set ::va_set(selected) $pickSurf
}

proc onpickSrfIsoCurve0Finish {} {
	if ![llength $pickSurf] return 
	set surftype [ic_geo_get_object_type surface $pickSurf]
	if {$surftype != "param"} {
		ic_mess "Error: Surface $pickSurf is not a BSpline surface\n" red
		ic_show_geo_selected surface $pickSurf 0
		set pickSurf ""
		return
	}
	if !$auto_pick_mode return		
	createIsoUVpick pick
	if {$creCurveEGVal == 1} {pickEdgePnt pick}
}

proc onpickSrfIsoCurve1Finish {} {

	if ![llength $pickSurf] return 
	set surftype [ic_geo_get_object_type surface $pickSurf]
	if {$surftype != "param"} {
		ic_mess "Error: Surface $pickSurf is not a BSpline surface\n" red
		ic_show_geo_selected surface $pickSurf 0
		set pickSurf ""
		return
	}
	if !$auto_pick_mode return
	pickEdgePnt pick
	if ![llength $pickEdgePnt] {
	    ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt 1
	    ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt2 0
	    pickEdgePnt2 pick
	}
}

proc onpickSrfIsoCurve2Finish {} {
	if {![llength $pickSurf] || !$auto_pick_mode} return
	createCurvesDEZ apply
	pickSrfIsoCurve2 pick
}

proc onpickEdgePntFinish {} {
    if [llength $pickEdgePnt] {
        ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt2 1
        set pickEdgePnt2 ""
    } else {
        ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt2 0
    }
	if {[llength $pickEdgePnt] && $auto_pick_mode} {
		createCurvesDEZ apply
		pickEdgePnt pick
	} else {
	 	ic_show_geo_selected surface $pickSurf 0
	}	
} 

proc onpickEdgePnt2Finish {} {
    if [llength $pickEdgePnt2] {
        ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt 1
        set pickEdgePnt ""
    } else {
        ::AIEnv::GUIManagement::ToggleGrey pickEdgePnt 0
    }
	if {[llength $pickEdgePnt2] && $auto_pick_mode} {
		createCurvesDEZ apply
		pickSrfIsoCurve1 pick
	} else {
	 	ic_show_geo_selected surface $pickSurf 0
	}	
} 


proc oncreateIsoUVpickFinish {} {
	if {[llength $pickCurvCrePnt] && $auto_pick_mode} {
		createCurvesDEZ apply
        createIsoUVpick pick
	} else {
	 	ic_show_geo_selected surface $pickSurf 0
    } 
} 

proc oncreateCrvInterLoad {} {
    if $auto_pick_mode {
		switch $creCrvIntSetRVal {
			2 {createCurveIntSet1 pick}
			1 {creCrvIntSetP1 pick}
			0 {creCrvIntSet1 pick}
		}			
    }
}

#------------------------------4
proc oncreateCrvProjLoad {} {
    if $auto_pick_mode {createCurvProj pick}
}

#-------------------------------6
proc oncreateCrvSegmentLoad {} {
    if ![info exists keepOriginCurvFlag] {set keepOriginCurvFlag 0}
    switch -- $modifyCurveSegFRVal {
	0 {if $auto_pick_mode {modifyCurvSeg pick} }
	1 {if $auto_pick_mode {modifyCurvSegcrv1 pick} }
	2 {if $auto_pick_mode {modifyCurvSeg2 pick} }
	3 {if $auto_pick_mode {modifyCurvSeg3 pick} }
	4 {if $auto_pick_mode {modifyCurvSeg4 pick} }
    }
}

#-------------------------------7
proc oncreateCrvConcatLoad {} {
    if $auto_pick_mode {
        switch -- $modifyReapproxCrvVal {
	    0 {modifyCurvConcat pick}
	    1 {reapproxCrv pick}
	    2 {reapproxCrvHull pick}
        }
    }
}

#-------------------------------7
proc oncreateCrvExtractLoad {} {
    set BList [list Interior Exterior Both]
    set boundary Both
    if {$MinSeg == ""} {set MinSeg 0}
    if $auto_pick_mode {createBoundCurves pick}
}

proc onmodCrv_3Load {} {
	global va_set
	set va_set(brcrv) ""	
}

#-------------------------------10
proc oncreateMidCrvLoad {} {
    # there are two options:
    if $auto_pick_mode {
	    if !$createCrvMidMethodVal {
            MidLinePick pick
        } else {
            createCrvMidSetPick1 pick
        }
    }
}

#-----------------------------------------------End of Auto Pick for Curve Creation Procedure------------------
#-------------------------------Start of Auto Apply for Curve Creation Procedure-------------------------------

proc oncreateCurvePickFinish {} {
	global vid_options
	if {![llength $pickList]} {
		return
	}
        createCurvesDEZ apply
    if $auto_pick_mode {   
	createCurvePick pick
    }
}
#-------------------------------------0
proc oncreateArcWdgt0Finish {} {
    if {($pickArcList != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	if {$::select_action == "cancel"} return
	createArcWdgt0 pick
    }
}
#-------------------------------------0
proc oncreateArcWdgt1Finish {} {
    if {($pickArcList != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	createArcWdgt1 pick
    }
}
proc oncreateArcWdgt2Finish {} {
    if {($pickArcList != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	createArcWdgt2 pick
    }
}
#--------------------------------------1
proc oncreatePointsCircleWdgtFinish {} {
    if {($pickCircleList != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	createPointsCircleWdgt pick
    }
}
#--------------------------------------2

proc oncreateCurveIntSet1Pick {} {
    mess "Selecting Set1 surfaces\n" blue
}

proc oncreateCurveIntSet2Pick {} {
    mess "Selecting Set2 surfaces\n" blue
}

proc oncreateCurveIntSet1Finish {} {
    if {($pickSet1Surfs != "") && $auto_pick_mode} {
	    createCurveIntSet2 pick
    }
}

proc oncreateCurveIntSet2Finish {} {
    if $auto_pick_mode {
	    createCurvesDEZ apply
	    createCurveIntSet1 pick
    }
}
#---------------------------------------4
proc oncreateCurvProjFinish {} {
    if {($pickCurvesProj != "") && $auto_pick_mode} { 
	    createSurfProj pick
    }
}

#---------------------------------------4
proc oncreateCurvProjvecFinish {} {
    if {($pickCurvesProj != "") && $auto_pick_mode} { 
	    createSurfProjvec pick
    }
}
#---------------------------------------5
proc oncreateSurfProjvecFinish {} {
    if {($pickSurfsProj != "") && $auto_pick_mode} {
	    if {$createCrvProjMethodVal == 0} {
	        createCurvesDEZ apply
	        createCurvProjvec pick
	    }
    }
}
#---------------------------------------5
proc oncreateSurfProjFinish {} {
    if {($pickSurfsProj != "") && $auto_pick_mode} {
	    createCurvesDEZ apply
	    createCurvProj pick
    }
}
#---------------------------------------6
proc onmodifyCurvPntFinish {} {
    if {($pickPointSeg != "") && $auto_pick_mode} {
	    createCurvesDEZ apply
	    modifyCurvSeg pick
    }
}
#---------------------------------------7
proc onmodifyCurvSegFinish {} {
    if {($pickCurveSeg != "") && $auto_pick_mode} {
	modifyCurvPnt pick
    }
}
proc onmodifyCurvSegcrv1Finish {} {
    if {($pickCurveSeg != "") && $auto_pick_mode} {
	modifyCurvSegcrv2 pick
    }	
}
proc onmodifyCurvSegcrv2Finish {} {
    if {($pickCurveSegWith != "") && ($pickCurveSeg != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	modifyCurvSegcrv1 pick

#		if $multiselectflag {
#			createCurvesDEZ apply
#			modifyCurvSegcrv2 pick
#		} else {
#			createCurvesDEZ apply
#			modifyCurvSegcrv1 pick
#		}
		
    }	
}
proc onmodifyCurvSeg2Finish {} {
    if {($pickCurveSeg != "") && $auto_pick_mode} {
	#	createCurvesDEZ apply
	#	modifyCurvSeg2 pick
    }
}
proc onmodifyCurvSeg3Finish {} {
    if {($pickCurveSeg != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	modifyCurvSeg3 pick
    }
}
proc onmodifyCurvSeg4Finish {} {
    if {($pickCurveSeg != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	modifyCurvSeg4 pick
    }
}
#---------------------------------------8
proc onmodifyCurvConcatFinish {} {
    switch -- $modifyReapproxCrvVal {
	0 {
	    if {($pickCurveConcat != "") && $auto_pick_mode} {
		createCurvesDEZ apply
		modifyCurvConcat pick
	    }
	}
	1 {
	    if {($pickCurveReapp != "") && $auto_pick_mode} {
		createCurvesDEZ apply
		reapproxCrv pick
	    }
	}
	2 {
	    if {($pickCurveHull != "") && $auto_pick_mode} {
		createCurvesDEZ apply
		reapproxCrvHull pick
	    }
	}
    }
}

#---------------------------------------
proc oncreateBoundCurvesFinish {} {
    if {($pickCurveExtract != "") && $auto_pick_mode} {
	createCurvesDEZ apply
	createBoundCurves pick
    }
}

#---------------------------------------9
proc onmodifyCurvFinish {} {
    createCurvesDEZ apply
}
#---------------------------------------10
proc onMidLinePickFinish {} {
    if {($pickMidline_crv2 != "") && $auto_pick_mode} {
        createCurvesDEZ apply
	MidLinePick pick
    }
}
proc oncreateCrvMidSetPick1Finish {} {
    if {($midlineList != "") && $auto_pick_mode} {
		createCrvMidSetPick2 pick
	}
}
proc oncreateCrvMidSetPick2Finish {} {
    if {($midlineList2 != "") && $auto_pick_mode} {
		createCurvesDEZ apply
		createCrvMidSetPick1 pick
	}
}	 
#---------------------------------------11

proc onsectCurveUnload {} {
	global va_set
	set pickSurfSect ""
	if [info exists va_set(img)] {
		catch {$va_set(img) delete}
		unset va_set(img)
	}
}

proc onsectCurvethrpntLoad {} {
    global auto_pick_mode

	::AIEnv::GUIManagement::ToggleGrey sectCurveMDelta 1
	::AIEnv::GUIManagement::ToggleGrey sectMstrtPick 1
	::AIEnv::GUIManagement::ToggleGrey sectMfinPick 1
	::AIEnv::GUIManagement::ToggleGrey sectCurveMulti 1
	::AIEnv::GUIManagement::ToggleGrey sectCurveOffsetGG 1    
    
    if $auto_pick_mode {	
		sectCrvplanepntp1Pick pick
		sectCrvplanepntp2Pick pick
		sectCrvplanepntp3Pick pick
	}
}

proc onsectCurvethrpntUnload {} {
	global va_set
	::AIEnv::GUIManagement::ToggleGrey sectCurveOffsetGG 
	if [info exists va_set(img)] { 
		catch {$va_set(img) delete}
		unset va_set(img)
	}
}


proc onsectCrvplanepntp1PickPick {} {
	global va_set tdv_default
	
	foreach p {1 2 3} {
		set xyz [createCurvesDEZ get sectCurveplnpnt$p]
		set va_set(pln_pnt$p) [ic_coords_into_global $xyz]
	}
	
	aie_cr_geom_plane threepoints 1

}

proc onsectCrvplanepntp2PickPick {} {
	global va_set tdv_default
	
		foreach p {1 2 3} {
		set xyz [createCurvesDEZ get sectCurveplnpnt$p]
		set va_set(pln_pnt$p) [ic_coords_into_global $xyz]
	}
	
	aie_cr_geom_plane threepoints 2

}

proc onsectCrvplanepntp3PickPick {} {
	global va_set tdv_default
	
	foreach p {1 2 3} {
		set xyz [createCurvesDEZ get sectCurveplnpnt$p]
		set va_set(pln_pnt$p) [ic_coords_into_global $xyz]
	}
	
	aie_cr_geom_plane threepoints 3

}

proc onsectCurvealngLoad {} {
	::AIEnv::GUIManagement::ToggleGrey sectCurveMDelta 1
	::AIEnv::GUIManagement::ToggleGrey sectMstrtPick 1
	::AIEnv::GUIManagement::ToggleGrey sectMfinPick 1
	::AIEnv::GUIManagement::ToggleGrey sectCurveMulti 1
	::AIEnv::GUIManagement::ToggleGrey sectCurveOffsetGG 1
	
	if $auto_pick_mode {	
		sectCurveExstPick pick
	}
			
}

proc onsectCurvealngUnload {} {			
	::AIEnv::GUIManagement::ToggleGrey sectCurveOffsetGG 
}


#=============================
proc oncreateTrimPlane_CLoad {} {
global auto_pick_mode
# part_name not available for this proc
# Must be new name, otherwice may delete existing 
set w ::AIEnv::DEZ::createSurfsDEZ::
foreach n {part_name name} {set $n [set ${w}$n]}
set ${w}name [va_auto_name surface $name $part_name]
	if $auto_pick_mode {
		TrimPlaneSurf pick
	}
}
#-------------------------------------
proc oncreateSurStdShapeLoad {} {
if {[info exists createStdShapeEGVal] && $createStdShapeEGVal == 6} {
	oncreateTrimPlane_CLoad
}
set StdHoleCrvList ""
set StdHoleSurfList ""
set StdHoleLocList ""
}
proc onrepairSurfaceUntrimLoad {} {
	if $auto_pick_mode {
		repairSurfacePickTrimmed pick
	}
}				
proc onrepairSurfacePickTrimmedFinish {} {
	if ![llength $TrimSurfs] return
	if $auto_pick_mode {
		createSurfsDEZ apply
		repairSurfacePickTrimmed pick
	}
}

#---------------------------------------
proc onTrimPlaneSurfFinish {} {
	if ![llength $TrimPlaneSurfList] return
	if $auto_pick_mode {
		TrimPlaneCurve pick
	}
}
proc onTrimPlaneCurveFinish {} {
     if {$auto_pick_mode && $StdPlaneCurveParam != "" && $TrimPlaneCurveList != "" && $TrimPlaneSurfList != ""} {
		createSurfsDEZ apply
		TrimPlaneCurve pick
	}	
}

proc onStdDiscPickFinish {} {
     if {$auto_pick_mode && $StdPlaneCurveParam != "" && $TrimPlaneCurveList != "" && $StdPlaneRadius != ""} {
#		createSurfsDEZ apply
#		StdDiscPick pick
	}	
}

proc onStdPlanePickFinish {} {
     if {$auto_pick_mode && $StdPlaneCurveParam != "" && $TrimPlaneCurveList != "" && $StdPlaneSide != ""} {
#		createSurfsDEZ apply
#		StdPlanePick pick
	}	
}
#---------------------------------------10
proc onModifyCurveDEZLoad {} {
    # for Curve End Tolerance
    set tolCurveEnd 0.1
}

proc onModifyCurveLoad {} {
	global va_set
    # for Curve End Tolerance
    set va_set(brcrv) ""
}

proc onModifyCurveUnload {} {
	global va_set
    # for Curve End Tolerance
    set va_set(brcrv) ""
}
proc oncreateMultipleSrfsLoad {} {
  set curveList all
  mess "    Press Apply to create surfaces.
    Curves must be in XY-plane (any Z).
    Surface quality for concave boundaries may be poor.
    Function does not require build topology in advance. 
    New curves and points will be created if there are curves intersections.   
    Curves selection \"all\" or \"\" will use all curves and build topology automatically after surfaces creation.   
    Checkbutton \"Set Part based on Shape\" set parts based on number of \"edges\". Edge may include several curves. 
    " red
 }

proc oncreateSurfsDEZOK {} {
    global convex_hull tdv aie_geoTypeVis geom_visible fam_visible
    global file_name interrupt_pending vid_options
    global tdv_default va_set beta_mode

    status_message ""
    if {[string match $::geo_part_name "From screen"] && $createSurfsEXGVal != 5} {
        mess "Error: wrong part name: \"$::geo_part_name\"\n" red
        return
    }
    if {![aie_check_inherit_fam] && [ic_hex_subset_named_selection $::geo_part_name]} {
        mess "Error: a named selection subset with name \"$::geo_part_name\" already exists; use some other part name\n" red
        return
    }
    
    set part_name [aie_geo_set_part_name $::geo_part_name]
    # A blank part name for midsurfacing means auto-assign
    if {$createSurfsEXGVal != 5} {
        set fam [aie_new_part $part_name]
    } else {
        set fam $part_name
    }
    set build_topo 0
    if {[info exists vid_options(new_srf_topo)] && $vid_options(new_srf_topo)} {
        set build_topo 1
    }
    set do_home [expr ![ic_geo_is_loaded] && ![ic_uns_is_loaded]]
    
    # set geom_visible(surface) 1
    # set aie_geoTypeVis(surface) 2
    # aie_updateGeoVis surface
    
    #    mess "Which function:$createSurfsEXGVal\n"
    set nnames ""
    if ![info exists createSurfsEXGVal] { createSurfsDEZ setdirty; return }
    
    catch { array unset pfam }
    switch -- $createSurfsEXGVal {	
	0 {
	    switch $createSurfSimpleMethodVal {
	        0 {
	            aie_check_inherit_fam fam curve $curveList
	            set nnames [ic_surface 2-4crvs $fam $name [list $createSrfTol $curveList]] 
	        }
		1 {
		    ic_vset composite_tolerance $createSrfTol
		    aie_check_inherit_fam fam curve $curveList
		    set nnames [ic_surface bsinterp $fam $name  $curveList]			
		}
		2 {
		    aie_check_inherit_fam fam point $Simple4ptsList
		    set newlist [va_check_data_set_points $Simple4ptsList keep $fam $name.01]
		    set nnames [ic_surface 4pts $fam $name  $newlist]
		}	    
		3 {
		    # return number of new surfaces
		    # family and names must be discussed
		    if ![llength $curveList] {
		      set curveList all
			    set n_del [ic_delete_geometry surface all] 
				  mess " $n_del surfaces deleted\n" red        
		     }
		    set nnames [ic_surface multiple $fam $name [list $curveList $Mult1Pnt 1 0]]			
		}		
		    
	    }
	}	
	1 {
	    # surface creation by a driving curve (curve-driven surface)
	    busy 1
	    aie_check_inherit_fam fam curve "$curveDrivenList $curveDrivingList"
	    foreach crv $curveDrivenList {
		if [catch {ic_geo_cre_srf_crv_drv_srf $fam $name $crv $curveDrivingList $build_topo} srf] {
		    mess "Failed to create surface: $srf\n" red
		    break
		} else {
		    lappend nnames $srf
		}
	    }
            if {$nnames != ""} { ic_reinit_geom_objects }
	    busy 0
	    mess "Created a curve driven-surface surface: $nnames \n"
	}	
	2 {
	    aie_check_inherit_fam fam curve $curveSweepList
	    if !$createSurfSweepMethodVal {  
	        # surface creation by Sweep Method
	        # First find a translation vector from point 1 to 2
	        set pt1 [lindex $pntSweepVecList 0]
	        set pt2 [lindex $pntSweepVecList 1]
	        set vector [ic_vcalc diff $pt1 $pt2]
	        if {$vector == ""} { return }
	        if [catch {ic_geo_cre_srf_sweep $fam $name $curveSweepList $vector 1} res] {
		        mess "$res \n" red
	        } else {
		        mess "created a sweep surface, $res , by sweeping $curveSweepList\n"
		        set nnames $res
	        }
	    } else {
		    if {![llength $crvSweepDList] || ![llength $curveSweepList]} { return }
		    ic_undo_group_begin
		    if [catch {ic_geo_cre_srf_sweep $fam $name $curveSweepList $crvSweepDList 1} res] {
		        mess "$res \n" red
		        ic_undo_group_end; aie_undo
		    } else {
		        ic_undo_group_end
		    }
	    }
	    set curveSweepList ""
    }
	3 {
	    # surface creation by revolve
	    aie_check_inherit_fam fam curve $curveRevList
	    if ![va_is_int_or_real $sangle] {
		ic_mess "Error: define StartAngle parameter\n" red 
		return
	    }
	    if ![va_is_int_or_real $eangle] {
		ic_mess "Error: define EndAngle parameter\n" red 
		return
	    }
	    if {([llength $curveRevAxis] != 2) || ![llength $curveRevList]} {
		ic_mess "Error: select Axis Points and Curves\n" red 
		return
	    }					  	    
	    set base [lindex $curveRevAxis 0]
	    set axis [lindex $curveRevAxis 1]
	    set zaxis [ic_vcalc dir $base $axis]
	    if [catch {ic_geo_cre_srf_rev $fam $name $curveRevList $base $zaxis $sangle $eangle c 1} res] {
		mess "Error: Surface of revolution failed\n $res" red
		busy reset
	    } else {
		set nnames $res
	    }	    
	    set curveRevList ""
	}
	4 {
	    if ![va_is_int_or_real $lofttol ] {
		ic_mess "Error: define tolerance\n" red 
		return
	    }
	    aie_check_inherit_fam fam curve $loftsurfList
	    set n_start_eq_end 0
	    foreach crv $loftsurfList {
		set e0 [lindex [ic_geo_get_crv_pos 0 $crv] 0]
		set e1 [lindex [ic_geo_get_crv_pos 1 $crv] 0]
		# lofttol used to check distance between end points. May be independent value, say, 0.001.
		if {[ic_vcalc distance $e0 $e1] < $lofttol} {incr n_start_eq_end}
	    }
	    if $n_start_eq_end {
		ic_mess "Warning: $n_start_eq_end curves have common start/end points.\n" red
	    }
	    set cross_order [expr (2-$loftLinearFlag)*2]
	    if [catch {ic_geo_cre_srf_loft_crvs $fam $name $lofttol $loftsurfList $cross_order $loftBlendFlag $loftBTopoFlag} res] {
		mess "Error: $res\n" red
	    } else {
		mess "Created loft surface $res"
		set nnames $res
            }
        }
	5 {
	    if ![va_is_int_or_real $offsetdist ] {
		ic_mess "Error: define Distance parameter\n" red 
		return
	    }	   
	    if {$offsetSurfList == ""} {
		mess "No surfaces selected\n" red
		return
	    }
	    # surface creation by Offset
	    foreach surf $offsetSurfList {
		set surftype [ic_geo_get_object_type surface $surf]
		if {$surftype != "param"} {
		    msg ERROR "Offset method works only for Bspline surfaces.\nSurface: $surf is not a Bspline surface"
		}
	    }
	    aie_check_inherit_fam fam surface $offsetSurfList    
	    #set newname {ic_geo_cre_srf_offset $fam $name $offsetSurfList $offsetdist}
            if !$beta_mode { set stFlag 0 }
	    busy 1            
	    if [catch {ic_geo_cre_srf_offset $fam $name $offsetSurfList $offsetdist 0 $stFlag} res] {
                mess "Error: $res\n"
                busy reset
            } else {
                mess "Surface, $res, offset by $offsetdist from base surface $offsetSurfList\n"
                set nnames $res
            }
            busy 0
        }
        6 {
            # surface creation by Midsurface needs: max dist, family, surfaces mode is False
            if {![va_is_int_or_real $distance ] || ($distance < 0)} {
                ic_mess "Error: define Distance parameter\n" red 
                set distance 0
            }
            set ppp $partialFlag
            if {[info exists offsetFlag]} {
                set ooo $offsetFlag
            } else {
                set ooo 0
            }
            if {$createSurfMidMethodVal == 2} {
                #
                #   By Pairs
                #
                set nummode 0
            } else {
                set ooo 0
                switch -- $mode {
                    Quiet {set nummode 0}
                    Confirm {set nummode 1; set ppp 0}
                    Present/Confirm {set nummode 2; set ppp 0}
                }
            }
            set args "save_old $keepFlag ask $nummode precision 0 tolerance $::geo_cad(toler)"
            lappend args partial $ppp
            if {$ooo != 0} {
                lappend args partial $ppp offset $ooo
            }
            if {$createSurfMidMethodVal != 2} {
                #
                #   By Surfaces or By Parts
                #
                lappend args max_dist $distance similar $similarFlag
                lappend args prefer_connected $connectedFlag
            }
            mess "\nTopology tolerance used: $::geo_cad(toler)\n"
            catch {unset exist_already}
            set interrupt 0
            set res 0
            switch -- $createSurfMidMethodVal {
                0 {
                    #
                    #   By Parts
                    #
                    set midsurfacesList ""
                    set new_cv 0
                    foreach part $partsurfList {
                        set surfs [ic_geo_get_objects surface $part]
                        if ![llength $surfs] {
                            mess "There are no surfaces in part $part\n"
                            continue
                        }
                        set midsurfacesList [concat $midsurfacesList $surfs]
                        foreach s $surfs {set exist_already($s) 1}
                        set sf ""
                        if [aie_check_inherit_fam] { set sf $s }
                        set old_behavior 1
                        if $assemblyFlag {
                            if {!$old_behavior && $fam != ""} {
                                set mid_part $fam/MIDS
                            } else {
                                set mid_part $part/MIDS
                            }
                        } else {
                            if {$fam != ""} {
                                set mid_part $fam
                            } else {
                                set mid_part $part
                            }
                        }
                        if [aie_check_inherit_fam] {
                            if {$sf != ""} {
                                if $assemblyFlag {
                                    set mid_part [ic_geo_get_part surface $sf]/MIDS
                                } else {
                                    set mid_part [ic_geo_get_part surface $sf]
                                }
                            }
                        } else {
                            set mid_part [aie_new_part $mid_part]
                        }
                        set args2 $args
                        lappend args2 family $mid_part surfaces $surfs
                        createSurfsDEZ setclean
                        createSurfsDEZ setclean_others
                        #lappend args2 no_busy 1
                        if [catch {eval ic_geo_midsurface $args2 } res] {
                            mess "$res\n" red
                        } else {
                            if {[regexp Interrupted $res]} {
                                set interrupt 1
                            }
                            if $assemblyFlag {
                                if {$res > 0} {
                                    if $keepFlag {
                                        if {!$old_behavior && $fam != ""} {
                                            set orig_part $fam/ORIG
                                        } else {
                                            set orig_part $part/ORIG
                                        }
                                        set part_color_orig [family_color_for_name $part]
                                        aie_new_part $orig_part
                                        ic_rename_family $part $orig_part
                                        aie_color_part $orig_part $part_color_orig
                                    } else {
                                        aie_new_part $part/UNRESOLVED
                                        ic_rename_family $part $part/UNRESOLVED
                                    }
                                    aie_color_part $mid_part [family_color_for_angle $new_cv]
                                    incr new_cv 100
                                }
                            } else {
                                foreach s [ic_geo_get_objects surface $fam] {
                                    if ![info exists exist_already($s)] {
                                        lappend nnames $s
                                    }
                                }
                            }
                        }
                        createSurfsDEZ setdirty
                        createSurfsDEZ setdirty_others
                        busy 0
                        ic_geo_set_modified 1
                        if $interrupt break
                    }
                }
                1 {
                    #
                    #   By Surfaces
                    #
                    set midsurfacesList $midsurfList
                    # To get newly created surfaces
                    foreach s [ic_geo_get_objects surface $fam] {
                        set exist_already($s) 1
                    }
                    set fam [aie_geo_set_part_name $::geo_part_name]
                    if [aie_check_inherit_fam] {
                        set fam ""
                    }
                    lappend args family $fam surfaces $midsurfList
                    #lappend args no_busy 1
                    createSurfsDEZ setclean
                    createSurfsDEZ setclean_others
                    if [catch {eval ic_geo_midsurface $args} res] {
                        mess "$res\n" red
                    } else {
                        foreach s [ic_geo_get_objects surface $fam] {
                            if ![info exists exist_already($s)] {
                                lappend nnames $s
                            }
                        }
                        ic_geo_set_modified 1
                    }
                    if {[regexp Interrupted $res]} {
                        set interrupt 1
                    }
                    createSurfsDEZ setdirty
                    createSurfsDEZ setdirty_others
                    busy 0
                }
                2 {
                    #
                    #   By Pairs
                    #
                    set midsurfacesList [concat $midsurfList $midsurfList2]
                    # To get newly created surfaces
                    foreach s [ic_geo_get_objects surface $fam] {
                        set exist_already($s) 1
                    }
                    set fam [aie_geo_set_part_name $::geo_part_name]
                    if [aie_check_inherit_fam] {
                        set fam ""
                    }
                    lappend args family $fam surfaces $midsurfList surfaces2 $midsurfList2
                    #lappend args no_busy 1
                    createSurfsDEZ setclean
                    createSurfsDEZ setclean_others
                    if [catch {eval ic_geo_midsurface $args} res] {
                        mess "$res\n" red
                    } else {
                        foreach s [ic_geo_get_objects surface $fam] {
                            if ![info exists exist_already($s)] {
                                lappend nnames $s
                            }
                        }
                        ic_geo_set_modified 1
                    }
                    if {[regexp Interrupted $res]} {
                        set interrupt 1
                    }
                    createSurfsDEZ setdirty
                    createSurfsDEZ setdirty_others
                    busy 0
                }
            }
            if {$res > 0 && !$keepFlag && $interrupt == 0} {
                set still_valid_surfs ""
                foreach s $midsurfacesList {
                    if [llength [ic_geo_check_objects_exist surface names $s]] {
                        lappend still_valid_surfs $s
                    }
                }
                set unmoved_surfaces [ic_surface_thickness_check $still_valid_surfs "" 1]
                set hc [llength $unmoved_surfaces]
                if $hc {
                    ic_highlight color white names $unmoved_surfaces width 3
                    set x [tk_dialog .unmoved_surfs "Some original surfaces still exist" \
                          "$hc original surface(s) found. What do you want to do?" "" -1 "Create Subset" "Delete" "Cancel" ]
                    ic_highlight color "" names $unmoved_surfaces 
                    switch -- $x {
                        -1 { if [winfo exists .unmoved_surfs] { top_destroy .unmoved_surfs } }
                        0 {
                            set ll ""
                            foreach l $unmoved_surfaces {lappend ll surface $l}
                            set name ORIG_MIDSURFACES
                            mess "Put [llength $unmoved_surfaces] surfaces in subset $name\n" blue
                            ic_geo_subset_add_items $name $ll
                            ::AIEnv::GUIManagement::Tree::AddGroup geom_subset $name 1
                            ::AIEnv::GUIManagement::Tree::ToggleGroupVisibility geom_subset $name same
                        }
                        1 {
                            ic_delete_geometry surface names $unmoved_surfaces
                        }
                        2 {
                        }
                    }
                }
            }
            if $DelUnattFlag {
                ic_geo_delete_unattached
            }
	        ic_highlight
        }

	    7 { #
			set mesh_srfs ""
			foreach s $crvSurfTrmSurfList {
				if {[ic_geo_get_object_type surface $s] == "mesh"} {
					lappend mesh_srfs  $s
				}
			}
			set n_mesh  [llength $mesh_srfs]
            set curLCS [ic_csystem_get_current] 
	        switch -- $modifyFacetSurf2EXGVal {
		        0 {
		            aie_project_crvs_and_trim_srfs $fam $crvSurfTrmCurveList $crvSurfTrmSurfList $name 0
		        }
		        1 {  
			        switch $modSegmPlaneNormEGVal {
				        0 { 
					        set nrm [ic_vset -vec - $segPlanenormal]
					        set p1 $SegPlanePntList
					        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 $SegPlanePnt1
					        set p2 $SegPlanePnt2	
					        set p3 $SegPlanePnt3
					        set nrm [ic_vcalc product $p1 $p2 $p3]
				        }
			        }
			        # Note: picker always return xyz in LCS: convert into global
                    if {$curLCS != "global"} {
                        mess "Using current coordinate system $curLCS to segment surface(s)\n"
                    }
			        foreach vec "nrm p1 p2 p3" {
				        set v [set $vec]
				        if {$v == ""} { return }
				        set $vec [ic_coords_into_global $v]
			        }
  			        tdv_active 0
  			        set param_srfs ""
  			        set nnames ""
  			        set p1_plane $p1
  			        foreach surf $crvSurfTrmSurfList {
  				        set type [ic_geo_get_object_type surface $surf]
       			        set fam ""
       			        set segsurf ""
       			        if {$type == "param"} {
       				        lappend param_srfs $surf
           		        } else {
           		            if {$curLCS != "global"} {
           		                set p1 [ic_coords_into_local $p1_plane]
           		                if [info exists va_set(normal)] {
           		                    set nrm $va_set(normal)
           		                }
           		            }
              		        append nnames "[ic_geo_create_surface_segment $surf plane angle 20 mintri 1 plane_p $p1 plane_n $nrm keep_old 0 curves {}] "
                        }
			        }
                    if {$param_srfs != ""} {				
           		        set nnames [ic_geo_cre_surface_section $fam $name $param_srfs 0 $p1 $p2 $p3 1]
       		        }
       		        if {[llength $nnames]} {
       		            if {$param_srfs != ""} {
       		                mess "Done \"Segment Surface by plane\": trimmed with curve(s) $nnames\n"
       		            } else {
       		                mess "Done \"Segment Surface by plane\": [llength $nnames] new surface(s)\n"
       		                if !$::vid_options(inherit) {
       		                    foreach s $nnames {
       		                        ic_geo_set_part surface $s $part_name 0
       		                    }
       		                }
       		            }
       		        } else {
       		            mess "Unable to segment surface(s)\n" red
       		        }
  			        tdv_active 1
		        }
		        2 {
			        if !$n_mesh {
				        status_message "Segmentation by connectivity works only for faceted data\n"
				        return
			        }
                    if {$curLCS != "global"} {
                        mess "Using current coordinate system $curLCS\n"
			            set nrm [ic_vset -vec - "0 0 1"]
			            set plane_p [ic_coords_into_global "0 0 0"]
			            set plane_n [ic_coords_into_global $nrm]
                    } else {
                        set plane_p [list 0 0 0]
                        set plane_n [list 0 0 1]
                    }
		            # segment by lack of connectivity
		            set nnames ""
		            foreach s $mesh_srfs {
				        append nnames "[ic_geo_create_surface_segment $s connect angle 0 mintri $minSeg plane_p $plane_p plane_n $plane_n keep_old $modSurfKeepOldFlag] "
				        if {[llength $nnames]} {
				            mess "Unable to segment surface $s\n" red
				        }
		            }
				    if {[llength $nnames]} {
				        mess "Done \"Segment Surface by connectivity\": [llength $nnames] new surface(s)\n"
       		            if !$::vid_options(inherit) {
       		                foreach s $nnames {
       		                    ic_geo_set_part surface $s $part_name 0
       		                }
       		            }
				   }
		        }
		        3 {
			        if !$n_mesh {
				        status_message "Segmentation by angle works only for faceted data\n"
				        return
                    }
		            if {$seg_angle == 0} { mess "Warning: Angle is not defined\n" red; return }
                    if {$curLCS != "global"} {
                        mess "Using current coordinate system $curLCS\n"
			            set nrm [ic_vset -vec - "0 0 1"]
			            set plane_p [ic_coords_into_global "0 0 0"]
			            set plane_n [ic_coords_into_global $nrm]
                    } else {
                        set plane_p [list 0 0 0]
                        set plane_n [list 0 0 1]
                    }
		            foreach s $mesh_srfs {
		                set new [ic_geo_create_surface_segment $s angle angle $seg_angle mintri $minSeg plane_p $plane_p plane_n $plane_n keep_old $modSurfKeepOldFlag curves {}]
		            }
		            set nnew [llength $new]
		            if {$new > 0 && $nnew < 10} {
				        set nnames "segmentation: $new"
			        } elseif {$nnew == 0} {
				        status_message "No new surfaces with angle $seg_angle degrees. Please try with angle between 0 and $seg_angle" red
				        return
			        } else {
				        set nnames "segmentation: $nnew new surfaces"
		            }
		        }
	        }
	        set crvSurfTrmSurfList ""
	    }

	    8 {
	    switch -- $modifyReapproxSurfVal {
		0 {
		    if {$modSurfMergeList == ""} {
			status_message "No surfaces selected!" red
			return
		    }
		    foreach isurf $modSurfMergeList {
			if {[ic_geo_check_objects_exist surface $isurf] == ""} {
			    status_message "Selected surface \"$isurf\" does not exist!" red
			    return
			}
		    }
		    set surftype [ic_geo_get_object_type surface $modSurfMergeList]
		    #  
		    # Merge: only for faceted; surfaces may be not connected.
		    # Reapproximation: only for bsp connected surface with topo info
		    	    
		    if { $surftype=="param" || $surftype=="mixed"} {
		        set msg "Only faceted surfaces could be merged."
		        append msg " Reapproximate param surfaces (require topology).\n"
		        append msg "Do you want to Convert selected Bspline surfaces to facets?"
		        switch -- [tk_dialog .confacet "Merge Surfaces" $msg "" -1 Yes No] {
			    0 {
			        set facetSurfList ""
			        set ta [tdv_active 0]
			        busy 1
				foreach surf $modSurfMergeList {
				    set surftype [ic_geo_get_object_type surface $surf]
				    if {$surftype=="param"} {
				        set nsurf [ic_facetize_geometry surface $surf]
					if {$nsurf != ""} {
					    ic_delete_geometry surface names $surf
					    lappend facetSurfList $nsurf
					} else {
					    mess "Error: Could not facetize surface: $surf; merge surfaces failed\n" red
					}
				    } else {
					lappend facetSurfList $surf
				    }
				}
				set modSurfMergeList $facetSurfList
				busy 0
				tdv_active $ta
			    }
			    1 - -1 {
			        if [winfo exists .confacet] { top_destroy .confacet }
			        foreach s $modSurfMergeList {
		                    ic_show_geo_selected surface $s 0
		            }
		            set modSurfMergeList ""
			        return
			    }
		        }
		    }
		    busy 1
		    set dest [lindex $modSurfMergeList 0]
		    set objects [lrange $modSurfMergeList 1 end]
		    ic_geo_merge_objects surface $dest $objects
		    ic_delete_geometry surface names $objects
		    set nnames "$dest (merged with $objects )"
		    ic_geo_finish_edit surface $dest
		    ic_show_geo_selected surface $dest 0
		    set modSurfMergeList ""
		    busy 0
		}
		1 {
		    if {$reappSurfList == ""} {
		        status_message "No surfaces selected!" red
		        return
		    }
		    if {$mtol1 == ""} {
		        status_messsage "Please enter the tolerance" red
		        return
		    }
		    foreach s $reappSurfList {
			if {[ic_geo_check_objects_exist surface $s] == ""} {
			    status_message "Selected surface \"$s\" does not exist!" red
			    return
			}
                    }
                    # Avoid dez user interaction during apply run
                    createSurfsDEZ setclean
                    createSurfsDEZ setclean_others
		    set res [ic_geo_modify_surface_reappr $reappSurfList $mtol1 1 0]
		    createSurfsDEZ setdirty
		    createSurfsDEZ setdirty_others
		    if ![llength $res] {
		        status_message "Check topology" red
		    } else {
		        foreach s $res {
		            ic_show_geo_selected surface $s 0
		        }
		        set nnames $res
		        set reappSurfList ""
		    }
		    set reappSurfList ""
		}
		2 {
		    if {$reappSurf1List == ""} {status_message "No surfaces selected" red; return}
		    if {$reappCur1List == ""} {status_message "No curves selected" red; return}
		    if {$mtol2 == ""} {status_message "Please enter the tolerance" red; return}
		    foreach s $reappSurf1List {
			if {[ic_geo_check_objects_exist surface $s] == ""} {
			    status_message "Selected surface \"$s\" does not exist!" red
			    return
			}
                    }
                    # Avoid dez user interaction during apply run
                    createSurfsDEZ setclean
                    createSurfsDEZ setclean_others
		    set new_surf [ic_geo_modify_surface_reappr $reappSurf1List $mtol2 1 0 $reappCur1List]
		    createSurfsDEZ setdirty
		    createSurfsDEZ setdirty_others
		    foreach s $new_surf {
		        ic_show_geo_selected surface $s 0
		    }
		    set reappSurf1List ""
		    set reappCur1List ""
		}
		3 {
		    foreach s $reappSurf2List {
			if {[ic_geo_check_objects_exist surface $s] == ""} {
			    status_message "Selected surface \"$s\" does not exist!" red
			    return
			}
                    }
		    if {$facetedonlyFlag3} {
			set reappSurf2List [ic_get_facets surface $reappSurf2List]
		    }
		    if {$reappSurf2List == ""} {status_message "Select faceted surfaces" red; return}
		    if {$debug} {
		        mess "Debug level = $debug\n" red
		    }
		    set shrink 0.2
		    set hull [ic_hull_2d $reappSurf2List $mtol4 1 "surface" $shrink $debug]
                    # Avoid dez user interaction during apply run
                    createSurfsDEZ setclean
		    createSurfsDEZ setclean_others
		    set new_surf [ic_geo_modify_surface_reappr $reappSurf2List $mtol4 1 0 $hull]
		    createSurfsDEZ setdirty
		    createSurfsDEZ setdirty_others
		    if {!$debug && $new_surf == "{}"} {
		        ic_delete_geometry curve names $hull
		    }
		    foreach s $new_surf {
		        ic_show_geo_selected surface $s 0
		    }
		    set reappSurf2List ""
		}
		4 {
		    foreach s $reappEachSurfList {
			if {[ic_geo_check_objects_exist surface $s] == ""} {
			    status_message "Selected surface \"$s\" does not exist!" red
			    return
			}
                    }
                    set each_surf 0
		    if {$facetedonlyFlag4} {
			set reappEachSurfList [ic_get_facets surface $reappEachSurfList]
		        if {$reappEachSurfList == ""} {status_message "Select faceted surfaces" red; return}
		        if {[llength $reappEachSurfList] > 1} { set each_surf 1 }
		    } else {
		        if {[llength [ic_get_facets surface $reappEachSurfList]] > 1} { set each_surf 1 }
		    }
		    if {$reappEachSurfList == ""} {status_message "Select surfaces" red; return}
		    if {$mtol3 == ""} {status_message "Please enter the tolerance" red; return}		    
		    set topo_run_ok 1
		    foreach s $reappEachSurfList {
		        if {[llength [ic_get_facets surface $s]] == 1} {
		            if {[ic_geo_boundary surface $s 0 1 1] == ""} {
		                set topo_run_ok 0
		                break
		            }
		        }
		    }
		    if !$topo_run_ok {
		        mess "Faceted surface(s) found: You must have run the Build Diagnostic Topology\
		              function for them before you can use this function.\n" red
		        set reappEachSurfList ""
		        return
		    }
		    
		    set ask 1
		    switch -- $mode1 {
			Quiet {set ask 0}
			Confirm {set ask 1}
		    }
		    if $each_surf {
		        foreach s $reappEachSurfList {
			    if {[ic_geo_check_objects_exist surface $s] == ""} {
			        mess "Selected surface \"$s\" was replaced by a previous reapproximation!\n"
			        continue
			    }
                            # Avoid dez user interaction during apply run
                            createSurfsDEZ setclean
			    createSurfsDEZ setclean_others
		            foreach surf [ic_geo_modify_surface_reappr $s $mtol3 $ask 1] {
		                ic_show_geo_selected surface $surf 0
		            }
		            createSurfsDEZ setdirty
		            createSurfsDEZ setdirty_others
		        }
		    } else {
                        # Avoid dez user interaction during apply run
                        createSurfsDEZ setclean
		        createSurfsDEZ setclean_others
		        set new_surfs [ic_geo_modify_surface_reappr $reappEachSurfList $mtol3 $ask 1]
		        createSurfsDEZ setdirty
		        createSurfsDEZ setdirty_others
		        foreach s $new_surfs {
		            ic_show_geo_selected surface $s 0
		        }
		    }
		    set reappEachSurfList ""
		}
	    }
	}

        9 {
            if {$TrimSurfs == ""} { return }
            foreach surf $TrimSurfs {ic_geo_untrim_surface $surf}
            # regenerate surface: 45119  
            set TrimSurfs ""
            ic_regenerate_tris
        }

        10 {
            busy 1
            set build_topo $prTrFlag
            ic_undo_group_begin
            foreach curtmember $CurtSurfCurvList {
                set fam $part_name
                aie_check_inherit_fam fam curve $curtmember
                set newname [ic_vset -new_name $name all]
                set new_srf_name [ic_geo_create_surface_curtain $curtmember $CurtSurfSurfList $newname $fam $build_topo]
                if {$new_srf_name == ""} {
                    ic_undo_group_end
                    aie_undo
                    busy 0
                    return
                } else {
                    lappend nnames $new_srf_name
                }
            }
            ic_undo_group_end
            busy 0
        }

        11 {
            # 0 = Closest, 1 = Tangential from edge, 2 = Tangential along U/V
            set perpendicular [lsearch $extendlist $extend_method]
            foreach s $ExtendSurf {
                if {[ic_geo_check_objects_exist surface $s] == ""} {
                    mess "No surface named $s\n" red
                    return
                }
            }
            foreach c $ExtendCurve {
                if {[ic_geo_check_objects_exist curve $c] == ""} {
                    mess "No curve named $c\n" red
                    return
                }
            }
            switch $createSurfExtMethodVal {
                0 {
                    if {$connect && $ExtendSurf == ""} {
                        mess "Please select at least one surface\n" red
                        return
                    }
                    ic_geo_surface_extend $ExtendCurve $ExtendSurf $::geo_cad(toler) $connect $perpendicular $connect
                }
                1 {
                    if {$ExtSrfAtEdgeSrf == ""} {
                        mess "No surfaces selected!\n" red
                        return
                    }
                    if {$ExtSrfAtEdgeEdgenum == ""} {
                        mess "No edge selected!\n" red
                        return
                    }
                    if {$ExtSrfAtEdgeDistance == "" || $ExtSrfAtEdgeDistance == 0} {
                        mess "No distance given!\n" red
                        return
                    }
                    set surftype [ic_geo_get_object_type surface $ExtSrfAtEdgeSrf]
                    if {$surftype!="param" } {
                        msg ERROR "Extension method works only for Bspline surfaces.\nSurface: $ExtSrfAtEdgeSrf is not a Bspline surface"
                        return
                    }
                    set not_connected 1
                    foreach e [ic_geo_get_srf_edges $ExtSrfAtEdgeSrf] {
                        if {"$e" == "$ExtSrfAtEdgeEdgenum"} {
                            set not_connected 0
                            break
                        }
                    }
                    if $not_connected {
                        mess "Curve $ExtSrfAtEdgeEdgenum not connected to surface $ExtSrfAtEdgeSrf\n" red
                        return
                    }
                    set old_func 0
                    if {$old_func && !$absolute} {
                        set xyz  [lindex [ic_geo_get_crv_pos 0.5 $ExtSrfAtEdgeEdgenum] 0]
                        foreach "u v" [ic_geo_find_nearest_srf_pnt $ExtSrfAtEdgeSrf $xyz] {
                            # convert uv in edge:
                            # {0 xx} -> 1; {xx 0} -> 2; {1 xx} -> 3; {xx 1} -> 4
                            if {[expr abs($u-0.5)] > [expr abs($v-0.5)]} {
                                if {$u > 0.5} {set edge 3} else {set edge 1}
                            } else {
                                if {$v > 0.5} {set edge 4} else {set edge 2}
                            }
                        }
                        mess "Extend surface \"$ExtSrfAtEdgeSrf\" by $ExtSrfAtEdgeDistance at edge $edge.\n"
                        ic_geo_mod_srf_tanext $ExtSrfAtEdgeSrf $ExtSrfAtEdgeDistance $edge $connect
                    } else {
                        mess "Extend surface \"$ExtSrfAtEdgeSrf\" by $ExtSrfAtEdgeDistance at edge \"$ExtSrfAtEdgeEdgenum\".\n"
                        set dist $ExtSrfAtEdgeDistance
                        if {!$absolute} {
                            set dist -$ExtSrfAtEdgeDistance
                        }
                        set res [catch {ic_geo_mod_srf_ext $ExtSrfAtEdgeSrf $dist \
                            $ExtSrfAtEdgeEdgenum $connect} msg]
                        if $res {
                            mess "Extension error: $msg\n"
                            return
                        }
                    }
                    mess "Surface extended.\n"
#                    return
                }
                2 {
                    # for midsurfaces only:
		    set connect_mid 0
		    if {[info exists vid_options(new_srf_topo)] && $vid_options(new_srf_topo)} {
		        set connect_mid 1
		    }
                    if ![array exists arr_crv_proj] {
                        if ![ExtSrfEval] { return }
                    }
                    ic_image delete
                    # do by groups; interrupt by group
                    # clean arr_crv_proj:
                    foreach crv [array names arr_crv_proj] {
                        set pts "" 
                        foreach p $arr_crv_proj($crv) {
                            if {$p == "none"} continue
                            lappend pts $p
			}
			if ![llength $pts] {
			   unset arr_crv_proj($crv)
			} else {
			    set arr_crv_proj($crv) $p
			}
		    }
		    set crvs [array names arr_crv_proj]
		    if ![llength $crvs] {
		        ic_mess "No valid selection\n"
		        return
		    }
		    set crv_groups [aie_set_crvs_connected $crvs]
		    set n_groups [llength $crv_groups]
		    set curr_group 0
		    interrupt init
		    interrupt set 0
                    foreach group $crv_groups {
                        incr curr_group
			interrupt check $curr_group $n_groups
			set srfs ""
			if [info exists tmp_prts] {unset tmp_prts}
				# check crv in group and exclude if not exists
				set crvs_exist ""
			foreach crv $group {
					if {[ic_geo_check_objects_exist curve $crv] == ""} {
						continue
					}
					lappend crvs_exist $crv 					
			    foreach p $arr_crv_proj($crv) {
			        set tmp_prts($p) 1
			    }
			}
			if ![info exists tmp_prts] continue
                        foreach p [array names tmp_prts] {
                            append srfs " " [ic_geo_get_objects surface $p]
			}
				set new_surfs [ic_geo_surface_extend $crvs_exist $srfs $::geo_cad(toler) $connect_mid $perpendicular $connect_mid]
                        foreach s $new_surfs {
		            ic_show_geo_selected surface $s 0
		        }
			if {$interrupt_pending == "1"} break
                    }
                    interrupt finish
                    # unset all arrays: are not valid anymore
                    foreach arr {arr_crv arr_crv_tan arr_crv_dir arr_crv_proj} {
                        if [info exists $arr] {unset $arr}
                    }
                    ic_geo_set_tag clear "" curve.single 0
                    status_message "Done extend"
                }
            }

	}
	12 {
	    switch -- $shrinkWrapEGVal {
		1 {

		# Selection
		    if {$convexHullSurList == ""} {
		        ic_mess "No Geometry selected\n" red
		        return
		    }
	
		#
		    set convex_hull(how) [lindex "single interact grid" $convexHullMethodEXGVal]
		#
		# Validation for grid:			
		if {$convex_hull(how) == "grid"} {
		# Integer split numbers ?
			foreach n "$splitXDiv $splitYDiv $splitZDiv" {
				if [catch "format %d $n"] {
					ic_mess "Wrong divisions $n\n" red
					return
				}
			}
		# Must have at least 1 actual split, otherwice error...					
			if 	{($splitXDiv < 2) && ($splitYDiv < 2) && ($splitZDiv < 2)} {
				ic_mess "Make at least one divisions 2 or more\n" red
				return
			}
		}				
		#
		    set convex_hull(divs_type) [lindex "model screen" $splitMethodGGVal]
		    set convex_hull(tol)      $convexTol
		    set convex_hull(xdivs)    $splitXDiv
		    set convex_hull(ydivs)    $splitYDiv
		    set convex_hull(zdivs)    $splitZDiv
		    set convex_hull(coarsen)  $convexCoarsenGGVal
		    set convex_hull(rem_int)  $convexRemInterFaceFlag
		    set convex_hull(use_fam)  ""
		    if [aie_check_inherit_fam] {
		        catch { unset use_this_part }
		        foreach {t n} $convexHullSurList {
		           if {$t == "surface"} {
		              set convex_hull(use_fam) [ic_geo_get_part $t $n]
		              break
		           } else {
		              set use_this_part [ic_geo_get_part $t $n]
		           }
		        }
		        if {$convex_hull(use_fam) == ""} {
		            if [info exists use_this_part] {
		                set convex_hull(use_fam) $use_this_part
		            } else {
		                set convex_hull(use_fam) $fam
		            }
		        }
		    } else {
		        set convex_hull(use_fam) $fam
		    }
		    set convex_hull(ask_fams) 0
		    set convex_hull(sep_fams) $convexHullSeparateFlag
		    set the_list ""
		    foreach {t n} $convexHullSurList {
		        lappend the_list "$t $n"
		    }
		    # from med_gui/convex_hull.tcl:
		    geo_convex_hull_doit $the_list   
		}
		0 {
		    if {$minFeatSize == ""} {
                msg ERROR "No minimum size specified for cartesian shrink wrap"
                return
		    }
		    if {$projFactor == ""} {
                msg ERROR "No surface projection factor specified for cartesian shrink wrap"
                return
		    }
		    if {$nSmooth == ""} {
                msg ERROR "No num. of smooth iterations specified for cartesian shrink wrap"
                return
		    }
		    if {$c3dshrinkPart == ""} {
                msg ERROR "No part specified for envelope"
                return
		    }
		    # Part by Part
		    if $partFlag {
                ::AIEnv::GUIManagement::Tree::ShowGeometry 1
                set assemblies ""
                set parts [aie_list_parts 0]
                foreach part $parts {
                    if {$VisGeomFlag && !$fam_visible($part)} continue
                    set surfs [ic_geo_get_objects surface $part]
                    if ![llength $surfs] continue
                    set asmly [lindex [split $part /] 0]
                    if {[lsearch $assemblies $asmly] < 0} {
                        lappend assemblies $asmly
                    }
                }
                set part_by_part 1
                set nruns [llength $assemblies]
		    } else {
                set part_by_part 0
                set nruns 1
		    }

		    if {$c3dshrinkPart != "inherited"} {
                set fam [aie_new_part $c3dshrinkPart]
		    } else {
                set fam "inherited"
		    }
		    
		    set force_load 0
		    for {set i 0} {$i < $nruns} {incr i} {
                set temp_c3dshrink_file temp_c3dshrink.tin
                if $part_by_part {
                    set asmly  [lindex $assemblies $i]
                    mess "\n******* Running cartesian shrink wrap for Assembly: $asmly **********\n"
                    ::AIEnv::GUIManagement::Tree::ToggleGroupVisibility part * 0
                    ::AIEnv::GUIManagement::Tree::ToggleGroupVisibility part $asmly 1
                    aie_updateGeoVis
                    ic_save_tetin $temp_c3dshrink_file 1
                    set tetinFN $temp_c3dshrink_file
#                    set fam $asmly
                    set force_load 1
                } elseif $VisGeomFlag {
                    foreach part [aie_list_parts 0] {
                        if {$fam_visible($part)} {
                            ic_geo_update_visibility surface $part 1
                        }
                    }
                    if {![ic_geo_num_visible_objects surface 1]} {
                        msg ERROR "No surfaces are visible"
                        return
                    }
                    ic_save_tetin $temp_c3dshrink_file 1
                    set tetinFN $temp_c3dshrink_file
                    set force_load 1
                } elseif {($file_name(tetin) == "") || ([ic_geo_is_modified])} {
                    ic_save_tetin $temp_c3dshrink_file
                    set tetinFN $temp_c3dshrink_file
                } else {
                    set tetinFN $file_name(tetin)
                }
                if {($tetinFN == "") || ![ic_geo_is_loaded]} {
                    msg ERROR  "No geometry file loaded\n"
                    return
                }
                set size $minFeatSize
                if $part_by_part {
                    set emax [ic_geo_get_family_param $fam emax]
                    if {$emax != ""} {
                        set size $emax
                    }
                }
                ic_undo_suspend
                set mtype 1
                busy reset
                ic_hexcart_shrinkwrap $tetinFN $size $projFactor $nSmooth $fam $force_load $mtype
                busy reset
                ic_undo_resume
                aie_create_initial_assemblies
                if {$i < [expr $nruns-1]} {
                    ic_save_unstruct temp_shrink${i}.uns
                }
            }
            if {$nruns > 1} {
                for {set i 0} {$i < [expr $nruns-1]} {incr i} {
                    ic_load_unstruct temp_shrink${i}.uns
                    catch {file delete temp_shrink${i}.uns}
                }
            }
            # New flag: Create Geometry from Mesh Automatically (Onyx 38190)
            # In order to avoid duplicated geometry move new geometry from part
            #  $P to part ${P}_WRAP
            if $MakeGeomFlag {
                if ![ic_uns_is_loaded] {
                    msg ERROR  "No mesh for geometry creation is loaded\n"
                    return
                }
                if [info exists tmp_srflist] {unset tmp_srflist} 
                set mesh_fams [ic_uns_non_empty_families]
                foreach f $mesh_fams {
                    foreach srf [ic_geo_get_objects surface $f] {
                        set tmp_srflist($srf) $f
                    }    
                }
                ic_geo_import_mesh {} 1 1 1		    
                ic_unload_uns_mesh
                aie_close_Mesh 0
                foreach f $mesh_fams {
                    foreach srf [ic_geo_get_objects surface $f] {
                        if ![info exists tmp_srflist($srf)] {
                            ic_geo_set_family surface ${f}_WRAP names $srf 0
                        }
                    }
                }
                aie_initGeoVis
                ic_geo_set_modified 1
                aie_clear_dez
                aie_load_lcs
                aie_update_icons geom
            }
            if $VisGeomFlag aie_updateGeoVis
            catch {file delete $temp_c3dshrink_file}
            if $part_by_part {
                foreach p $assemblies {
                    ::AIEnv::GUIManagement::Tree::ToggleGroupVisibility part $p 1
                }
                if {$c3dshrinkPart != "inherited"} {
                    ::AIEnv::GUIManagement::Tree::ToggleGroupVisibility part $fam 1
                }
                aie_updateGeoVis
                aie_updateMeshVis
            }
		}
	    }
	}
	13 {
	    # STD: standard geometry: plane, box, cylinder
	    # Box and cylinder already in EZCAD. Just call. 
	    # Only cartesian LCS !
            if {[lindex [ic_csystem_get [ic_csystem_get_current]] 0] != "cartesian"} {
		status_message "Use cartesian coordinate system for Std Geometry\n" red
		return
            } 
            global va_set
	    switch -- $createStdShapeEGVal {
		0 {
			if ![info exists stdBoxTypeEGVal] { return }
			switch $stdBoxTypeEGVal {
				0 {
					foreach {dx dy dz} $StdBoxSides ""
					set pt1 $boxAxPntList
				}
				1 {
				    switch $stdBoxAdjustBoundsVal {
					0 {
					    foreach s {xF yF zF} {
						if ![string is double -strict [set $s]] {
						    mess "[set $s] is not a valid value\n" red
						    return
						}
					    }
					    set entities ""
					    foreach {t n} $boxEntityList {
						if {$t == "body"} {
							set objs [ic_geo_body_lower_entities $n]
							if {$objs != ""} {
								eval lappend entities $objs
							}
						} else {
							lappend entities $t $n
						}
					    }
					    if {$entities == ""} {set entities all}
					    set bbx [ic_geo_bounding_box $entities]
					    if ![llength $bbx] return
					    set pt1 [lindex $bbx 0]
					    set pt2 [lindex $bbx 1]
					    foreach {pt1x pt1y pt1z} $pt1 {pt2x pt2y pt2z} $pt2 ""
					    set dx [expr {($pt2x - $pt1x) * $xF}]
					    set dy [expr {($pt2y - $pt1y) * $yF}]
					    set dz [expr {($pt2z - $pt1z) * $zF}]
					    set pt1x [expr {$pt1x - (($xF - 1.0) * 0.5) * ($pt2x - $pt1x)}]
					    set pt1y [expr {$pt1y - (($yF - 1.0) * 0.5) * ($pt2y - $pt1y)}]
					    set pt1z [expr {$pt1z - (($zF - 1.0) * 0.5) * ($pt2z - $pt1z)}]
					    set pt1 [list $pt1x $pt1y $pt1z]
					}
				    	1 {
					    foreach s {Xmin Xmax Ymin Ymax Zmin Zmax} {
						if ![string is double -strict [set $s]] {
						    mess "[set $s] is not a valid value\n" red
						    return
						}
					    }
					    set dx [expr $Xmax - $Xmin]
					    set dy [expr $Ymax - $Ymin]
					    set dz [expr $Zmax - $Zmin]
					    set pt1 [list $Xmin $Ymin $Zmin]
				 	}
					 default {
					    mess "This option is not supported\n" red
					}
				    }
				}
			}

			set name [ic_vset -new_name  box8.00 all]
			set obID [lindex [split $name .] end]
			set Ref box8.$fam.$obID.Ref
			# Ref name will be used ONLY if point/vector not exists
			# set p [va_check_data_set_point $pt1 point $fam $Ref]
			# Explicit definition of collapsed box with "surface 2sides":
			if {$dx == 0} {
				set nnames [ic_surface 2sides $fam $name [list $pt1 X $dy $dz]]
			} elseif {$dy == 0} {
				set nnames [ic_surface 2sides $fam $name [list $pt1 Y $dx $dz]]
			} elseif {$dz == 0} {			
				set nnames [ic_surface 2sides $fam $name [list $pt1 Z $dx $dy]]
			} else {			
				set nnames [ic_vid_object box8 $fam $obID $pt1 $dx $dy $dz]
			}
			if {$nnames == ""} { createSurfsDEZ setdirty }
		} 
		1 {
			if {[llength $StdSphereList] != 2} { return }				
			aie_check_inherit_fam fam point $StdSphereList
			set list [va_check_data_set_points $StdSphereList keep $fam $name.01]
			if !$RadStdSphGGVal {
				set radiusSph [ic_vcalc distance [lindex $StdSphereList 0] [lindex $StdSphereList 1]]
			}
			if {$stangleSph < 0 || $stangleSph > 180 || $enangleSph < 0 || $enangleSph > 180} {
			    ic_mess "Sphere start/end angles should be between 0 and 180\n" red
			    return
			}
			set nnames [ic_surface sphere $fam $name "$list $radiusSph $stangleSph $enangleSph"] 
		}  
		2 {
		    if {[llength $cylAxPntList] != 2} { return }
		    aie_check_inherit_fam fam point $cylAxPntList
			set list [va_check_data_set_points $cylAxPntList keep $fam $name.01]	    
		    set nnames [ic_surface cyl $fam $name "$list $CylindRad1 $CylindRad2 $CylindBase1Flag $CylindBase2Flag"]  
		}
		4 {
		    set name [va_auto_name surface $name $fam]
			set c $TrimPlaneCurveList
			if ![llength [ic_geo_check_objects_exist curve $c]] return
			set p $StdPlaneCurveParam
			set a [ic_vset - $StdPlaneSide]
			if {$a == "" || ($a <= 0)} {
				status_message "Side must be > 0" red			
				return
			}			
			foreach "xyz tan vcen vnor" [ic_geo_get_crv_data_at_par $p $c] ""
			if ![llength $xyz] {
				status_message "Wrong curve name" red		
				return
			}			
			aie_cre_pnt_norm_plane $fam $name $xyz $tan $a 0			
		}
		5 {
		    set name [va_auto_name surface $name $fam]			
		    va_set_fam_name_etc $fam $name
			set c $TrimPlaneCurveList
			if ![llength [ic_geo_check_objects_exist curve $c]] return
			set p $StdPlaneCurveParam
			set rad [ic_vset - $StdPlaneRadius]
			if {$rad == "" || ($rad <= 0)} {
				status_message "Radius must be > 0" red
				return 
			}				
			foreach "xyz tan vcen vnor" [ic_geo_get_crv_data_at_par $p $c] ""
			if ![llength $xyz] {
				status_message "Wrong curve name" red		
				return
			}
			aie_cre_pnt_norm_plane $fam $name $xyz $tan $rad 1					
		}
		6 {
		#assuming, that surfaces selected and curve selected 
		# check valid curve and param: user may press "Apply"
		set c $TrimPlaneCurveList
		if ![llength [ic_geo_check_objects_exist curve $c]] return
		set p $StdPlaneCurveParam
		foreach "xyz tan vcen vnor" [ic_geo_get_crv_data_at_par $p $c] ""
		if ![llength $xyz] {
			status_message "Wrong curve name" red		
			return
		}
		set tmpfam  TMP_FAM
		ic_delete_geometry all families $tmpfam
		ic_delete_geometry surface srfplane 0
		set va_set(tmp_fam) $tmpfam
		set va_set(srfplane) srfplane
		set srfs $TrimPlaneSurfList
			set data ""
		set crvs ""
			foreach srf $TrimPlaneSurfList {
				lappend data "surface $srf"
			}
			foreach "bbmin bbmax" [ic_geo_bbox_of_entities $data] ""
			set bbsize [expr 2.0*[ic_vcalc distance $bbmin $bbmax]]
			set bbcenter [ic_vcalc sum_smult $bbmin $bbmax 0.5]
			set dist_to_cent [ic_vcalc distance $xyz $bbcenter]
			if {$dist_to_cent > $bbsize} {
				set bbsize [expr $bbsize + $dist_to_cent]
			} 	
			aie_cre_pnt_norm_plane $tmpfam srfplane $xyz $tan $bbsize
	        foreach srf $srfs {
				set crvi [ic_geo_intersect_surfaces $tmpfam "$srf srfplane" use_bsp]
		  if [llength $crvi] {
			foreach crv $crvi {lappend crvs $crv}
		  }
	        } 
	        if ![llength $crvs] {
		   ic_delete_geometry surface names srfplane 0
			ic_delete_geometry curve families $tmpfam
			status_message "No intersections between plane and selected surfaces\n" red
			return
		}		   		
		set crvs [aie_close_crvs_on_plane $tmpfam]
	        set res [catch {ic_geo_trim_surface srfplane $crvs $build_topo} data]
	        if !$res {
		# Build topo in order to find what is interior surface
		  ic_build_topo $::geo_cad(toler) $tmpfam
		   set intsurf [aie_delete_exterior_surfaces $tmpfam]
		   if {[llength $intsurf] != 1} {
			ic_delete_geometry all families $tmpfam
				status_message "Cannot create closed loop intersectng plane with selected surface(s)\n" red
			return
		   }
		   ic_geo_set_family surface $part_name names $intsurf 0
		   ic_geo_set_name surface $intsurf $name
		   set va_set(srfplane) [va_auto_name surface $va_set(srfplane)] 
		   ic_delete_geometry all families $tmpfam
		   set name [va_auto_name surface $name]
		   createSurfsDEZ setdirty
		} else {
			status_message "Cannot trim plane with selected surface(s)" red 
			return
		}
		}
		3 {
		    set holename ""
		    if $ReplaceHoleGGVal {
		        if {[llength  $StdHoleCrvList] == 1} {
			    set holename $StdHoleCrvList
                        }	
		    } else {
		       if {$StdHoleRad <= 0} {
		           status_message "Need radius > 0 to drill a hole" red 
		           return
		       }
		    }
		    if {$holename == ""} {
			set holename [ic_vset -new_name $name all]
		    } 
		    aie_check_inherit_fam fam surface $StdHoleSurfList
		    set nnames [ic_surface hole $fam $holename [list $StdHoleSurfList $StdHoleLocList $StdHoleRad]]
                    if {$nnames != "" && ([ic_geo_check_objects_exist curve $nnames] != "")} {
                        ic_build_topo $::geo_cad(toler) -no_concat -surfaces $StdHoleSurfList -curves $nnames
                    }
		}
	}
#This was for drilling bolt hole
#		4 {
#
# Next 4 closing brackets: a) case 7 b) switch createStdShapeEGVal
# c) close case 13 d) close main switch statement
#	    }
		}
	}
    
    # For all Surface DEZs:
	aie_default_topo_tolerance
    if {$nnames != ""} {
	mess "Done: create/modify surface(s) $nnames\n" blue
	# Force Visible
	if {$fam != ""} {
	    set msg ""
            set no_msg 0
	    if {!([info exists fam_visible($fam)] && $fam_visible($fam))} {
                set msg "Part $fam"
                if ![::AIEnv::GUIManagement::Tree::GroupExists part $fam] {
                    set no_msg 1
                }
	    } elseif !$geom_visible(surface) {
	        set msg Surface
	    }
	    if {$msg != ""} {
	        if !$no_msg { mess "\n$msg is not visible\n" red }
	        ic_show_geo_selected surface $nnames 1 white 1
		after 250 "ic_show_geo_selected surface [list $nnames] 0"			 
	    }	
	}
    }
    
    if [info exists va_set(img)] {
        catch {$va_set(img) delete}
		unset va_set(img)
    }
    
    # update curve color if "On"
    aie_update_curve_color_if_on
    aie_updateGeoVis surface 0 1
    # Next 2 lines are necessary in order to set config. (dormant, pickable, visible)
    # for new bsp dormant objects which may be created with surface, e.g. by "build_topo" 
    ::AIEnv::GUIManagement::Tree::ShowDormant point
    ::AIEnv::GUIManagement::Tree::ShowDormant curve   
    
    aie_create_parts_in_tree_if_needed 
    aie_update_parts_in_tree_if_needed
    aie_update_icons geom
    createSurfsDEZ setdirty
    if $do_home { tdv_home $tdv_default }
    if {$name == ""} {set name srf.00}
    set name [ic_vset -new_name $name all]	
}
#===========================
# Routines for Std shapes
proc onStdHoleCrvChrFinish {} {
# If curves not selected - Ok
# Set radius if selected, from 1-st curve
	set StdHoleLocList ""
	if ![llength $StdHoleCrvList] return
	if $auto_pick_mode {
	catch {ic_geo_remove_feature $StdHoleCrvList}
		set StdHoleCrvList ""
		StdHoleCrvChr pick
	}
}
proc onStdBoltCrv1ChrFinish {} {
}
proc onStdHoleLocChrPick {} {

}
proc onStdBoltLocChr1Pick {} {
# repair hole first to select location on whole surface! 
# If curves not selected - Ok
	if ![llength $StdBoltCrv1List] return
	ic_geo_remove_feature $StdHoleCrv1List
	set StdHoleCrv1List ""
}
proc onStdBoltLocChr2Pick {} {
# repair hole first to select location on whole surface! 
# If curves not selected - Ok
	if ![llength $StdBoltCrv2List] {
		ic_geo_untrim_surface 
		return
	}
	ic_geo_remove_feature $StdHoleCrv2List
}
proc onStdHoleLocChrFinish {} {
	if {$auto_pick_mode && [llength $StdHoleLocList]} {
		createSurfsDEZ apply
		set StdHoleLocList ""
		StdHoleLocChr pick
	}
}
proc onStdBoltLocChrFinish {} {
	if {$auto_pick_mode && [llength $StdBoltLocList]} {
		createSurfsDEZ apply
#		StdBoltLocChr pick
	}
}
proc onAdjBox1Load {} {
	    foreach s {xF yF zF} {
		if ![string is double -strict [set $s]] {
		    mess "[set $s] is not a valid value\n" red
		    return
		}
	    }
	    set entities ""
	    foreach {t n} $boxEntityList {
		if {$t == "body"} {
			set objs [ic_geo_body_lower_entities $n]
			if {$objs != ""} {
				eval lappend entities $objs
			}
		} else {
			lappend entities $t $n
		}
	    }
	    if {$entities == ""} {set entities all}
		# on...Load function may be called implicitly /building GUI/
		set bbx [ic_geo_bounding_box $entities]
		if ![llength $bbx] return
		set pt1 [lindex $bbx 0]
		set pt2 [lindex $bbx 1]

	    foreach {pt1x pt1y pt1z} $pt1 {pt2x pt2y pt2z} $pt2 ""
	    set dx [expr {($pt2x - $pt1x) * $xF}]
	    set dy [expr {($pt2y - $pt1y) * $yF}]
	    set dz [expr {($pt2z - $pt1z) * $zF}]
	    set ptt1x [expr {$pt1x - (($xF - 1.0) * 0.5) * ($pt2x - $pt1x)}]
	    set ptt1y [expr {$pt1y - (($yF - 1.0) * 0.5) * ($pt2y - $pt1y)}]
	    set ptt1z [expr {$pt1z - (($zF - 1.0) * 0.5) * ($pt2z - $pt1z)}]
	    set ptt2x [expr {$pt2x + (($xF - 1.0) * 0.5) * ($pt2x - $pt1x)}]
	    set ptt2y [expr {$pt2y + (($yF - 1.0) * 0.5) * ($pt2y - $pt1y)}]
	    set ptt2z [expr {$pt2z + (($zF - 1.0) * 0.5) * ($pt2z - $pt1z)}]
	    set pt1 [list $ptt1x $ptt1y $ptt1z]
	    set pt2 [list $ptt2x $ptt2y $ptt2z]


	    set Xmin [lindex $pt1 0]
	    set Ymin [lindex $pt1 1]
	    set Zmin [lindex $pt1 2]
	    set Xmax [lindex $pt2 0]
	    set Ymax [lindex $pt2 1]
	    set Zmax [lindex $pt2 2]
mess "\nSetting min/max sizes based off the bounding box with the defined scale factors.\n"
mess "If you change scale factors, please turn off/on Adjust min/max values to update.\n"
mess "Please adjust the min/max values and hit Apply to create the box.\n"
}
#---------------------------------------------
proc onCreateSurfsFamModify {dez val} {
    if {$val == "From screen"} {
    	set p [geo_select_part_from_screen 1]
	set ::geo_part_name [aie_geo_set_part_name $p]
    }
}

proc aie_trace_c3dshrinkpart {name element op} {
    if {[createSurfsDEZ get c3dshrinkPart] == "From screen"} {
	createSurfsDEZ set c3dshrinkPart [geo_select_part_from_screen 1]
    }
}
# -------------------------------------------------------------------------------
proc oncreateSurfsDEZLoad {} {
    global toptol_userset
    aie_default_topo_tolerance
# do not select on first load: set invalid selection value
    aie_show_name createSurfName [aie_gui_get vid_options(show_item_name)]
    if ![info exists createSurfsEXGVal] {
	set createSurfsEXGVal -1
	set createSurfSimpleMethodVal 0
# * * * * * * * * * * * * * * *
# one-time settings:
# 		
	set createSrfTol 0.01
	set createSurfSweepMethodVal 0		
	set sangle 0
	set eangle 360
	set offsetdist 0
	set loftLinearFlag 0
	set loftBlendFlag 0
	set loftBTopoFlag 1
	set DelUnattFlag 1	
	set lofttol 0.1	
	set mnodestol 0.01
	set mtol1 0.1
	set mtol2 0.1
	set mtol3 0.1
	set mtol4 0.1
	set debug 0
	set connectedFlag 0
	set convexTol 0.001
	set convexCoarsenGGVal 1
	set convexHullSeparateFlag 1
	set convexRemInterFaceFlag 0
	set splitXDiv 2; set splitYDiv 2; set splitZDiv 2
	set seg_angle 30
	set minSeg 1   	
	set plane_n {0 0 1}
	set modSurfKeepOldFlag 0
	set completeFlag 0
	set internalFlag 0
	set mergeFlag 1
	set planeScale 1
	set segPlanenormal "0 1 0"
	set perpendicular 1
	set connect 1
	set proximity [expr [ic_geo_default_topo_tolerance] * 20 ]
	if ![info exists createSurfExtMethodVal] {set createSurfExtMethodVal 2}
	set radiusSph 1
	set stangleSph 0
	set enangleSph 180	
	set StdSphereList {{0 0 0} {0 0 1}}
	set CylindRad1 1
	set CylindRad2 1
	set CylindBase1Flag 1
	set CylindBase2Flag 1	
    }
# * * * * * * * * * * * * * * * 
# settings for each SurfsDEZLoad (usually - selection):
	
# It seems like a simulation of ttkrf option? 

    set extendlist {
        "Closest"
        "Tangential from edge"
        "Tangential along U/V"
    }
    if {[lsearch $extendlist $extend_method] < 0} {
        set extend_method [lindex $extendlist 0]
    }
    set how_modes {
        Confirm
        Present/Confirm
        Quiet
    }
    set how_modes1 {
        Confirm
        Quiet
    }
    if {![info exists mode]} {
        mess "mode variable does not exist"
        set mode [lindex $how_modes 0]
        # pull down now shows the first value
        createSurfMidMode setvalue last
    } else {
        set Index [lsearch $how_modes $mode]
        if {$Index !=-1} {
            createSurfMidMode setvalue @$Index
        } else {
            set Index [lsearch $how_modes $mode]
            if {$Index !=-1} {
                createSurfMidMode setvalue @$Index
            } else {
                # the user's previous choice was not found.
                # This should not happen but in case 
                set mode    [lindex $how_modes 0]
                createSurfMidMode  setvalue last
            }
        }
    }
    if {![info exists mode1]} {
        mess "mode1 variable does not exist"
        set mode1 [lindex $how_modes1 0]
        # pull down now shows the first value
        reappEachSurfMode setvalue first
    } else {
        set Index1 [lsearch $how_modes1 $mode1]
        if {$Index1 !=-1} {
            reappEachSurfMode setvalue @$Index1
        } else {
            set Index1 [lsearch $how_modes1 $mode1]
            if {$Index1 !=-1} {
                reappEachSurfMode setvalue @$Index1
            } else {
                # the user's previous choice was not found.
                # This should not happen but in case 
                set mode1    [lindex $how_modes1 0]
                reappEachSurfMode setvalue first
            }
        }
    }
    #            -----------------on craeteSurfDEZOK second group
    
    #--method 0
    set curveList ""
    #--method 1
    set curveDrivingList ""
    set curveDrivenList ""
    
    #--method 2 
    set curveSweepList ""
    set pntSweepVecList {{0 0 0} {1 0 0}}
    #--method 3
    set curveRevAxis ""
    set curveRevList ""
    set offsetSurfList ""

    #--methdo 4
    set loftsurfList ""    

    #--method 5
    if ![va_is_int_or_real $distance ] {set distance [expr [ic_geo_default_topo_tolerance] * 10 ]}
    set midsurfList ""
    set midsurfList2 ""

    #--method 9
    set crvSurfSegCurveList ""
    set crvSurfSegSurfList ""

    #--method 11 Cartesian Shrinkwrap and Convex Hull
    set convexHullSurList ""
    set convexHullName HULL
    ::AIEnv::GUIManagement::ToggleGrey convexcoarsen 0
    set midparts "" 
    if {[trace vinfo c3dshrinkPart] != ""} {
        trace vdelete c3dshrinkPart w aie_trace_c3dshrinkpart
    }
    trace variable c3dshrinkPart w aie_trace_c3dshrinkpart

    #-----------------13 Modify/segment faceted dat
    set modSurfSegSurfList ""

    set pickCurveList ""
    set plane_pnt ""
    #----------------Method 13 Std shape
    set planePntList ""
    set boxAxPntList "0 0 0"
    set boxEntityList ""
    set xF 1
    set yF 1
    set zF 1
    #---------------------------------------------------------------   
    set PartList [aie_list_parts 1]
    set part_name [aie_geo_set_part_name]
    set ::geo_part_name [aie_geo_set_part_name]
    if {$name == ""} {set name srf.00}
    set name [ic_vset -new_name $name all]	
    
    #------------------------------
    # default values for sides, length, radius, etc.
    # will replace text if not numerical
    # Add more names here if necessary
    foreach sizevar { StdPlaneSide StdPlaneRadius } {
	if {![info exists $sizevar] || ![va_is_int_or_real [set $sizevar]]} {
	    set $sizevar [aie_get_scale]
	}
    } 
    # similar set for triplets
    foreach sizevar {StdBoxSides} {
	if {![info exists $sizevar] || ![va_is_triplet [set $sizevar]]} {
	    set s [aie_get_scale] 
	    set $sizevar "$s $s $s"
	}
    } 
    ::AIEnv::GUIManagement::ToggleGrey createSurfsFam [aie_check_inherit_fam]
}

proc oncreateSurfsDEZUnLoad {} { 
    global in_ic_geo_modify_surface_reappr va_set
    if [info exists in_ic_geo_modify_surface_reappr] {
        mess "Warning: \"Dismiss\" was used during an surface operation.\n" red
    }
    if {[trace vinfo c3dshrinkPart] != ""} {
        trace vdelete c3dshrinkPart w aie_trace_c3dshrinkpart
    }
    if [info exists va_set(img)] {
        catch {$va_set(img) delete}
		unset va_set(img)
    }
    set midparts ""
    if {[trace vinfo mode] != ""} {
        trace vdelete mode w aie_create_surfs_trace_how_modes
    }
    if {[trace vinfo offsetFlag] != ""} {
        trace vdelete offsetFlag w aie_create_surfs_trace_partial_offset
    }    
    ic_image delete    
    banner ""
}
#-----------------------------Start of Auto Pick in Create Surface Procedure------------------------------------
proc oncreateSurfSimpleLoad {} {
    if $auto_pick_mode {
	switch $createSurfSimpleMethodVal {
            0 {createSurfEdgPick pick}
            1 {createSurfSimpleCrvs pick}
            2 {createSurfSimple4pts pick}
	}
    }
}
#----------------------------------0
proc oncreateSurfDrvLoad {} {
    if $auto_pick_mode {createSurfDrivPick pick}
}
#-----------------------------------1
proc oncreateSurfSweepLoad {} {
    if $auto_pick_mode {
		if !$createSurfSweepMethodVal {
			createSurfPPick pick
		} else {
			createSurfPDPick pick
		}
	}
}
#------------------------------------2
proc oncreateSurfRevLoad  {} {
    if $auto_pick_mode {createSurfRevAxisPick pick}
}
#------------------------------------3
proc oncreateSurfOffsetLoad {} {
    if $auto_pick_mode {createSurfOffsetPick pick}
}

#------------------------------------4

# No auto_pick_mode for Midsurface creation
proc oncreateSurfMidLoad {} {
    global beta_mode vid_options
    
    if $beta_mode {
        if {[trace vinfo offsetFlag] != ""} {
            trace vdelete offsetFlag w aie_create_surfs_trace_partial_offset
        }
        trace variable offsetFlag w aie_create_surfs_trace_partial_offset
        aie_create_surfs_trace_partial_offset "" "" ""
    }
    if [aie_check_inherit_fam] {
	::AIEnv::GUIManagement::ToggleGrey createSurfsFam 1
    } else {
	::AIEnv::GUIManagement::ToggleGrey createSurfsFam 0
    }
}

proc oncreateSurfMidUnLoad {} {   
    ::AIEnv::GUIManagement::ToggleGrey createSurfsFam 0
}

#------------------------------------5
proc onsurfsThicknessAdjustLoad {} {

#    if $auto_pick_mode {
#	switch -- $createThicknessAdjMethodVal {
#	    0 {SurfThickPickMids pick}
#	    1 {SurfThickPick pick}
#	}
#    }
}
#-----------------------------------6
proc oncreateSurfLoftLoad {} {
    if $auto_pick_mode {createSurfLoftPick pick}
}
#-----------------------------------7

proc oncreateSurfCurtainLoad {} {
    if $auto_pick_mode {CurtSurfCurvPick pick}
}
#----------------------------------8

proc oncreateSurfTrimLoad {} {
    if !$auto_pick_mode return
    switch $modifyFacetSurf2EXGVal {
        0 {createSurfTrmSurfPick pick}
        1 {createSurfTrmSurfPick2 pick}
        2 {createSurfTrmSurfPick3 pick}
        3 {createSurfTrmSurfPick4 pick}
    }           
}
#----------------------------------9

proc onmodifyMergeSurfLoad {} {
    if $auto_pick_mode {
        switch -- $modifyReapproxSurfVal {
	    0 {modifySurfMergeSurf pick}
	    1 {reapproxSelSurf pick}
	    2 {reapproxSelSurf1 pick}
	    3 {reapproxSelSurf2 pick}
	    4 {reapproxEachSurf pick}
        }
    }    
}

#-----------------------------------10
proc oncreateSurfHullLoad {} {
    set c3dShrinkPartList [aie_list_parts 1]
    lappend c3dShrinkPartList inherited
    if {![info exists c3dshrinkPart] || $c3dshrinkPart == ""} {
      set c3dshrinkPart inherited
    }
    if {![info exists minFeatSize] || ![va_is_int_or_real $minFeatSize]} {
	    set bbox [ic_geo_bounding_box all]
      set minFeatSize 1
	    if {$bbox != ""} {
		    set dxyz [ic_vcalc diff [lindex $bbox 0] [lindex $bbox 1]]
	      set lmax 0.0
	      foreach l $dxyz {
			   if {$l > $lmax} {set lmax $l}
	      }
	      set minFeatSize [format %3g [expr 0.75 * $lmax / 64.0]]
	    }
	  set nSmooth 5
	  set projFactor 0.5  	    
    }   
}

#-----------------------------------12
proc onmodifyFacetSurfsLoad {} {
    if $auto_pick_mode {modifyfacetPick pick}
}
#-----------------------------------

proc oncreateSurModifyLoad {} {
    if $auto_pick_mode {surfmodifyPick pick}   
}
proc onsegPlaneAxisOptionVLoad {} {
    if {$auto_pick_mode} {segPlaneAxis2PPick pick}
}

#----------------------------------Enf of Auto Pick in Create Surface Procedure---------------------------------

#--------------------------------------------Auto Apply for surface creation-------------------------------------
proc onsurfNormalPickFinish {} {

    set obj_type [ic_geo_get_object_type surface $surfNormalRef]
    if {$obj_type == "mesh"} {
	    mess "Faceted type of surfaces is not supported\n" red
	    set surfNormalRef ""
	    aie_updateGeoVis
	    return
    }
    if {($surfNormalRef != "") && $auto_pick_mode} {
        repairGeomDEZ apply
	    ic_geo_configure_one_attribute surface draw_norm 1
	    surfNormalPick pick
    }
}
proc onsurfNormalPickAnyFinish {} {	
	set newlst ""
	set msrfs 0
	foreach srf $surfNormalRefAny {
		set obj_type [ic_geo_get_object_type surface $srf]
		if {$obj_type == "mesh"} {
			incr msrfs
		} else {
			lappend newlst $srf
		}
	}
	set surfNormalRefAny $newlst
	if $msrfs {
		ic_mess "Faceted surfaces ignored $msrfs\n"
	}
    if {($surfNormalRefAny != "") && $auto_pick_mode} {
        repairGeomDEZ apply
		surfNormalPickAny pick
    }
}
#---------------------------

proc oncreateSurfNormalsLoad {} {
   ic_mess "Build topology in order to make normals consistent\n"

   #ic_geo_configure_one_attribute surface draw_norm 1

   # to keep it consistent with menu check for Surfaces

   global aie_ColorByNormal
   if {!$aie_ColorByNormal} {
      set aie_ColorByNormal 1
      ::AIEnv::GUIManagement::Tree::ShowSurfaceNormalsColor
   }
}
#----------------------
proc oncreateSurfEdgPickFinish {} {
    if {($curveList != "") && $auto_pick_mode} {
        createSurfsDEZ apply
	createSurfEdgPick pick
    }
}		
proc oncreateSurfSimple4ptsFinish {} {
    if {$auto_pick_mode && $Simple4ptsList != ""} {
    	createSurfsDEZ apply
    	createSurfSimple4pts pick
    }
}	
proc oncreateSurfSimpleCrvsFinish {} {
    if {$auto_pick_mode && $curveList != ""} {
    	createSurfsDEZ apply
    	createSurfSimpleCrvs pick
    }
}


#-----------------------------------------------0
proc oncreateSurfDrivPickFinish {} {
    if {($curveDrivingList != "") && $auto_pick_mode} {
	createSurfDrivenPick pick
    }
}
#---
proc ExtSrfEvaluateProc {} {
	::AIEnv::DEZ::createSurfsDEZ::ExtSrfEval
}
namespace eval ::AIEnv::DEZ::createSurfsDEZ {
proc ExtSrfEval {} {
foreach v {midparts extend_method extendlist proximity} {
	variable $v
}
	set mpartsmethod [lsearch $extendlist $extend_method]
	if {$mpartsmethod < 0} {
		ic_mess "DB something wrong: $extendlist ; $extend_method\n"
		return
	}
	variable arr_crv_proj

	ic_image delete
	foreach arr {arr_crv arr_crv_tan arr_stat arr_crv_proj arr_crv_dir} {
		if [info exists $arr] {unset $arr}
	}
	if ![llength $midparts] {
		ic_mess "No parts\n" red
		return 0
	}
	# parameters on curves:
    set check_pts 3
	set par_list ""
	set par_list [expr 0.5/$check_pts]
	set par_incr [expr $par_list*2.0]
	set par_cur $par_list
	for {set i 1} {$i < $check_pts } {incr i} {
		set par_cur [expr $par_cur+$par_incr]
		lappend par_list $par_cur
	}
	# single curves settings
	foreach p $midparts {
		# check single curves and distances
		set crvs [ic_geo_get_objects curve $p]
		foreach crv $crvs {
			set srfs [ic_geo_incident curve $crv]
			if {[llength $srfs] != 1} continue
			set res [ic_pre_get_crv_dir $crv $par_list]
			if {$res == ""} continue
			set arr_crv($crv) [lindex $res 0]
			set arr_crv_tan($crv) [lindex $res 1]
			set arr_crv_dir($crv) [lindex $res 2]
		}
	}
	if ![array exists arr_crv] {
		ic_mess "No single curves in selected parts\n"
		return 0 
	}
# Project curve from one part to surfaces from other part
			
	if {[llength $midparts] > 2} {
		ic_mess "Wait, please...\n"
	}
	# set tag for single curves selection:
	b ic_geo_set_tag clear "" curve.single 0
	ic_geo_set_tag curve [array names arr_crv] curve.single 1
	if ![va_is_int_or_real $mpartsmethod ] {set mpartsmethod 0}

	# create list of surfaces except current part (for distance check) 
	set actual_distance 1e8 
	set tol_constraint 0 
	set n_total 0

		foreach crv [array names arr_crv] {
			set the_srf [ic_geo_incident curve $crv]
			set the_part [ic_geo_get_family surface $the_srf]
		set n_proj 0
		foreach p $midparts {
			if {$the_part == $p} continue
#===============================
		if !$mpartsmethod {
				set res [ic_pre_project_nearest_srfs part $p $arr_crv($crv) $arr_crv_tan($crv) 15 0]
				if {$res == ""} continue
		} else {
				set res [ic_pre_project_tangent_srfs part $p $arr_crv($crv) $arr_crv_dir($crv) 0]
				if {$res == ""} continue
			# for tangent do not project if ::geo_cad(toler) > nearest
				if {$::geo_cad(toler) >= [lindex $res 1]} continue			 
		}
			set d [lindex $res 0]
# do not extend if ::geo_cad(toler) more then max projection
			if {$::geo_cad(toler) >= $d} {
				if {$tol_constraint < $d} {set tol_constraint $d}
				continue
			}
			if {$d < $actual_distance} {set actual_distance $d}
			if {$d > $proximity} continue
			# create image and add data
			if !$mpartsmethod {
			set res [ic_pre_project_nearest_srfs part $p $arr_crv($crv) $arr_crv_tan($crv) 15 1]
			} else {
			set res [ic_pre_project_tangent_srfs part $p $arr_crv($crv) $arr_crv_dir($crv) 1]
			}
			set n_res [llength $res]
			for {set i 0} {$i < $n_res } {incr i} {
			ic_image arrow_im ${i}.${n_proj}.$crv [lindex $arr_crv($crv) $i] [lindex $res $i]
			}		 
			lappend arr_crv_proj($crv) $p
			incr n_total
			incr n_proj
		}
		}
	set n_single [llength [array names arr_crv]]

	ic_mess "Statistics:\n"
	ic_mess "$n_single single curves.\n"	
	if ![array exists arr_crv_proj] {
		set ms "No gaps found in the range $::geo_cad(toler) to $proximity.\n"
		append ms "Increase \"Max distance\" at least to $actual_distance\n"
		if $tol_constraint {
			append ms "Or set tolerance less than $tol_constraint\n"
		}
		ic_mess $ms
		return 0 
	}
	foreach crv [array names arr_crv_proj] {
		set np [llength $arr_crv_proj($crv)]
		if ![info exists arr_stat($np)] {
			set arr_stat($np) 1
		} else {
			incr arr_stat($np)
		}
	}
#	ic_image min_length arrow_im init 0

	foreach n [lsort -integer [array names arr_stat]] {
		ic_mess "$arr_stat($n) curve(s) have $n extension(s) from each curve\n"
	}
	ic_mess "$n_total total valid single curves extensions for range: from $::geo_cad(toler) to $proximity\n"
	return $n_total
#	ic_image set arrow_im -color white width 4
}
}
proc imagesizeProc {} {
	if $imagesize {
		ic_image min_length arrow_im screen 20
	} else {
		ic_image min_length arrow_im reset 0
	}
}
#	entityChooser ExtSrfImageP "Delete" ext_image
proc onExtSrfImagePPick {} {
	if ![info exists arr_crv_proj] {
		ic_mess "No midsurface extensions. Use \"Preview Vectors\"\n"
		ExtSrfImageP cancelpick
	}
}
proc onExtSingleCrvPick {} {
	if ![info exists arr_crv] {
		ic_mess "Press \"Preview Vectors\"\n"
		ExtSingleCrv cancelpick
	}
}

proc onExtSingleCrvFinish {} {
# Add only one projection if more are valid
	set mpartsmethod [lsearch $extendlist $extend_method]
	if {$mpartsmethod < 0} {
		ic_mess "DB something wrong: $extendlist ; $extend_method\n"
		return
	}

	if [va_is_triplet $ext_single] {
	# must be single curve
		set crv [set ::va_set(names_for_coords)]
		# project and add in list or explain what's wrong
	} else {
		return
	}
	set ext_single $crv

	# exclude curve incident part and already selected parts
	set srf     [ic_geo_incident curve $crv]
	set res [ic_pre_get_crv_dir $crv "0.25 0.5 0.75"]
	set arr_crv($crv) [lindex $res 0]
	set arr_crv_tan($crv) [lindex $res 1]
	set arr_crv_dir($crv) [lindex $res 2]
	set exclude [ic_geo_get_family surface $srf]
	if [info exists arr_crv_proj($crv)] {
		set n_proj [llength $arr_crv_proj($crv)]
		append exclude " " $arr_crv_proj($crv)
	} else {
		set n_proj 0
	}		
	set use_parts ""
	foreach p $midparts {
		if {[lsearch $exclude $p] >= 0} continue
		lappend use_parts $p
	}  
	set srfs ""
	set add_part ""
	if ![llength $use_parts] {
		ic_mess "No valid parts for selected curve\n"
		return
	} 
	set min_dist_to_valid_part 1e9
	foreach p $use_parts {	
		if !$mpartsmethod {
			set res [ic_pre_project_nearest_srfs part $p $arr_crv($crv) $arr_crv_tan($crv) 15 0]	
		} else {
			set res [ic_pre_project_tangent_srfs part $p $arr_crv($crv) $arr_crv_dir($crv) 0]
		}
		if {$res != ""} {
			set max_dist [lindex $res 0]
			if {$max_dist < $min_dist_to_valid_part} {
				set min_dist_to_valid_part $max_dist
				set add_part $p
			}
		}	
	}
	if {$add_part != ""} {
		if !$mpartsmethod {
			set res [ic_pre_project_nearest_srfs part $add_part $arr_crv($crv) $arr_crv_tan($crv) 15 1]

		} else {
			set res [ic_pre_project_tangent_srfs part $add_part $arr_crv($crv) $arr_crv_dir($crv) 1]
		}
		set n_res [llength $res]
		for {set i 0} {$i < $n_res } {incr i} {
			ic_image arrow_im ${i}.${n_proj}.$crv [lindex $arr_crv($crv) $i] [lindex $res $i]
		}		 
		lappend arr_crv_proj($crv) $add_part
	}

# Info:
	if [info exists arr_stat] {unset arr_stat}
	foreach crv [array names arr_crv_proj] {
		set np 0
		foreach p $arr_crv_proj($crv) {
			if {$p == "none"} continue
			incr np
		}
		if !$np continue
		if ![info exists arr_stat($np)] {
			set arr_stat($np) 1
		} else {
			incr arr_stat($np)
		}
	}
	foreach n [lsort -integer [array names arr_stat]] {
		ic_mess "$arr_stat($n) curve(s) have $n extension(s) from each curve\n"
	}
#



    if {$auto_pick_mode} {
		ExtSingleCrv pick
    }
}
proc onExtSrfImagePFinish {} {
	if {$ext_image == ""} return
# format: 1.1.crv 
#
# check that it's a special image with name n.m.curve
# where n < 10 - point on curve m < 10 - which projection from the same curve
	
	if {([string index $ext_image 1] != ".") || ([string index $ext_image 3] != ".")} return
	set check_pts 3
	# image projection		
	set crv [string range $ext_image 4 end]
	if ![info exists arr_crv_proj($crv)] {
		ic_mess "Wrong image\n"
		return
	}
	set parts $arr_crv_proj($crv)
	set n [string index $ext_image 2]
	# use word "none" to mark deleted curves, but keep the same n
	set arr_crv_proj($crv) [lreplace $parts $n $n none]
	for {set i 0} {$i < $check_pts} {incr i} {
		ic_image delete ${i}.${n}.$crv
	}
	# end of image work
# Info:
	if [info exists arr_stat] {unset arr_stat}
	foreach crv [array names arr_crv_proj] {
		set np 0
		foreach p $arr_crv_proj($crv) {
			if {$p == "none"} continue
			incr np
		}
		if !$np continue
		if ![info exists arr_stat($np)] {
			set arr_stat($np) 1
		} else {
			incr arr_stat($np)
		}
	}
	foreach n [lsort -integer [array names arr_stat]] {
		ic_mess "$arr_stat($n) curve(s) have $n extension(s) from each curve\n"
	}
#
    if {$auto_pick_mode} {
		ExtSrfImageP pick
    }
}

proc oncreateSurfDrivenPickFinish {} {
    if {($curveDrivenList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfDrivPick pick
    }
}
#-----------------------------------------------1
proc oncreateSurfPDPickFinish {} {
    if {($crvSweepDList != "") && $auto_pick_mode} {
	createSurfCurveDPick pick
    }
}

proc oncreateSurfPPickFinish {} {
    if {($pntSweepVecList != "") && $auto_pick_mode} {
	createSurfCurvePick pick
    }
}

proc oncreateSurfDCurvePickFinish {} {
    if {($curveSweepDrvList != "") && $auto_pick_mode} {
	createSurfCurvePick2 pick
    }
}
#---
proc oncreateSurfCurveDPickFinish {} {
    if {($curveSweepList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfPDPick pick
    }
}
proc oncreateSurfCurvePickFinish {} {
    if {($curveSweepList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfPPick pick
    }
}
proc oncreateSurfCurvePick2Finish {} {
    if {($curveSweepList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfDCurvePick pick
    }
}
#-----------------------------------------------2

proc oncreateSurfRevAxisPickFinish {} {
    if {($curveRevAxis != "") && $auto_pick_mode} {
	createSurfRevCrvPick pick
    }
}
#----
proc oncreateSurfRevCrvPickFinish {} {
    if {($curveRevList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfRevAxisPick pick
    }
}
#----------------------------------------------3

proc oncreateSurfOffsetPickFinish {} {
    if {$offsetSurfList == ""} return
    if {($offsetdist != 0 ) && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfOffsetPick pick
    }
}
#----------------------------------------------4
proc oncreatePartMidPickFinish {} {
    # No automatically apply for Midsurface - wait for user apply
}

#----------------------------------------------5
proc onSurfThickPickFinish {} {

    set thickness2 [ic_geo_surface_thickness [lindex $surfaces 0] 2]
    set thickness3 [ic_geo_surface_thickness [lindex $surfaces 0] 3]
    set thickness4 [ic_geo_surface_thickness [lindex $surfaces 0] 4]
    
    set M12 [lindex $thickness3 1]
    set M13 [lindex $thickness3 3]
    set M [lindex $thickness3 4]
    set M24 [lindex $thickness3 5]
    set M34 [lindex $thickness3 7]
    
    set M1t2 [lindex $thickness4 1]
    set M1tt2 [lindex $thickness4 2]
    set M1t3 [lindex $thickness4 4]
    set M1 [lindex $thickness4 5]
    set M2 [lindex $thickness4 6]
    set M2t4 [lindex $thickness4 7]
    set M1tt3 [lindex $thickness4 8]
    set M3 [lindex $thickness4 9]
    set M4 [lindex $thickness4 10]
    set M2tt4 [lindex $thickness4 11]
    set M3t4 [lindex $thickness4 13]
    set M3tt4 [lindex $thickness4 14]
    
    switch -- $createThickAdjOrderVal {
	0 {
	    set thickness [ic_geo_surface_thickness [lindex $surfaces 0] 2]
	    #mess "thickness is $thickness\n"
	    set C1 [lindex $thickness2 0]
	    set C2 [lindex $thickness2 1]
	    set C3 [lindex $thickness2 2]
	    set C4 [lindex $thickness2 3]
	}
	1 {
	    set thickness [ic_geo_surface_thickness [lindex $surfaces 0] 3]
	    #mess "thickness is $thickness\n"
	    set C1 [lindex $thickness3 0]
	    set C2 [lindex $thickness3 2]
	    set C3 [lindex $thickness3 6]
	    set C4 [lindex $thickness3 8]
	}
	2 {
	    set thickness [ic_geo_surface_thickness [lindex $surfaces 0] 4]
	    #mess "thickness is $thickness\n"
	    set C1 [lindex $thickness4 0]
	    set C2 [lindex $thickness4 3]
	    set C3 [lindex $thickness4 12]
	    set C4 [lindex $thickness4 15]
	}
    }
}

proc onSurfThickPickMidsFinish {} {
    # No automatically apply for Assign Thickness from Solid - wait for user apply
#    if {($midsurfaces != "") && $auto_pick_mode} {
#	ic_mess "Select solid surfaces\n"
#	SurfThickPickSolid pick
#    }	
     set max_thickness ""
     foreach obj $midsurfaces {
	set thickness [ic_geo_surface_thickness $obj $thick_order]
	set mthick [lindex [lsort -real $thickness] end]
	if {$max_thickness ==""} {
	  set max_thickness $mthick
	} else {
	  if {$max_thickness != $mthick} {
	     set max_thickness ""
	     return
	  }
	}
     }
}

proc onSurfThickPickSolidFinish {} {
    # No automatically apply for Assign Thickness from Solid - wait for user apply
#    if {($solidsurfaces != "") && $auto_pick_mode} {
#        repairGeomDEZ apply
#	ic_mess "Select midsurfaces\n"
# 	SurfThickPickMids pick
#    }	
}

#----------------------------------------------6

proc oncreateSurfLoftPickFinish {} {
    if {($loftsurfList != "") && $auto_pick_mode} {
        createSurfsDEZ apply
	createSurfLoftPick pick
    }
}

proc oncreatePairSurfMidPick1Finish {} {
    if {$midsurfList != ""} {
        mess "Select surface for side 2\n"
	createPairSurfMidPick2 pick
    }
}

proc oncreatePairSurfMidPick2Finish {} {
    if {$midsurfList2 != ""} {
        createSurfsDEZ apply
    }
}

#-----------------------------------------------7

proc onCurtSurfCurvPickFinish {} {
    if {($CurtSurfCurvList !="") && $auto_pick_mode} {
	createCurtSurfSurfPick pick
    }
}

proc oncreateCurtSurfSurfPickFinish {} {
    if {($CurtSurfSurfList !="") && $auto_pick_mode} {
	createSurfsDEZ apply
    }
}

proc oncreateSurfTrmCurvePickPick {} {
#  
#	ic_highlight solid 0 surface $crvSurfTrmSurfList
#	ic_highlight solid 1 surface $crvSurfTrmSurfList
}

proc oncreateSurfTrmSurfPickFinish {} {
    if {($crvSurfTrmSurfList != "") && $auto_pick_mode} {createSurfTrmCurvePick pick}
}

proc oncreateSurfTrmSurfPick2Finish {} {
    if {($crvSurfTrmSurfList == "") || !$auto_pick_mode} return
    switch $modSegmPlaneNormEGVal {
        0 { segPlanePointnrm1 pick }
        1 { 
            segPlanePoint1 pick
            segPlanePoint2 pick
            segPlanePoint3 pick
        }
    }
}

proc oncreateSurfTrmCurvePickFinish {} {
    if {($crvSurfTrmCurveList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfTrmSurfPick pick
    }
}

proc onsegPlanePointnrm1Pick {} {
    if {$createSurfsEXGVal != 7} return
    if {$crvSurfTrmSurfList == ""} {
        mess "Select surface first\n" red
        return
    }
    set va_set(pln_pnt1) [ic_coords_into_global [createSurfsDEZ get SegPlanePntList]]
    aie_cr_geom_plane pointandplane "" createSurfsDEZ segPlanenormal
}

proc onsegPlanePointnrm1Finish {} {
    global auto_pick_mode

    if $auto_pick_mode {
 		createSurfsDEZ apply
 		createSurfTrmSurfPick2 pick
    }
}

proc onsegPlaneAxisPntPlnLoad {} {
    global auto_pick_mode
    if {$createSurfsEXGVal != 7} return
    if $auto_pick_mode {
        segPlanePointnrm1 pick
    }
}

proc onsegPlaneAxisThreepntLoad {} {
    global auto_pick_mode
    if $auto_pick_mode {
        segPlanePoint1 pick
        segPlanePoint2 pick
        segPlanePoint3 pick	
    }	
}

proc onsegPlanePoint1Pick {} {
	global va_set
	
	foreach p {1 2 3} {
		set xyz [createSurfsDEZ get SegPlanePnt$p]
		set va_set(pln_pnt$p) [ic_coords_into_global $xyz]
	}
	
	aie_cr_geom_plane threepoints 1

}

proc onsegPlanePoint2Pick {} {
	global va_set tdv_default
	
		foreach p {1 2 3} {
		set xyz [createSurfsDEZ get SegPlanePnt$p]
		set va_set(pln_pnt$p) [ic_coords_into_global $xyz]
	}
	
	aie_cr_geom_plane threepoints 2		

}

proc onsegPlanePoint3Pick {} {
	global va_set tdv_default
	
		foreach p {1 2 3} {
		set xyz [createSurfsDEZ get SegPlanePnt$p]
		set va_set(pln_pnt$p) [ic_coords_into_global $xyz]
	} 
	
	aie_cr_geom_plane threepoints 3

}		
	


#----------------------------------------------9

proc onmodifySurfMergeSurfFinish {} {
	    if {($modSurfMergeList != "") && $auto_pick_mode} {
		createSurfsDEZ apply
		modifySurfMergeSurf pick
	    }
	}
proc onreapproxSelSurfFinish {} {
	    if {($reappSurfList != "") && $auto_pick_mode} {
		createSurfsDEZ apply
		reapproxSelSurf pick
	    }
	}
proc onreapproxSelSurf1Finish {} {
	    if {($reappSurf1List != "") && $auto_pick_mode} {
	    reapproxSelCur1 pick
	}
}
proc onreapproxSelCur1Finish {} {
	if {($reappCur1List != "") && $auto_pick_mode} {	
		createSurfsDEZ apply
		reapproxSelSurf1 pick
	    }
	}
proc onreapproxSelSurf2Finish {} {
	    if {($reappSurf2List != "") && $auto_pick_mode} {
		createSurfsDEZ apply
		reapproxSelSurf2 pick
	    }
	}
proc onreapproxEachSurfFinish {} {
	    if {($reappEachSurfList != "") && $auto_pick_mode} {
		createSurfsDEZ apply
		reapproxEachSurf pick
    }
}
#----------------------------------------------10

proc onconvexHullSurfPickFinish {} {
    if { ($convexHullSurList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	convexHullSurfPick pick
    }
}
#-----------------------------------------------11
proc onStdSphChooserFinish {} {
    if {($StdSphereList !="") && $auto_pick_mode} {
	createSurfsDEZ apply
	StdSphChooser pick
    }
}
proc onboxAxesPPickFinish {} {
    if {($boxAxPntList !="") && $auto_pick_mode} {
	createSurfsDEZ apply
	boxAxesPPick pick
    }
}
proc oncylAxisPPickFinish {} {
    if {($cylAxPntList !="") && $auto_pick_mode} {
	createSurfsDEZ apply
	cylAxisPPick pick
    }
}
#-----------------------------------------------12

proc onmodFaceSrfLoad {} {
    set allsurf ""
    set coarsentol 1
    if [ic_geo_is_loaded] {
        set allobj [ic_geo_lookup surface all]
        foreach obj $allobj {
            set a [lindex $obj 1]
            if {[ic_geo_get_object_type surface $a] =="mesh"} {
		lappend allsurf $a
            }
	}
	
        if {$allsurf !=""} {
            set minl [ic_geo_min_edge_length surface $allsurf]
            mess "\nMin edge of all geometry: $minl\n" blue
            set coarsenFacetTol [expr $minl/10]
	} 
    }
    
    set keepOriginSurfFlag 0
    set coarsenCurveList ""
    set coarsenPointList ""
}

proc onmodifyfacetPickFinish {} {
    if { ($modFacetSurfList != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	# modifyfacetPick pick
    }
}
#------------------------------------------------13 Facet Tools2, segment
proc onPlanePPickFinish {} {
    if { ($planePntList != "") &&  $auto_pick_mode} {
	createSurfsDEZ apply
    }
}
#------------------------------------------------14 Segment surfaces

#------------------------------------------------Extend surfaces
proc oncreateExtSurfEdgeLoad {} {
	ic_image delete
	# user must select Method every time in order to evaluate
	set imagesize 0
    switch $createSurfExtMethodVal {
	0 {
	     if $auto_pick_mode {createSurfacePickExtendC pick}
	}
	1 {
	    if $auto_pick_mode {ExtSrfAtEdgeSrfPick pick}
	}
    }
}
#-----
proc oncreateSurfaceExtendSurfLoad {} {
    if $auto_pick_mode {createSurfacePickExtendC pick}
}
#-----------------------------------------------
proc oncreateSurfacePickExtendCFinish {} {
    if {($ExtendCurve != "") && $auto_pick_mode} {
	createSurfacePickExtendS pick
    }
}
#-----------------------------------------------
proc oncreateSurfacePickExtendSFinish {} {
    if {($ExtendSurf != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	createSurfacePickExtendC pick
    }
}
#-----
proc oncreateExtSurfacEdgeLoad {} {
    if $auto_pick_mode {ExtSrfAtEdgeSrfPick pick}
}
#-----------------------------------------------
proc onExtSrfAtEdgeSrfPickFinish {} {
    if {($ExtSrfAtEdgeSrf != "") && $auto_pick_mode} {
	ExtSrfAtEdgeCurveEntry pick
    }
}
#-----------------------------------------------
proc onExtSrfAtEdgeCurveEntryFinish {} {
    if {($ExtSrfAtEdgeEdgenum != "" && $ExtSrfAtEdgeDistance != "") && $auto_pick_mode} {
	createSurfsDEZ apply
	ExtSrfAtEdgeSrfPick pick
    }
}


#_______________________________________________________________________________
#------------------------ Body --------------------------------------------------

proc oncreateBodyDEZOK {} {
    global geom_visible

	set part_name [aie_delete_any_space $part_name]
	set name [aie_delete_any_space $name]

    if {$part_name == ""} {
        set part_name "BODY"
    }
    
    if [ic_hex_subset_named_selection $part_name] {
        mess "Error: a named selection subset with name \"$part_name\" already exists; use some other part name\n" red
        return
    }
    
    if ![ic_geo_check_part $part_name] {
        aie_new_part $part_name
    } else {
        set part_name [aie_new_part $part_name]
    }
    if ![info exists createBodyEXGVal] return
    
    set objs 0
    foreach type "surface curve point" {
        incr objs [llength [ic_geo_get_objects $type $part_name]]
    }
	if $objs {
	    set mess "Part $part_name contains geometry objects.\nThis is not recommended and could cause problems.\
	        \nPlease select another part name for \"Create Body\"."
        msg ERROR "$mess"
		return
	}

    switch -- $createBodyEXGVal {
	1 {
	    set need_build_topo 0
	    if $createBodyTopoGGVal {
		if {$surfList == ""} {
		    mess "Warninng: Please select enclosed surfaces\n" red
		    return
		}
		set surfs $surfList
	    } else {
		set surfs [ic_geo_get_objects surface]
	    }

	    foreach surf $surfs {
		if {[ic_geo_boundary surface $surf] == ""} {
		    set need_build_topo 1
		    break
		}
	    }

	    if {$need_build_topo && $createBodyTopoGGVal == 1} {
            set mess "This feature needs geometry connectivity. Do you want to run build topology?"
            switch -- [tk_dialog .bodywarn "Create body warning" $mess "" -1 Yes No] {
                0 {
                    aie_apply_other_dez repairGeomDEZ repairSurfaceEGVal 0
                    ic_undo_suspend
                }
                1 - -1 {
                    if [winfo exists .bodywarn] { top_destroy .bodywarn } 
                    return
                }
            }
        }

	    switch -- $createBodyTopoGGVal {
		0 {
		    set from_solids 0
		    if [ic_geo_count_solids_without_material] {
		        set mess "Geometry already contains solids. Create bodies from existing solids?"
		        switch -- [tk_dialog .bodywarn "Create body by topology" $mess "" -1 Yes No] {
		            0 {
			            set from_solids 1
		            }
		        }
		    }
		    
	        if {$need_build_topo && !$from_solids} {
                set mess "This feature needs geometry connectivity. Do you want to run build topology?"
                switch -- [tk_dialog .bodywarn "Create body warning" $mess "" -1 Yes No] {
                    0 {
                        aie_apply_other_dez repairGeomDEZ repairSurfaceEGVal 0
                        ic_undo_suspend
                    }
                    1 - -1 {
                        if [winfo exists .bodywarn] { top_destroy .bodywarn } 
                        return
                    }
                }
	        }
		    
		    ic_delete_elements family $part_name no_undo 1
		    ic_geo_build_bodies $part_name 0 0 0 1 "" $createAssemblyFlag $from_solids
			mess "Build completed.\n" blue
			aie_update_gui group
		}
		1 {
		    # something could have changed after build topo
		    foreach surf $surfList {
			    if {[ic_geo_check_objects_exist surface $surf] == ""} {
			        msg ERROR "surface: $surf does not exist"
			        return
			    }
		    }
		    ic_geo_create_body $surfList $name $part_name
		}
	    }
	}

	0 {
	    # Material point selection
	    switch -- $createBodyMatptGGVal {
            1 { # single
                if {[llength $pointList] == 1} {
                    if {[ic_csystem_get_current] != "global"} {
                        set xyz [ic_coords_into_global [ic_geo_get_point_location $pointList]]
                    } else {
                        set xyz [ic_geo_get_point_location $pointList]
                    }
                } elseif {[llength $pointList] == 3} {
                    if {[ic_csystem_get_current] != "global"} {
                        set xyz [ic_coords_into_global $pointList]
                    } else {
                        set xyz $pointList
                    }
                } else {
				    ic_mess "Select location\n" red
				    return
			    }
		    }
		    0 { # center
                if {[llength $pointList2] != 2} {
				    ic_mess "Select 2 locations\n" red
				    return
			    }
                if {[ic_csystem_get_current] != "global"} {
                    if {[llength [lindex $pointList2 0]] == 1} {
                        set p1  [ic_coords_into_global [ic_geo_get_point_location [lindex $pointList2 0]]]
                    } else {
                        set p1 [lindex $pointList2 0]
                    }
                    if {[llength [lindex $pointList2 1]] == 1} {
                        set p2  [ic_coords_into_global [ic_geo_get_point_location [lindex $pointList2 1]]]
                    } else {
                        set p2 [lindex $pointList2 1]
                    }
			        set xyz [ic_coords_into_global [ic_vcalc sum_smult $p1 $p2 0.5]]
			    } else {
			        set xyz [ic_vcalc sum_smult [lindex $pointList2 0] [lindex $pointList2 1] 0.5]
			    }
		    }
		    default return
	    }
	    ic_geo_create_volume $xyz $name $part_name
	}
    }
    aie_updateGeoVis body 1 1
    ic_undo_resume
}
proc oncreateBodyDEZAfterOK {} {
    aie_create_parts_in_tree_if_needed 
    aie_update_icons geom
}

proc onCreateBodyFamModify {dez val} {
    if {$val == "From screen"} {
	createBodyDEZ set part_name [geo_select_part_from_screen 1]
    }
}
#---------------------------------------------------------------------
proc oncreateBodyDEZLoad {} {

    set PartList [aie_list_parts 1]
    lappend PartList ORFN
    aie_show_name createBodyName [aie_gui_get vid_options(show_item_name)]	
	set part_name [aie_delete_any_space $part_name]
	set name [aie_delete_any_space $name]
    if {$part_name == ""} {
	    set part_name [::AIEnv::GUIManagement::Tree::getSelection part]
        if {$part_name == ""} {set part_name BODY}
    }

    set topoang 30
    set FilterPntsFlag 0
    set FilterCrvsFlag 0
    set RegSurfFlag 1
    set JoinEdgesFlag 0
 
    set ActFamFlag 0
    set DelUnattFlag 1
    set createAssemblyFlag 0
}

proc oncreateBodyDEZUnLoad {} {
    #ic_undo_resume
}

#----------------------------------------------------------------------
proc oncreateBodyMatPntLoad {} {
    ::AIEnv::GUIManagement::ToggleGrey createBodyName 0
    if $auto_pick_mode {
	if {$createBodyMatptGGVal == 0} {
	    matptPick2 pick
	}
	if {$createBodyMatptGGVal == 1} {
	    matptPick pick
	}
    }
}
#------------------------------------
proc oncreateBodyTopoLoad {} {
    if {$createBodyTopoGGVal == 1 && $auto_pick_mode} {createBodyPick pick}
}
#-----------------------------------
proc oncreateBodyPickFinish {} {
    if {$surfList != "" && $auto_pick_mode} {
	createBodyDEZ apply
	createBodyPick pick
    }
}
#------------------------------------
proc onmatptPickFinish {} {
    if {$pointList != "" && $auto_pick_mode} {
	createBodyDEZ apply
	matptPick pick
    }
}
proc onmatptPick2Finish {} {
    if {$pointList2 != "" && $auto_pick_mode} {
	createBodyDEZ apply
	matptPick2 pick
    }
}

proc aie_geo_build_material_from_solids {} {
    ic_geo_build_material_from_solids
    aie_create_parts_in_tree_if_needed
    aie_update_parts_in_tree_if_needed
    aie_delete_empty_parts
    aie_updateGeoVis body 1 1
}

proc aie_geo_remove_solids_without_material {} {
    ic_geo_remove_solids_without_material
    aie_create_parts_in_tree_if_needed
    aie_update_parts_in_tree_if_needed
    aie_delete_empty_parts
    aie_updateGeoVis body 1 1
}

proc aie_geo_autosizing_from_body {} {
    set max_size [ic_autosizing tetra]
    foreach bdy [ic_geo_get_objects body] {
        set surfs ""
        foreach {t n} [ic_geo_body_lower_entities $bdy] {
            if {$t == "surface"} { lappend surfs $n }
        }
        if {$surfs == ""} continue
        set surfs [list surface $surfs]
        set bbox [ic_geo_bounding_box $surfs]
        set dist [eval ic_vcalc distance $bbox]
	    set size [expr 0.1 * $dist]
	    if {$max_size != 0 && $max_size < $size} continue
	    set max_size $size
	}
    return $max_size
}

proc aie_geo_reduce_number_of_parts {} {

    set types [ic_geo_get_types]
    set parts [aie_list_parts 0]
    set len [llength $parts]
    foreach p $parts {
        if [regexp \# $p] {
            set pp [lindex [split $p #] 0]
            foreach type $types {
                set objs [ic_geo_get_objects $type $p 1]
                if {$type == "material" || $type == "body"} {
                    if [ic_geo_count_in_family "surface curve point" $pp] continue
                }
                if {$objs != ""} {
                    ic_geo_set_family $type $pp names $objs 0
                }
            }
        }
    }
    aie_delete_empty_parts
    aie_create_parts_in_tree_if_needed
    aie_update_parts_in_tree_if_needed
    mess "Reduced number of parts from $len to [llength [aie_list_parts 0]]\n" blue
}

#_______________________________________________________________________________
#------------------------ Create Modify Facets ---------------------------------

proc oncreateFacetedDEZLoad {} {
	aie_default_topo_tolerance
	
 # do not select on first load: set invalid selection value
	if ![info exists Faceted_0_EXGVal] {
		set Faceted_0_EXGVal -1
		set modifyFacetCleanEXGVal -1
		set f_1_EXGVal -1
		set modifyFacetSurfEXGVal -1
    set ::va_set(create_smooth_curveFlag) 0
    set ::va_set(create_closed_curveFlag) 0		
	}
	aie_show_name createFacetedName [aie_gui_get vid_options(show_item_name)]	
    set PartList [aie_list_parts 1]
    set ::geo_part_name [aie_geo_set_part_name]
    set part_name [aie_geo_set_part_name $::geo_part_name]
    if {$name == ""} {set name facet.00}
    set name [ic_vset -new_name $name all]	
	set coarsentol .01
	set mtol .01
	::AIEnv::GUIManagement::ToggleGrey createFacetedFam [aie_check_inherit_fam]
	set modFaceSrfDelGGVal 0
    if {$smooth_tol == ""} {set smooth_tol 1.0}
    if {![info exists width] || ($width == "")} {
	set n_slice 5
	set width 5
	set TrimFlag 0
	set RemFlag 0
    }
}

proc oncreateFacetedDEZOK {} {
#
# "OK" & "APPLY" set "busy signal" 1. It is necessary in order to avoid 100s busy pairs.
# But there are several irregular Faceted functions:
#  instead of "picker" they use some custom picking functions
# Until AI*GUI pickers will replace these irregularity, keep next "busy reset" line:
  busy reset
#
    global geom_visible fam_visible va_set

    if {![aie_check_inherit_fam] && [ic_hex_subset_named_selection $::geo_part_name]} {
        mess "Error: a named selection subset with name \"$::geo_part_name\" already exists; use some other part name\n" red
        return
    }
    
    set part_name [aie_geo_set_part_name $::geo_part_name]  
    set part_name [aie_new_part $part_name]
    set nnames ""
    set fam $part_name   

    switch -- $Faceted_0_EXGVal {
	0 {	    
	    switch -- $f_1_EXGVal {
		0 {
		    set Nurb2FacetList [aie_set_faceted 0 curve $Nurb2FacetList]
		    if ![llength $Nurb2FacetList] {
			ic_mess "Select b-spline curves\n" red
			return
		    }
		    set ta [tdv_active 0]
		    busy 1
		    set nnames ""
		    foreach obj $Nurb2FacetList {
                        set vis [ic_geo_get_visibility curve $obj]
			set msh_par [ic_set_meshing_params curve $obj]
			set new [ic_facetize_geometry curve $obj]
			if [llength $new] {
			    set newname [va_auto_name curve ${obj}.$name]
		            ic_geo_set_name curve $new $newname 
			    eval "ic_set_meshing_params $newname $msh_par"
			    lappend nnames $newname
			}
			if {$keepOriginCurvFlag == 0} {
			    ic_delete_geometry curve names $obj
			}
                        if {!$vis && [llength $new]} {
                            ic_geo_temporary_visible curve $newname 0
                        }
		    }
		    if ![aie_check_inherit_fam] {
			ic_geo_set_family curve $fam names $nnames 0
		    }
		    busy 0
		    tdv_active $ta
		}
		
		1 {
		    # Create Curve
		    aie_check_inherit_fam fam point $FacePtsList
		    set coords [va_check_data_set_points $FacePtsList keep $fam $name.00]
		    if {[llength $coords] < 2} return
		    # curve may be created during "pick". Next line try delete such curve.
		    if {[ic_gui_set va_set(name)] == $name} {ic_delete_geometry curve names $name 0}
		    set nnames [ic_geo_create_unstruct_curve_from_points $name $fam $coords]   
		}		
		2 {
		    # Move node
		    switch -- $modFaceMoveNodeEGVal {
			0 {
			    aie_geo_modify_movenode curve none
			}
			1 {
			    aie_geo_modify_movenode curve loc $pickMoveNodeLoc
			}
			2 {
			    switch -- $modFaceCrvNormEGVal {
				0 {set modFaceVector "1 0 0"}
				1 {set modFaceVector "0 1 0"}
				2 {set modFaceVector "0 0 1"}
				3 {}
			    }
			    aie_geo_modify_movenode curve plane $modFaceVector
			}
			3 {
			    aie_geo_modify_movenode curve surface $modConstSrf
			}
			4 {
			    aie_geo_modify_movenode curve line $pickMoveNodeLoc
			}
			5 {
			    aie_select_move_geo_nodes curve $moveNodesIncr
			}
		    }
		}
		3 {
		    # Merge node
		    geo_modify_mergenode curve
		}
		4 {
		    # Create Segment
		    geo_modify_object_add curve 2 segment
		}
		5 {
		    # Delete Segment
		    geo_modify_object_delete curve segment			
		}
		6 {
		    # Split Segment
		    geo_modify_splitseg curve segment 2			
		}
		7 {
		    # Restrict
		    geo_modify_object_restrict curve segment
		}
		8 {
		    # Move Segment to new curve fam
		    geo_modify_moveseg curve segment 1 $fam $name
		}
		9 {
		    # Move Segment to existing curve
		    geo_modify_moveseg curve segment 0
		}
		111 {
		    # Not used
		    switch -- $modifyFacetCurv2EXGVal {
			0 {
			    mess "segment curve by angle:$seg_angle2\n" blue
			    set modCurveHow angle
			    mess "the curve list:$modCurvSegList\n" blue
			    set new_crvs [ic_geo_create_curve_segment $modCurvSegList $modCurveHow angle $seg_angle2 keep_old 0]
			    set nnames [aie_set_part_and_new_names curve $new_crvs $fam $name]
			}
			1 {
			    mess "segment curve by point\n" blue
			    set modCurveHow point
			    set pickPointList [lindex $pickPointList 0]
			    if {[llength $pickPointList]==1} {
				set segPnt [ic_geo_get_point_location $pickPointList]
			    } else {
				set segPnt $pickPointList
				mess "segPnt:$segPnt\n"
				ic_geo_cre_pnt Temp $name $segPnt
			    }
			    mess "segpoint:$segPnt"
			    set new_crvs [ic_geo_create_curve_segment $modCurvSegList $modCurveHow point $segPnt keep_old 0]
			    set nnames [aie_set_part_and_new_names curve $new_crvs $fam $name]
			}
			2 {
			    mess "segment curve by lack of connectivity"
			}
		    }	
		}
	    }
	}

	1 { ;#+++++++++SURFACES
	    switch -- $modifyFacetSurfEXGVal {
                0 {
		    # Convert Bspline to Faceted
		    set Nurb2FacetList [aie_set_faceted 0 surface $Nurb2FacetList]
		    if ![llength $Nurb2FacetList] {
			ic_mess "Select b-spline surfaces\n" red
			return
		    }
		    busy 1
		    set ta [tdv_active 0]
		    set nnames ""
		    foreach obj $Nurb2FacetList {
                        set vis [ic_geo_get_visibility surface $obj]
			set msh_par [ic_set_meshing_params surface $obj]
			set new [ic_facetize_geometry surface $obj]
			if ![llength $new] continue
			set newname [va_auto_name surface ${obj}.$name]
			ic_geo_set_name surface $new $newname
			eval "ic_set_meshing_params surface $newname $msh_par"
			if {$keepOriginSurfFlag==0} {
			    ic_delete_geometry surface names $obj
			}
                        if {!$vis && [llength $new]} {
                            ic_geo_temporary_visible surface $newname 0
                        }
			lappend nnames $newname
		    }
		    if ![aie_check_inherit_fam] {
			ic_geo_set_family surface $fam names $nnames 0
		    }
		    tdv_active $ta
		    busy 0
		}
		1 {
		    # Restrict
		    if ![va_is_int_or_real $coarsentol] {
			mess "Set tolerance" red
			return
		    }
		    geo_coarsen_surface $coarsentol
		}	
		2 {
		    # Create New Faceted Surface
		    switch -- $modifyFacetSrfEGMVal {
			    0 {
			        switch -- $internalFlag {
				        0 { set bb bound_edge }
				        1 { set bb edge }
				        default { set bb bound_edge }
			        }
			        while 1 {
				        set edges [geo_select_segments all_surfaces "" $bb 0 0 0 0 0 1]
				        if {$edges == ""} {
				            return
				        } else {
				            set res [ic_geo_stlrepair_holes surface $edges $internalFlag $internalFlag $completeFlag "" $::geo_cad(toler)]
				        }
				        if !$res return
			        }
			    }
			    1 {
			        set n [llength $FacePtsList]
			        set res [ic_surface_from_points $FacePtsList $fam $name]
			    }
			    2 {
			        set n [llength $FacePtsList]
			        set res [ic_surface_from_points $FacePtsList $fam $name]
			    }
		    }
		}
		3 {
		    # Merge edges
		    switch -- $internalFlag {
			0 {set bb bound_edge}
			1 {set bb edge}
			default {set bb bound_edge}
		    }
		    set edges [geo_select_segments all_surfaces "" $bb 0 0 0 0 0 1]
		    if {$edges != ""} {
                        set non_vis ""
                        foreach s [ic_geo_get_objects surface] {
                            if ![ic_geo_get_visibility surface $s] {
                                lappend non_vis $s
                            }
                        }
			            ic_geo_stlrepair_edges surface $edges $mtol $mergeFlag
                        if {$non_vis != ""} {
                            ic_geo_temporary_visible surface $non_vis 0
                        }
		    }
		}
		4 {
		    geo_modify_splitedge surface
		}
		5 {
		    geo_modify_swapedge surface
		}			
		6 {
		    # Move node
		    switch -- $modFaceSrfNodeEGVal {
			0 {aie_geo_modify_movenode surface none}
			1 {aie_geo_modify_movenode surface loc $pickMoveNodeLoc}
			2 {
			    switch -- $modFaceSrfNormEGVal {
			        0 {set modFaceVector "1 0 0"}
			        1 {set modFaceVector "0 1 0"}
			        2 {set modFaceVector "0 0 1"}
			        3 {}
			    }
			    aie_geo_modify_movenode surface plane $modFaceVector
		        }
		        3 {aie_geo_modify_movenode surface line $pickMoveNodeLoc}
		        4 {aie_select_move_geo_nodes surface $moveNodesIncr}						
		    }
	        }
	        7 {
		    # Merge nodes
		    if !$modFaceSrfMNodesGGVal {
		    	geo_modify_mergenode surface
		    } else {
		        if ![va_is_int_or_real $mnodestol] {set mnodestol 1}
			    geo_modify_mergenode_tol surface $mnodestol
		       }
		    }
	        8 {
		    # Create Triangle
		    geo_modify_object_add surface 3 triangle
	        }
	        9 {
		    # Delete Triangle
		    if !$modFaceSrfDelGGVal {
		        geo_modify_object_delete surface triangle			
		    } else {
		        geo_modify_object_restrict surface triangle
		    }					
	        }
	        10 {
		    # Split Segment
		    geo_modify_splitseg surface triangle 3			
	        }
	        11 {
		    # Restrict
		    geo_modify_object_restrict surface triangle
	        }		
	        12 {
		    # Move Segment to new surface
		    geo_modify_moveseg surface triangle 1 $fam $name
	        }
	        13 {
		    # Move Segment to existing surface
		    geo_modify_moveseg surface triangle 0
	        }
	        14 {
		    # Merge 2 Surface
		     geo_modify_merge surface
	        }
	        222 {
		    mess "Operation Coarsen Facets Geometry\n" blue
		    set minl [ic_geo_min_edge_length surface $modFacetSurfList]
		    set coarsenFacetTol [expr $minl/10]
		    mess "Tolerance:$coarsenFacetTol\n"
		    mess "min length:$minl\n"
		    ic_geo_coarsen surfaces $modFacetSurfList curves $coarsenCurveList points $coarsenPointList tol $coarsenFacetTol n_iter 4 minl $minl
	        } 
	    }
        }

        2 { 
          # Faceted Cleanup
          # All cleanup functions require visible faceted surface!!!
          
        	if ![ic_geo_objects surface number only_if_faceted only_if_visible] {
              status_message "No faceted visible surfaces" red
              return
          }
        
        
        
	    switch -- $modifyFacetCleanEXGVal {		
	        0 {
		    switch $modifyFacetCleanAMVal {
		        0 {
			    aie_smooth_facet_edge_align_to_curve edge
		        }
		        1 {
			    aie_smooth_facet_edge_align_to_curve node
		        }    
		        2 {
			    aie_smooth_facet_edges $smooth_tol
		        }				
		    }
	        }
	        1 {
	            if [aie_check_inherit_fam] {
			        geo_stlrepair_holes 0 0 1 1 0 
		        } else {
		            geo_stlrepair_holes 0 0 1 1 0 "$fam"
		        }
	        }
	        2 {
	          # MP12 function
	          ic_delete_geometry curve names mp12_tmp_crv 0
                       
                   set resume 0
                   if ![ic_undo_suspended] {
                      ic_save_model_for_undo
                      ic_undo_suspend
                      set resume 1
                    }
                    
                    busy 1
                    
                     # For explicit coordinates: redo curve
 
                     set va_set(global_coords) $pickList
                     aie_mp12_create_temporary_curve
                     
                     if {[ic_geo_check_objects_exist curve mp12_tmp_crv] != "mp12_tmp_crv"} return
                 
                     # set part_name for new surfaces if 1) closed + 2) !inherit
                     set Z_size [aie_mp12_set_lcs restore]
                     #  
                     ic_current_view $va_set(screen_view) 
                     set newsrfs [aie_mp12_seg_surf_by_screen $Z_size]                                       
                     if ![aie_check_inherit_fam] {
                        set nToNewPart [aie_mp12_set_facets_part_in_Z_dir $part_name $newsrfs]
                     } else {
                       set nToNewPart [aie_mp12_set_facets_part_in_Z_dir "" $newsrfs]
                     }
         
                     set nnames "[llength $newsrfs] new surfaces"
                   	
	           aie_mp12_clean
		 
		    ic_set_family_color_for_name $part_name [family_color_for_name $part_name]
		    aie_create_initial_assemblies
		    display_update geo $part_name
		
		busy 0
                   if $resume ic_undo_resume
	        }
	        3 {
		    aie_cut_stl $part_name
		    ic_set_family_color_for_name $part_name [family_color_for_name $part_name]
		    aie_create_initial_assemblies
		    display_update geo $part_name
	        }
	        4 {
	          #MP12 function
	          # For explicit coordinates: redo curve
                     set va_set(global_coords) $repairPickList
                     ic_delete_geometry curve names mp12_tmp_crv 0
                     aie_mp12_create_temporary_curve
                     
                   set resume 0
                   if ![ic_undo_suspended] {
                      ic_save_model_for_undo
                      ic_undo_suspend
                      set resume 1
                    } 
                    busy 1
                    
	        set va_set(names_for_coords)
	        set res [aie_mp12_repaire_seg_surf $part_name $name $FacCleMP_04_KeepFlag]
	         
	        # if {$res == "No trim"} {status_message "No trim"; return}
	        aie_mp12_clean
	         busy 0
                   if $resume ic_undo_resume	        	        
	        }	              
	        5 {
	        #MP12 function
	         mess "DB Under Construction\n" red		        
	        }	        	        
	        499 {# it seems next function still under construction-(
		    aie_create_character_curve $ref_curve $ref_surf $part_name $n_slice $width 
		    set ref_curve ""
		    set ref_surf ""
		    global va_set
		    foreach i [list curve_name surf_name n_slice width fillet] {
		        set va_set($i) ""
		    }
		    aie_create_initial_assemblies
		    display_update geo $part_name
	        }
	    }
            ic_reset_geo_selected
        }
    }
    # Force Visible
    if {$nnames != "" && (([info exists fam_visible($fam)] && !$fam_visible($fam)) || !$geom_visible(curve))} {
	    ic_show_geo_selected curve $nnames 1 white 1
	    mess "Part is not visible\n" red
	    ic_show_geo_selected curve $nnames 0
    }
    aie_updateGeoVis curve 0 1
    aie_update_icons geom
    if [llength $nnames] {status_message "Done:faceted $nnames"}
    aie_create_parts_in_tree_if_needed 
    set name [ic_vset -new_name $name all]	
}

#--------------------------------------------Auto Apply for Faceted creation-------------------------------------
proc onmoveNode_CrvWdgtFinish {} {
    if {[llength $pickMoveNodeLoc] && $auto_pick_mode} {
		createFacetedDEZ apply
		moveNode_CrvWdgt pick
    }
}
proc onmoveNode_SrfWdgtFinish {} {
    if {[llength $pickMoveNodeLoc] && $auto_pick_mode} {
		createFacetedDEZ apply
		moveNode_SrfWdgt pick
    }
}
proc onmodFaceCrv_00Load {} {
	if $auto_pick_mode {modFaceCrvPick_00 pick}
	
}

proc onmodFaceCrvPick_00Finish {} {
	 if {($Nurb2FacetList != "") &&  $auto_pick_mode} {
		 createFacetedDEZ apply
		 modFaceCrvPick_00 pick

	 } 
}

#---------
proc onmodFaceCrv_01Load {} {
	if $auto_pick_mode {modFaceCrvPick_P0 pick}
}
#---------
proc onmodFaceCrv_02Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}

#---------
proc onmodFaceCrv_03Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}

#---------
proc onmodFaceCrv_04Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}

#---------
proc onmodFaceCrv_05Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}

#---------
proc onmodFaceCrv_06Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}


#---------
proc onmodFaceCrv_07Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}

#---------
proc onmodFaceCrv_08Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}


#---------
proc onmodFaceCrv_09Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}

#---------
proc onmodFaceCrv_10Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}


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

proc onmodFaceSrf_00Load {} {
	if $auto_pick_mode {modFaceSrfPick_S0 pick}

}

proc onmodFaceSrfPick_S0Finish {} {
	 if {($Nurb2FacetList != "") &&  $auto_pick_mode} {
		 createFacetedDEZ apply
		 modFaceSrfPick_S0 pick

	 } 
}
#---------
proc onmodFaceSrf_01Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}

#---------
proc onmodFaceSrf_02Load {} {
  # There is no picker for edges (option 0). Select on Load.
	 if !$modifyFacetSrfEGMVal {
		createFacetedDEZ apply
        return
    }
	if $auto_pick_mode { 	  
	    switch $modifyFacetSrfEGMVal {
	        0 {createFacetedDEZ apply}
	        1 {modFaceSrfPick_P0 pick}
	        2 {modFaceSrfPick_P2 pick}
	    }
	}
}
#-------------------
proc onmodFaceSrfPick_P0Finish {} {
	 if {($FacePtsList != "") &&  $auto_pick_mode} {
		 createFacetedDEZ apply
		 modFaceSrfPick_P0 pick

	 } 
}
#---------
#-------------------
proc onmodFaceSrfPick_P2Finish {} {
	 if {($FacePtsList != "") &&  $auto_pick_mode} {
		 createFacetedDEZ apply
		 modFaceSrfPick_P2 pick
	 } 
}
#---------
proc onmodFaceSrf_03Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_04Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_05Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_06Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_07Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}

}
#---------
proc onmodFaceSrf_08Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_09Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_10Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_11Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_12Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_13Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_14Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodFaceSrf_15Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
	
}
#---------
proc onmodfacCln_00Load {} {
#This used to be only 1 option, now it is 3.
# 
	if !$auto_pick_mode return
	switch $modifyFacetCleanAMVal {
		0 {aie_smooth_facet_edge_align_to_curve edge}
		1 {aie_smooth_facet_edge_align_to_curve node}
		2 {aie_smooth_facet_edges $smooth_tol}				
	}
}
#---------
proc onmodfacCln_01Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}
#---------
#
#MP12--- concept  
#
proc onmodfacCln_02Load {} {
           aie_mp12_clean
	if $auto_pick_mode {
	 FacCleTrimScrPick pick
	}
}
proc onmodfacMP_04Load {} {
           aie_mp12_clean
           set ::va_set(create_closed_curveFlag) 1
	if $auto_pick_mode {
	 FacCleRepPick pick
	}
}
proc onmodfacMP_05Load {} {
           aie_mp12_clean
           set ::va_set(create_closed_curveFlag) 0
	if $auto_pick_mode {
	 FacChCrv1Pick pick
	}
}
proc onFacCleTrimScrPickPick {} {
    global va_set coords vid_options geom_visible 
    # set LCS screen and keep it until Apply completed: ? Or let user change view?
    # currently set on Aplly if not defined
    # User not suppose to use Screen LCS for GUI settings: use global !!! 
    aie_mp12_clean
    set geom_visible(curve) 1
    update_geom_visible curve v 
    # set screen LCS for picking; Curve will be created with global LCS
    # keep initial screen LCS, ignore rotations during pick!!!
    aie_mp12_set_lcs reset
    set ::va_set(fam) $part_name
    set ::va_set(do_when_create_xyz) 1
    set ::va_set(unset_list) do_when_create_xyz
    set ::va_set(do_when_create_xyz_start) ""	
    set ::va_set(do_when_create_xyz_continue) ""		
    set ::va_set(do_when_create_xyz_end) {
        {ic_csystem_set global}
        aie_mp12_create_temporary_curve
        {aie_mp12_set_lcs restore}
    }
    set ::va_set(do_when_create_xyz_cancel) aie_mp12_clean   
}
proc onFacCleTrimScrPickFinish {} {
     global va_set
    ic_csystem_set_current global
    # do not delete mp12 lcs now: user may change view, but apply lcs for "pick" time
    createFacetedDEZ set pickList [set ::va_set(global_coords)]
}
proc onmodfacCln_02UnLoad {} {
    aie_mp12_clean 
}


proc onFacCleRepPickPick {} {
   aie_mp12_set_tag_on_faceted surface.locations
#  tag "surface.locations" set selection available only for first selected surface
#  option "tag.surface.locations" must be set for picker FacCleRepPick in ttkrf file
#  (POINTORXYZ can use any tag with picker option "tag.$tagname")
    aie_mp12_clean
    set geom_visible(curve) 1
    update_geom_visible curve v
    set ::va_set(do_when_create_xyz) 1
    set ::va_set(unset_list) do_when_create_xyz
    set ::va_set(do_when_create_xyz_start) ""	
    set ::va_set(do_when_create_xyz_continue) ""		
    set ::va_set(do_when_create_xyz_end) {
        aie_mp12_create_temporary_curve
    }
    set ::va_set(do_when_create_xyz_cancel) aie_mp12_clean   
}
proc onFacCleRepPickFinish {} {
    createFacetedDEZ set pickList [set ::va_set(global_coords)]
}
proc onFacChCrv1PickPick {} {
   aie_mp12_set_tag_on_faceted surface.locations
#  tag "surface.locations" set selection available only for first selected surface
#  option "tag.surface.locations" must be set for picker FacCleRepPick in ttkrf file
#  (POINTORXYZ can use any tag with picker option "tag.$tagname")
    aie_mp12_clean
    set geom_visible(curve) 1
    update_geom_visible curve v 
    set ::va_set(do_when_create_xyz) 1
    set ::va_set(unset_list) do_when_create_xyz
    set ::va_set(do_when_create_xyz_start) ""	
    set ::va_set(do_when_create_xyz_continue) ""		
    set ::va_set(do_when_create_xyz_end) {
        aie_mp12_create_temporary_curve
    }
    set ::va_set(do_when_create_xyz_cancel) aie_mp12_clean   
}
proc onFacChCrv1PickFinish {} {
    createFacetedDEZ set pickChCrv1 [set ::va_set(global_coords)]
   if $auto_pick_mode {
	 FacChCrv2Pick pick
   } 
}
proc onFacChCrv2PickPick {} {
   aie_mp12_set_tag_on_faceted surface.locations
#  tag "surface.locations" set selection available only for first selected surface
#  option "tag.surface.locations" must be set for picker FacCleRepPick in ttkrf file
#  (POINTORXYZ can use any tag with picker option "tag.$tagname")
    set geom_visible(curve) 1
    update_geom_visible curve v 
    set ::va_set(do_when_create_xyz) 1
    set ::va_set(unset_list) do_when_create_xyz
    set ::va_set(do_when_create_xyz_start) ""	
    set ::va_set(do_when_create_xyz_continue) ""		
    set ::va_set(do_when_create_xyz_end) {
        aie_mp12_create_2_temporary_curves
    }
    set ::va_set(do_when_create_xyz_cancel) aie_mp12_clean   
}


#MP12--- end
#---------
proc onmodfacCln_03Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}
#----
#---------

proc onmodfacMP_06Load {} {
	if $auto_pick_mode {createFacetedDEZ apply}
}




proc onmodfacCln_04Unload {} {
    global va_set
    foreach i [list curve_name surf_name n_slice width fillet] {
	set va_set($i) ""
    }
    ic_delete_geometry all families MPCHAR 1 1
    ic_delete_geometry all families MPTPTS 1 1
    ic_delete_geometry all families MPGUIDE 1 1
}
#----
proc onmodFaceClnUnload {} {
     aie_mp12_clean
}

#----
proc oncreateFacetedDEZCancel {} {
   aie_mp12_clean
}

#--------------------------------------------End Auto Apply for Faceted creation-------------------------------------


#_______________________________________________________________________
#-----------------------------------------------------------------------

proc onRepairGeomDEZOK {} {
    global aie_ShowCurveAttachment aie_CurveColorByCount aie_ShowWide
    global fam_visible vid_options aie_ShowDormant last_repair_geom_option

    if {![aie_check_inherit_fam] && [ic_hex_subset_named_selection $::geo_part_name]} {
        mess "Error: a named selection subset with name \"$::geo_part_name\" already exists; use some other part name\n" red
        return
    }

    set part_name [aie_geo_set_part_name $::geo_part_name]
    # put new points and curves in "Repair Geometry -> Part" (if Not "inherit")
    set part_points $part_name
    set part_curves $part_name
    if ![info exists repairSurfaceEGVal] return
    
    switch -- $repairSurfaceEGVal {
        0 {
            # BUILD TOPOLOGY
            aie_default_topo_tolerance set_user_mode_if_modified $topotol_on_load
            if ![va_is_int_or_real $topoang ] {
                ic_mess "Error: define angle\n" red
                return
            }
            # Build Topology goes here
            set args "$::geo_cad(toler) -angle $topoang"
            if $FilterPntsFlag  { append args " -filter_points" }
            if $FilterCrvsFlag { append args " -filter_curves" }
            if $InteriorCrvsFlag {append args " -create_interior" }
            if !$RegSurfFlag  { append args " -no_reg_surf" }
            if !$JoinEdgesFlag { append args " -no_concat" }
            if $KeepDrmDrmFlag { append args " -keep_dormant_dormant" }
            if $UseLocalTolFlag { append args " -do_v_merge_for_crv" }
                             
            if ![aie_check_inherit_fam] {
                # temporary family name
                append args " -new_family TMP_TOPO_PART_NAME"
            }
#           if $single_curves  {
#               append args " -only_singles"
#           }
            switch $build_topo_what {
                0 - 1 {
                    set ActFamFlag $build_topo_what
                    set fams ""
                    set parts [ic_geo_list_families]
                    foreach i [array names fam_visible] {
                        if {!($ActFamFlag) || ( $ActFamFlag && $fam_visible($i))} {
                            if {[lsearch $parts $i] != -1} {
#                               if {$PerFamFlag != 1} {append args " $i"}
                                append fams " $i"
                            }
                        }
                    }
                    if {$PerFamFlag == 1} {
                        append args " -part_by_part $fams"
                    } else {
                        set args [concat $args $fams]
                    }
                }
                2 {
                    set fams [array names fam_visible]
                    set surfs ""
                    set curves ""
                    set points ""
                    if [info exists LongList] {
                        set thelist $LongList
                    } else {
                        set thelist $entityList
                    }
                    foreach {u v} $thelist {
                        switch $u {
                            surface { lappend surfs $v }
                            curve { lappend curves $v }
                            point { lappend points $v }
                            default {}
                        }
                    }
                    # if nothing selected ->do not execute build_topo
                    set sel 0
                    if {$surfs != ""} {append args " -surfaces $surfs"; incr sel}
                    if {$curves != ""} {append args " -curves $curves"; incr sel}
                    if {$points != ""} {append args " -points $points"; incr sel}
                    if !$sel {
                        status_message "No selection" red
                        return
                    }
                }
            }
            if {$build_topo_what != 2} {
                # delete unattached dormant curves and points
                ic_geo_delete_unattached $fams 0 1
            }
            busy 1
        if ![ic_undo_suspended] {
            ic_save_model_for_undo
            ic_undo_suspend
            set resume 1
        } else {
            set resume 0
        }
            #+++++
            
            eval ic_build_topo $args
            if {$BuildtopoOnlySingleVal && ($topotol_single > $::geo_cad(toler))} {
                set args2 [concat $topotol_single -only_singles [lrange $args 1 end]]
                eval ic_build_topo $args2
            }
            if $DelUnattFlag {
                if {$build_topo_what != 2} {
                    ic_geo_delete_unattached $fams
                } else {
                    # delete unattached only from selection
                    foreach v $curves {
                        if {[ic_geo_incident curve $v] != ""} continue
                        ic_delete_geometry curve names $v 0
                    }
                    foreach v $points {
                        if {[ic_geo_incident point $v] != ""} continue
                        ic_delete_geometry point names $v 0
                    }
                }
            }
            set entityList ""
            mess "Build topology completed.\n" blue
            # Move curves and points to the given PARTS
            # Nastran doesn't like PART have more than one element type
            # This is not very efficient - Ganesan
            if ![aie_check_inherit_fam] {
                mess "Moving Points and Curves to given parts....\n" blue
                set crvs [ic_geo_get_objects curve TMP_TOPO_PART_NAME]
                if {$crvs != ""} {
                    set part [aie_new_part $part_curves]
                    ic_geo_set_part curve $crvs $part 0
                }
                set pnts [ic_geo_get_objects point TMP_TOPO_PART_NAME]  
                if {$pnts != ""} {
                    set part [aie_new_part $part_points]
                    ic_geo_set_part point $pnts $part 0
                }
                status_message "Done topology" blue
            }
            busy 0
            if $resume ic_undo_resume
        }
	1 {
	    # Check Geometry
	    # This function select subset of curve/surfaces based in requested criteria
	    # User can highlight, set part, or set subset from that subset
	    # User must use other DEZ in order to delete/merge/reaprroximate/etc.
	    # No modifications here!
            set list ""
            set surface ""
	    switch $which_parts {
		0 { set surface [ic_geo_get_objects surface ""] }
		1 {
		    set fams ""
		    foreach i [array names fam_visible] {
                        if {$i == "ORFN"} continue
			if $fam_visible($i) { 
			    lappend fams $i
			}
		    }
                    if {$fams != ""} {
		        set surface [ic_geo_get_objects surface $fams]
                    }
		}
		2 {
                    if {$partList != ""} {
                        set surface [ic_geo_get_objects surface $partList]
                    }
                }
		3 { set surface $surfList }
	    }
            # Note: for curves: single OR multiple; for surfaces area AND curvature
	    switch $checkSurfVal {
	        0 {	
		    set result_type curve		
		    set sc ""
		    set mc ""
		    set curves [lsort -unique [ic_geo_get_attached_entities boundary surface $surface]]
		    if {$single_curve_check && $curves != ""}  {
		        set sc [ic_geo_get_entities_by_attach_num curve 1 $curves]
		    }
		    if {$multiple_curve_check && $curves != ""} {
		        set mc [ic_geo_get_entities_by_attach_num curve multiple $curves]
		    }
		    set list [concat $sc $mc]
	        }
	        1 {
		    set result_type surface
		    set list ""
		    set areaSelected ""
		    # reduce time checking mesh surfaces angle and normal once:
		    if [info exists tmp_crvt] {unset tmp_crvt}
		    if [info exists tmp_ang] {unset tmp_ang}
		    if {$checkGeoProblemsLargeCVal || $checkNormalSVal} {
			foreach srf $surface {
			    set type [ic_geo_get_object_type surface $srf]
			    if {$type != "mesh"} continue
			    set ang_norm [ic_geo_mesh_srf_angle $srf]
			    set tmp_crvt($srf) [lindex $ang_norm 0]
			    set tmp_norm($srf) [lindex $ang_norm 1]
			}
		    }						
		    if $checkGeoProblemsLargeCVal {
			foreach srf $surface {
			    if [info exists tmp_crvt($srf)] {
				set crvt $tmp_crvt($srf)
			    } else {
				set crvt [ic_surface_curvature $srf]
			    }
			    if $curvature_how {
				if {$crvt > $ref_angle} continue
			    } else {
				if {$crvt <= $ref_angle} continue
			    }
			    lappend list $srf
			}
			set surface $list
		    }
		    if $checkGeoProblemsSmallSVal {
			set list ""
			foreach srf $surface {			
			    set area [ic_geo_srf_area $srf]
			    if $area_how {
				if {$area > $ref_area} continue
			    } else {
				if {$area <= $ref_area} continue
			    }
			    lappend list $srf				 
			}
			set surface $list
		    }
		    if $checkNormalSVal {
			set list ""
			foreach srf $surface {
			    if [info exists tmp_norm($srf)] {
				set norm $tmp_norm($srf)
			    } else {
				set p0 [lindex [ic_geo_get_srf_pos 0.5 0.5 $srf] 0]
				set p1 [lindex [ic_geo_get_srf_pos 0.4 0.5 $srf] 0]
				set p2 [lindex [ic_geo_get_srf_pos 0.5 0.4 $srf] 0]	
				set norm [ic_vcalc product $p0 $p1 $p2]
			    }
			    set ref_dir [lindex "{1 0 0} {0 1 0} {0 0 1}" $normal_how]
			    set angle_to [ic_vcalc angle $norm $ref_dir]
			    if {$angle_to > 90} {set angle_to [expr 180-$angle_to]}
			    if {[expr abs($angle_to)] > $normal_srf_tol} continue
			    lappend list $srf				 
			}
		    }	
	        }
	    }
	    set nsel [llength $list]
	    ic_mess "Done: $nsel ${result_type}s\n"
	    if !$nsel return
	    switch $checkPlacementEGVal {
		0 {
		    aie_geom_placement $result_type $list highlight color white width 5
		}
		1 { 
		    if {$check_in_part == ""} {set check_in_part PART_00}
		    aie_geom_placement $result_type $list part $check_in_part
		}
		2 {
		    if {$check_in_subset == ""} {set check_in_subset subset_00}
		    aie_geom_placement $result_type $list subset $check_in_subset clear
		}
	    }
	    return
	}
	2 {
            # Close holes routine. This will take care of faceted and paramertic data separately
            # toler_max .1 yellow 1
            
            # Here close holes in CAD data
            if {$curveCloseSurfCADList == ""} {
                mess "No curves selected.\n" red
                return
            }
            mess "\nTopology tolerance used: $::geo_cad(toler)\n"
            if {$repairSurfCloseMultiFlag == 1} {set doval 4} else {set doval 3}
            if {$repairSurfCloseQuietFlag == 1} {set quiet 1} else {set quiet 0}
            busy 1
            set curtype [ic_geo_get_object_type curve $curveCloseSurfCADList]
            switch -- $curtype {
                mesh {
                    if {$repairSurfCloseMultiFlag == 0} {
                        set complete_edges 1
                    } else {
                        set complete_edges 0
                    }
                    set got_surfs ""
                    set all_surfs ""
                    array set segs_surf ""
                    foreach cc $curveCloseSurfCADList {
                        if {[ic_geo_get_object_type curve $cc] == "param"} { continue }
                        set isurfs [ic_geo_incident curve $cc]
                        foreach surf $isurfs {
                            set edges [ic_geo_surface_edges_incident_to_curve $surf $cc]
                            if {$edges != ""} {
                                lappend segs_surf($surf) $edges
                                lappend got_surfs $surf
                                if {[lsearch $all_surfs $surf] == -1} {
                                    lappend all_surfs $surf
                                }
                                break
                           }
                        }
                    }
                    set segs ""
                    foreach surf $got_surfs {
                        if [info exists segs_surf($surf)] {
                            lappend segs [list $surf $segs_surf($surf)]
                            unset segs_surf($surf)
                        }
                    }
                    if {$segs != ""} {
                        set curves ""
                        foreach surf $all_surfs {
                            set cc [ic_geo_boundary surface $surf]
                            if {$cc != ""} {
                                append curves " $cc"
                            }
                        }
                        if ![aie_check_inherit_fam] {
                            set points ""
                            foreach cc $curveCloseSurfCADList {
                                set pp [ic_geo_boundary curve $cc]
                                if {$pp != ""} {
                                    foreach p $pp { if {[lsearch $points $p] == -1} { append points "$p " } }
                                }
                            }
                        }
                        repairGeomDEZ setclean
                        set ok [ic_geo_stlrepair_holes surface $segs 0 0 $complete_edges $curveCloseSurfCADList $::geo_cad(toler)]
                        repairGeomDEZ setdirty
                        if {$all_surfs != "" && $ok} {

                            if ![aie_check_inherit_fam] { set fam [ic_geo_get_part surface [lindex $all_surfs 0]] }
                            
                            ic_geo_build_topo_on_srfs $all_surfs "$curves" $::geo_cad(toler) 0 0 1
                            
                            if {![aie_check_inherit_fam] && $points != ""} {
                                set len [llength $all_surfs]
                                set part_surface [aie_new_part $part_surface]
                                set surfaces [ic_geo_lookup surface families $fam]
                                set possible_srf ""
                                foreach srf $surfaces { append possible_srf "[lindex $srf 1] " }
                                if {$len == 1} {
                                    foreach srf $possible_srf {
                                        if ![info exists num] {
                                            set num [llength [ic_geo_boundary surface $srf]]
                                            set skip_srf $srf
                                        } elseif {[llength [ic_geo_boundary surface $srf]] > $num} {
                                            set num [llength [ic_geo_boundary surface $srf]]
                                            set skip_srf $srf
                                        }
                                    }
                                    unset num
                                }
                                foreach srf $possible_srf {
                                    if {[info exist skip_srf] && $srf == $skip_srf} continue
                                    set new_fam 0; set srf_points ""
                                    set cc [ic_geo_boundary surface $srf]
                                    foreach c $cc {
                                        set pp [ic_geo_boundary curve $c]
                                        if {$pp != ""} {
                                            foreach p $pp {
                                                if {[lsearch $srf_points $p] == -1} { append srf_points "$p " }
                                            }
                                        }
                                    }
                                    foreach p $points {
                                        if {[lsearch $srf_points $p] == -1} {
                                            set new_fam 1
                                            break
                                        }
                                    }
                                    if !$new_fam { ic_geo_set_part surface $srf $part_surface 0 }
                                }
                            }
                            
                        } elseif {!$ok && !$complete_edges} {
                            mess "Maybe \"Multiple holes\" must be off.\n" red
                        }
                    } else {
                        if [aie_check_inherit_fam] {
                            set use_part "-inherited"
                        } else {
                            set use_part "$part_surface"
                        }
                        repairGeomDEZ setclean
                        ic_geo_gap_repair toler $::geo_cad(toler) new_family $use_part curves $curveCloseSurfCADList do $doval partial 0 yellow 1 quiet $quiet
                        repairGeomDEZ setdirty
                    }
                }
                default {
                    if {$curveCloseSurfCADList != ""} {
                        if [aie_check_inherit_fam] {
                            set use_part "-inherited"
                        } else {
                            set use_part "$part_name"
                        }
                        set last_repair_geom_option 2
                        repairGeomDEZ setclean
                        ic_geo_gap_repair toler $::geo_cad(toler) new_family $use_part curves $curveCloseSurfCADList do $doval partial 0 yellow 1 quiet $quiet
                        repairGeomDEZ setdirty
                    }
                }
            }
             # 51733: Update surfaces visibility mode (new surfaces are wireframe)
            aie_changeSurfStyle
	    after 100 "update_geom_visible surface p 1"
	    ic_reset_geo_selected
            # end of 51733       
            ic_geo_reset_data_structures
            set curveCloseSurfCADList ""
            busy 0
            aie_create_parts_in_tree_if_needed
	}
	3 {
	    if ![llength $curveRemoveList] return
	    set newlist ""
	    foreach crv $curveRemoveList {
	        if {[ic_geo_check_objects_exist curve $crv] == ""} continue
	        lappend newlist $crv
	    }
	    if [llength $crv] {
	        ic_geo_remove_feature $curveRemoveList
	    }
	    set curveRemoveList ""
	}

        4 {
            #_______________Repair Gaps
            if {![va_is_int_or_real $maxGapdist ]} {
                ic_mess "Error: define Max Gap Distance\n" red
                return
            }
            #Note: $do=1 close gaps; $do=2 match surfaces; $do 3 close 1 hole; $do=4 close multiple holes

            switch -- $repairSurStichMethodVal {
                0 {set GRhow "User select" }
                1 {set GRhow "Match" }
                2 {set GRhow "Retrim" }
                3 {set GRhow "Fill" }
                4 {set GRhow "Blend" }
            }
            set use_part "-inherited"
            if ![aie_check_inherit_fam] {
                set use_part [aie_new_part $part_surface]
            }
            switch -- $GRhow {
                "User select" {
                    set curtype [ic_geo_get_object_type curve $curveCloseGapCADList]
                    switch -- $curtype {
                        param {
                            set last_repair_geom_option 4
                            repairGeomDEZ setclean
                            ic_geo_gap_repair toler $::geo_cad(toler) toler_max $maxGapdist \
                                new_family $use_part curves $curveCloseGapCADList \
                                do 1 partial $repairGapPartialFlag \
                                yellow $repairGapYellowFlag
                            repairGeomDEZ setdirty
                        }
                        mixed {
                            if {$curveCloseGapCADList != ""} {
                                mess "You have mixed Bspline and Faceted Curves.\n"
                                mess "Please convert all curves to faceted or Bspline to use this option\n"
                                set curveCloseGapCADList ""
                            }
                        }
                        mesh {
                            set got_surfs ""
                            array set segs_surf ""
                            foreach cc $curveCloseGapCADList {
                                if {[ic_geo_get_object_type curve $cc] == "param"} { continue; }
                                set isurfs [ic_geo_incident curve $cc]
                                foreach surf $isurfs {
                                    set edges [ic_geo_surface_edges_incident_to_curve $surf $cc]
                                    lappend segs_surf($surf) $edges
                                    lappend got_surfs $surf
                                }
                            }
                            set segs ""
                            foreach surf $got_surfs {
                                if [info exists segs_surf($surf)] {
                                    lappend segs [list $surf $segs_surf($surf)]
                                    unset segs_surf($surf)
                                }
                            }
                            ic_geo_stlrepair_edges surface $segs $::geo_cad(toler) -1
                        }
                    }
                }
                Match {
                    if {[llength $curveCloseGapCADList] < 2} {
                        mess "Please select at least two curves.\n" red
                    } else {
                        ic_geo_gap_repair toler $::geo_cad(toler) toler_max 0.0 new_family \
                            $use_part curves $curveCloseGapCADList do 2 partial \
                            $repairGapPartialFlag
                    }
                }
                Retrim {
                    set n_curves [llength $curveCloseGapCADList]
                    if {$n_curves != 2 && $n_curves != 3} {
                        mess "Please select two or three curves.\n" red
                    } else {
                        set action 1
                        if {$n_curves == 3} {
                            mess "Close Y-junction.\n"
                            set action 4
                        }
                        ic_geo_gap_repair toler $::geo_cad(toler) toler_max 0.0 new_family \
                            $use_part curves $curveCloseGapCADList do 1 partial 0 \
                            quiet $action
                    }
                }
                Fill {
                    if {[llength $curveCloseGapCADList] != 2} {
                        mess "Please select two curves.\n" red
                    } else {
                        ic_geo_gap_repair toler $::geo_cad(toler) toler_max 0.0 new_family \
                            $use_part curves $curveCloseGapCADList do 1 partial \
                            $repairGapPartialFlag quiet 2
                    }
                }
                Blend {
                    if {[llength $curveCloseGapCADList] != 2} {
                        mess "Please select two curves.\n" red
                    } else {
                        ic_geo_gap_repair toler $::geo_cad(toler) toler_max 0.0 new_family \
                        $use_part curves $curveCloseGapCADList do 1 partial \
                        $repairGapPartialFlag quiet 3
                    }
                }
            }
            ic_geo_reset_data_structures
            set curveCloseGapCADList ""
        }

	5 {
	    # split folded surface
	    if ![va_is_int_or_real $MaxCurvAng ] {
		ic_mess "Error: define Max Angle\n" red 
		return
	    }
	    if {$MaxCurvAng == 0} {
	        mess "Error: Angle is zero!\n" red
	        return
	    }
	    if {$FoldedSurf ==""} {
	        mess "Error: Folded surface not specified!\n" red
	        return
	    }
	    ic_geo_trm_srfs_by_curvature $FoldedSurf $MaxCurvAng
	}

        6 {
            switch -- $createThicknessAdjMethodVal {
                0 {
                    set debug 0;
                    if {$debug} {
                        mess "Debug level = $debug\n" red
                    }
                    if [catch {ic_geo_calculate_thickness $midsurfaces $solidsurfaces $thick_order \
                        $max_thickness $debug} res] {
			ic_mess "Error: $res\n" red
		    } else {
			ic_mess "Done\n"
		    }
#    set midsurfaces ""
#    set solidsurfaces ""
                }
                1 {
                    switch -- $createThickAdjOrderVal {
                        0 {
                            set b1 [list $C1 $C2 $C3 $C4]
                            foreach i $b1 {
                                if {$i < 0} {
                                    ic_mess "Please enter non-negative value for thickness\n" red
                                    return
                                }
                            }
                            ic_geo_surface_thickness $surfaces 2 $b1
                        }
                        1 {
                            set b2 [list $C1 $M12 $C2 $M13 $M $M24 $C3 $M34 $C4]
                            foreach i $b2 {
                                if {$i < 0} {
                                    ic_mess "Please enter non-negative value for thickness\n" red
                                    return
                                }
                            }
                            ic_geo_surface_thickness $surfaces 3 $b2
                        }
                        2 {
                            set b3 [list $C1 $M1t2 $M1tt2 $C2 \
                                $M1t3 $M1 $M2 $M2t4 $M1tt3 $M3 $M4 $M2tt4\
                                $C3 $M3t4 $M3tt4 $C4]
                            foreach i $b3 {
                                if {$i < 0} {
                                    ic_mess "Please enter non-negative value for thickness\n" red
                                    return
                                }
                            }
                            ic_geo_surface_thickness $surfaces 4 $b3
                        }
                    }
                    foreach surobj $surfaces {
                        set type [ic_geo_get_object_type surface $surobj]
                        if {$type != "param"} {
                            ic_mess "Cannot apply thickness to non-parametric surface $surobj\n" red
                        }
                    }
#                    set surfaces ""
                }
                2 {
                    if {$part_name == ""} { set part_name "ZERO_THICKNESS" }
                    if ![ic_geo_check_part $part_name] {
                        aie_new_part $part_name
                    }
#                     aie_check_inherit_fam part_name surface $surfaces
                     ic_surface_thickness_check $surfaces $part_name
#                    set surfaces ""
                }
            }
        }

	7 {
	    # Reorient Surface Normals        
		if {$createSurfNormalsMethodVal == 0} {
		if ![llength $surfNormalRef] return 
		busy 1
			if $reverseFlag {
				ic_modify reverse surface $surfNormalRef
			}
			ic_geo_surface_normals_orient $surfNormalRef 0
	    # this is what updates the surface normals on the screen --jka
			busy 0
		}
		if {$createSurfNormalsMethodVal == 1} {
			ic_modify reverse surface $surfNormalRefAny 
		}
		set surfNormalRefAny ""
		update idletasks
	    after 100 "update_geom_visible surface p 1"
	    status_message "Done: Normals" 
	    return
	}
	
	8 {
	    # Find/Assign Bolt Holes
		busy 1
	    global vid_options
	    if [aie_check_inherit_fam] {set pn ""} else {set pn $part_name}
	    if $removeHole {
		ic_meshdirect_bolt_holes 0 $smallest_hole 0 $ratio_rings $num_rings "" $bh_curves 
	    }
	    set num [ic_meshdirect_bolt_holes $smallest_hole $largest_hole "" $ratio_rings $num_rings \
		"" $bh_curves $pn $smartsizeFlag]

	    set bh_curves ""
	    aie_create_initial_assemblies
	    if $num {
		mess "$num bolt holes found\n"
		if {$pn == ""} {
		    mess "bolt holes put in subset HOLE\n"
		} else {
		    mess "bolt holes put in part $pn \n"
		}
	    } else {mess "no bolt holes found\n"}
		busy 0
	}
	
	
	9 {
	    # Find/Assign Buttons
		busy 1
		#+++++
	    #
	    #--> find button surfaces.
	    #
	    if {$butt_surfs == ""} {
		set free_surfs [ic_geo_get_objects surface ""]
	    } else {
		set free_surfs $butt_surfs
	    }
	    mess "Finding buttons...\n" 
	    set butt_loops [ic_meshdirect_find_button_features $free_surfs ]
	    set free_surfs [ic_list_remove_from_grouped $butt_loops $free_surfs]
	    set l [llength $butt_loops]
	    if $l {mess "$l buttons found\n\n"}
	    set free_loops ""
	    set split_loops "" 
	    set fillet_loops ""
	    #
	    #-->find free edged buttons
	    #
#	    if {$freeFlag == 1} {
#		mess "Finding free buttons...\n\n" 
#		set free_loops [b scrib_lib_feature_find_single_bounded_buttons $free_surfs]
#		set free_surfs [ic_list_remove_from_grouped $free_loops $free_surfs]
#		set l [llength $free_loops]
#		if $l {mess "$l buttons found\n\n"}
#	    }
	    #
	    #-->find split buttons stuff
	    #
	    if {$splitFlag == 1} {
		mess "Finding split buttons...\n" 
		set split_loops [ic_meshdirect_find_seam_buttons $free_surfs] 
		set free_surfs [ic_list_remove_from_grouped $split_loops $free_surfs]
		set l [llength $split_loops]
		if $l {mess "$l buttons found\n\n"}
	    }
	    #
	    #-->find fillet buttons stuff
	    #
	    if {$filletFlag == 1} {
		mess "Finding fillet buttons...\n"    
		if !$FilletArc_1TolGGVal {
			set fillet_tol 0.001
		}
		set fillet_loops [ic_meshdirect_fillet_find_by_arc $free_surfs 1 20 15 5000 2000 2 $fillet_tol]
		set free_surfs [ic_list_remove_from_grouped $fillet_loops $free_surfs]
		set l [llength $fillet_loops]
		if $l {mess "$l buttons found\n\n"}
	    }
	    #
	    #-->deal with buttons
	    #
	    set button_loops [concat $butt_loops $free_loops $split_loops $fillet_loops]
	    #There can be duplicate loops based off order of surface names
	    set bl ""
	    foreach b $button_loops {
		lappend bl [lsort -unique -increasing $b]
	    }
	    set button_loops [lsort -unique $bl]
	    set l [llength $button_loops]
	    if $l {
		mess "Total number of buttons is $l\n\n" blue
		set i 1
		foreach f $button_loops {
		    #need some way to find if a subset exists
		    set name BUTTON$i
		    set ll ""
		    foreach s $f {set ll [concat $ll surface $s] }
		    ic_geo_subset_add_items $name $ll
		    ::AIEnv::GUIManagement::Tree::AddGroup geom_subset $name 1
		    ::AIEnv::GUIManagement::Tree::ToggleGroupVisibility geom_subset $name same
		    incr i
		    #This should get moved into scrib stuff -->BEN
		    set rem_curves ""
		    foreach s $f {set rem_curves [concat $rem_curves [ic_geo_boundary surface $s]]}
		    set rem_curves [lsort -unique [ic_list_get_duplicated $rem_curves]]
#		    foreach r $rem_curves {
#			ic_geo_set_dormant_entity curve $r 1
#		    }
		    ic_geo_set_dormant_entity curve $rem_curves 1
		}
	    } else { mess "No buttons found\n" }
		busy 0
		#-----
	}
	
	10 {
		busy 1
		#+++++
	    # Find/Assign Fillets   
	    
	    if !$FilletArc_0TolGGVal {
			set fillet_tol 0.001
		}
	    set fillets ""
	    if {$fillet_surfs == ""} {set fillet_surfs [ic_geo_get_objects surface "" ] }
	    foreach s $fillet_surfs { 
	      if {[ic_surface_curvature $s] < $min_curvature} continue      
	      set crvs [ic_geo_boundary surface $s 1 1]
	      set arcs ""
                foreach c $crvs {	
	         set lng [ic_geo_crv_length $c]
	         set rel_tol [expr $fillet_tol * $lng]
	         if ![ic_geo_crv_is_arc $c $rel_tol] continue
	         if {$lng < $min_length || $lng > $max_length} continue
	         lappend arcs $c
	      }
	      if {[llength $arcs] < 2} continue 
	      lappend fillets $s		
              }
	    mess "fillets are $fillets\n"
	    set i 1
	    set ff [ic_geo_make_conn_regions surface $fillets] 
	    foreach f $ff {
		#need some way to find if a subset exists
		set name FILLET$i
		set ll ""
		foreach s $f {set ll [concat $ll surface $s] }
		ic_geo_subset_add_items $name $ll
		::AIEnv::GUIManagement::Tree::AddGroup geom_subset $name 1
		::AIEnv::GUIManagement::Tree::ToggleGroupVisibility geom_subset $name same
		mess "connected fillet region contains surfaces $f\n"
		incr i
	    }
	    if {[llength $ff] == 0} {mess "no fillet regions found\n"}
		busy 0
		#-----
	}
	
    }
    
    #Display curves wide and colour by count only first time!!!
    if ![info exists FirstTimeRepairApply] {
	set FirstTimeRepairApply 1
	foreach attach { show0 show1 show2 show3 } {
	    set aie_ShowCurveAttachment($attach) 1
	    ::AIEnv::GUIManagement::Tree::ShowCurveAttachment $attach
	}
	
	if ![ic_hex_blocking_loaded] {
	    set aie_CurveColorByCount 1
	    ::AIEnv::GUIManagement::Tree::CurveColorByCount
	    set aie_ShowWide(curve) 1
	    ::AIEnv::GUIManagement::Tree::ShowWide curve
	}
    }

    set aie_geoTypeVis(curve) 2
    aie_updateGeoVis
    aie_create_parts_in_tree_if_needed 
    aie_update_parts_in_tree_if_needed
    foreach t {point curve} {
        if {[info exists aie_ShowDormant($t)] && $aie_ShowDormant($t)} {
            ::AIEnv::GUIManagement::Tree::ShowDormant $t
        }
    }
    #aie_update_parts_vis
    #commented above, because it was causing problems when running build topo on active parts.
}
#-------------------------------------------------------------------------------------------------------------------------
# Purpose of this proc was to set geo_cad(toler) from SurfaceDEZ and return the toler.
# Now all Geometry DEZs (Surf, Curve, Repaire...) directly use geo_cad(toler) 
# Still this proc used in aie_hexa.tcl aie_mesher.tcl aie_translators.tcl aie_wb.tcl
# Some usage is wierd, e.g. "set geo_cad(toler) [aie_default_topo_tolerance]"
# Fix usage ... and may be delete this proc.
# Note: probably usage is confusing with function ic_geo_default_topo_tolerance,
# which does use bbox.  

proc onRepairGeomDEZLoad {} {
    global toptol_userset env geo_cad

    if {[info exists geo_cad(toptol_userset)] && $geo_cad(toptol_userset) == "1"} {
        set topotol_on_load [aie_default_topo_tolerance set_user_mode_if_modified]
        mess "Using user defined topo tolerance\n"
    } else {
        set topotol_on_load [aie_default_topo_tolerance]
        mess "Using default topo tolerance\n"
    }
    
    if [info exists LongList] { unset LongList }
    
    if { ! [ info exists RepairGeomInit ] } {
	    set RepairGeomInit 1  
	    set name new_name
	    set MaxCurvEGVal 0	
	    set topoang 30
	    set FilterPntsFlag 0
	    set FilterCrvsFlag 0
	    set RegSurfFlag 1
	    set JoinEdgesFlag 0
	    set ActFamFlag 0
	    set DelUnattFlag 1
	    set MaxCurvAng 90
	    set maxGapdist 0.1
	    set repairGapYellowFlag 1
	    set thick_order 4
	    set normal_srf_tol 0.1
	    set topotol_single [expr $topotol_on_load * 2.0] 
	    set KeepDrmDrmFlag 0
	    set build_topo_what 0
	    set fillet_tol 0.001
	    set smartsizeFlag 0
	    set ratio_rings 1
	    set num_rings 2
    }
    if {$topotol_single == ""} {
	    catch {set topotol_single [expr $::geo_cad(toler)*2.0]}
    } 
    repairGeomDEZ setdirty
    set PartList [aie_list_parts 1]
    set surfNormalRef ""
    set surfaces ""
    #Gap Repair Opts
    set GapRepairOpts [list "User select" Match Retrim Fill Blend ]
    if ![info exists GRhow] {set GRhow "User select"}
    if {$GRhow == ""} {set GRhow "User select"}
    if ![info exists env(AI_ENV_LSTC)] {    
    #Feature recognition stuff
	if {$smallest_hole == ""} {set smallest_hole 0}
	if {$largest_hole == ""} {set largest_hole [expr $topotol_on_load * 20] }
    #    if {$groupResultName == ""} {set groupResultName SPIDER}
    #    if {$max_width == ""} {set max_width 30}
    #    if {$min_width == ""} {set min_width 5}
    #    if {$max_curvature == ""} {set max_curvature 80}
    	if {$min_curvature == ""} {set min_curvature 15}
    #    if {$max_angle == ""} {set max_angle 20}
    #    if {$min_angle == ""} {set min_angle 0}
    	if {$min_length == ""} {set min_length 0}
    	if {$max_length == ""} {set max_length 20}
    #    if {$freeFlag == ""} {set freeFlag 1}
	if {$filletFlag == ""} {set filletFlag 1}
	if {$splitFlag == ""} {set splitFlag 1}
    }
    if {$InteriorCrvsFlag == ""} {set InteriorCrvsFlag 1}
    if {$ref_angle == ""} {
	set ref_angle 180
	set single_curve_check 1
	set multiple_curve_check 1
	set ref_area 1
	set checkPlacementEGVal 1
	set checkGeoProblemsLargeCVal 1
	set checkGeoProblemsSmallSVal 0
	::AIEnv::GUIManagement::ToggleGrey checkGeoProblemsLargeC
    }
    set part_name [aie_geo_set_part_name]
    # Requested the same part for topo points, curves, surface.
    # Temporary keep current variables:
    set part_points $part_name
    set part_curves $part_name
    set part_surface $part_name
    
    set PartList [aie_list_parts 1]
    set entityList ""
    foreach flag {FilterPntsFlag FilterCrvsFlag} {
        if {[trace vinfo $flag] != ""} {
            trace vdelete $flag w aie_geo_repair_trace_filterflag
        }
        trace variable $flag w aie_geo_repair_trace_filterflag
    }
    aie_geo_repair_trace_filterflag "" "" ""
    ::AIEnv::GUIManagement::ToggleGrey repairGeomFam [aie_check_inherit_fam]
}

proc onRepairGeomDEZUnLoad {} {
    global present_geo_selection last_repair_geom_option
    foreach flag {FilterPntsFlag FilterCrvsFlag} {
        if {[trace vinfo $flag] != ""} {
            trace vdelete $flag w aie_geo_repair_trace_filterflag
        }
    }
    banner ""
    if [info exists last_repair_geom_option] {
        switch -- $last_repair_geom_option {
            2 { set present_geo_selection 1 }
            4 { set present_geo_selection 0 }
        }
        unset last_repair_geom_option
    }
    if [info exists LongList] { unset LongList }
}

proc aie_geo_repair_trace_filterflag {name element op} {
    set pFlag [repairGeomDEZ get FilterPntsFlag]
    set cFlag [repairGeomDEZ get FilterCrvsFlag]
    if {!$pFlag && !$cFlag} {
        ::AIEnv::GUIManagement::ToggleGrey createBuilTopoAng 1
    } else {
        ::AIEnv::GUIManagement::ToggleGrey createBuilTopoAng 0
    }
}

proc onBuildTopoMPickFinish {} {
    
    if [info exists LongList] {
        set thelist $LongList
    } else {
        set thelist $entityList
    }
    foreach typ {surface curve point} {
        if [info exists tmp_$typ] { unset tmp_$typ }
    }
    foreach "typ nam" $thelist {
        set tmp_${typ}($nam) 1
    }
    foreach srf [array names tmp_surface] {
        foreach crv [ic_geo_boundary surface $srf] {
            set tmp_curve($crv) 1
        }
    }
    foreach crv [array names tmp_curve] {
        foreach pnt [ic_geo_boundary curve $crv] {
            set tmp_point($pnt) 1
        }
    }
    if [info exists LongList] {
        set ents ""
        foreach typ {surface curve point} {
            if ![info exists tmp_$typ] continue
            foreach nam [array names tmp_$typ] {
                lappend ents $typ $nam
            }  
            unset tmp_$typ
        }
        if {[llength $ents] != 0} {
            set nents [expr [llength $ents] / 2]
        } else {
            set nents 0
        }
        set LongList $ents
        set entityList "$nents entities"
    } else {
        set entityList ""
        foreach typ {surface curve point} {
            if ![info exists tmp_$typ] continue
            foreach nam [array names tmp_$typ] {
                lappend entityList $typ $nam
            }  
            unset tmp_$typ
        }
    }
}

proc onrepairGeoTopoLoad {} {
    set PartList [aie_list_parts 1]
# What for next?
if 0 {
    foreach var {FilterPntsFlag FilterCrvsFlag InteriorCrvsFlag RegSurfFlag} {
	if ![info exists $var] {set $var 0}
	trace variable $var w aie_config_repairGeoTopo
    }
    aie_config_repairGeoTopo
}
}
proc aie_config_repairGeoTopo {args} {
    #VG specific configuration only for this function...
    #   variables already defined: this function works inside namespace
    #	uses more generic function: aie_try_change_entry_configure
    set ds ::AIEnv::DEZ::repairGeomDEZ
    set v1 [set ${ds}::FilterPntsFlag]
    set v2 [set ${ds}::FilterCrvsFlag]
    set v3 [set ${ds}::InteriorCrvsFlag]
    set v4 [set ${ds}::RegSurfFlag]
    set chk [expr $v1 + $v2 + $v3 + $v4]
    set chk1 "-state normal -bg white"
    set chk0 "-state disabled -bg gray" 
    aie_try_change_entry_configure  repairGeoTopo topoang $chk $chk0 $chk1  
}
#-----
proc onrepairSurfCloseLoad {} {
    if $auto_pick_mode {repairSurfCADClosePick pick}
}
#-----
proc onrepairSurRemoveLoad {} {
    if $auto_pick_mode {repairSurfacePickRemove pick}
}
#-----
proc onrepairSurMatchLoad {} {
    if $auto_pick_mode {repairSurfGap2Pick pick}
}
#-----
proc onrepairSurfaceSplitFoldedLoad {} {
    if $auto_pick_mode {repairSurfacePickFolded pick}
}
#------------
proc onrepairSurfCADClosePickFinish {} {
    if {($curveCloseSurfCADList != "") && $auto_pick_mode} {
        repairGeomDEZ apply
        if {[aie_active_dez] == "repairGeomDEZ"} {
	        repairSurfCADClosePick pick
        }
    }
}
#-----------------------------------------------
proc onrepairSurfacePickRemoveFinish {} {
    if {($curveRemoveList != "") && $auto_pick_mode} {
	    repairGeomDEZ apply
        if {[aie_active_dez] == "repairGeomDEZ"} {
	        repairSurfacePickRemove pick
        }
    }
}
#-----------------------------------------------
proc onrepairSurfGap2PickFinish {} {
    if {($curveCloseGapCADList != "") && $auto_pick_mode} {
	    repairGeomDEZ apply
        if {[aie_active_dez] == "repairGeomDEZ"} {
	        repairSurfGap2Pick pick
        }
    }
}
#-----------------------------------------------
proc onrepairSurfacePickFoldedFinish {} {
    if {($FoldedSurf != "") && $auto_pick_mode} {
        repairGeomDEZ apply
        if {[aie_active_dez] == "repairGeomDEZ"} {
	        repairSurfacePickFolded pick
        }
    }
}

proc ontransformSurfsToolsDEZOK {} {
    global aie_SurfStyle

    if [info exists LongList] {
        set thelist $LongList
    } else {
        set thelist $surfaceList
    }
    
    # set the allowable entities to operate on
    set entities {surface curve body density point}
    if ![llength $thelist] {
        mess "Selection is empty, so selecting all entities and setting \"Keep Topology\" to true\n" blue
        set detachFlag 1
        foreach ent $entities { 
            set n [ic_geo_get_objects $ent]
            if {$n != ""} {
                foreach e $n {
                    append thelist "$ent $e "
                }
            }
        }
    } else {
        if $detachFlag {
            if {[expr [llength $thelist] / 2] != [llength [ic_geo_get_objects "surface curve point body density"]]} {
                mess "Only parts of the whole geometry were selected, setting \"Keep Topology\" to false\n"
	            set detachFlag 0
            }
        }
    }
    
    foreach ent $entities { set EntityList($ent) "" }
    for {set i 0} {$i < [llength $thelist]} {incr i 2} {
        set t [lindex $thelist $i]
        set n [lindex $thelist [expr $i+1]]
        foreach ent $entities {
            if {$t == $ent} { lappend EntityList($ent) $n }
        }
    }
    set no_geom_found 1
    foreach ent $entities {
        if {$EntityList($ent) != ""} {
            set no_geom_found 0
            break
        }
    }
    if $no_geom_found {
        mess "Select entities\n" red
        return
    }

    # first see if we should copy the entities and check input
    set do_copy 0
    set num_copies 1
    switch -- $transfrmSurfsEGVal {
        0 {
            set do_copy $copyTranslateGGVal
            set num_copies $numCopies
            switch -- $moveSurfsEGVal {
                0 {
                    set off_set "${x}, ${y}, $z"
                    set off_set [ic_vset -vec - $off_set]
                    if {$off_set == ""} {
                        mess "Define Offset X,Y,Z\n" red
                        return
                    }
                }
                1 {
                    set off_set [ic_vcalc diff [lindex $pointList2 0] [lindex $pointList2 1]]
                    if ![llength $off_set] {
                        mess "Select 2 points\n" red
                        return
                    }
                    set mvdis [ic_vset -var - $movedistance]
                    if {$mvdis == "" || $mvdis == "0"} {
                        mess "Wrong distance\n" red
                        return
                    }
                    set nrm [ic_vcalc nrm $off_set]
                    set off_set [ic_vcalc smult $nrm $mvdis]
                    set to_move $movedistance
                    set to_add $to_move
                }
            }
            set off_set_base $off_set
        }
        1 {
            set do_copy $copyRotateGGVal
            set num_copies $numCopies
            set current_angle [ic_vset -var - $rot_angle]
            if {$current_angle == ""} {
                mess "Angle not specified!\n" red
                return
            }
            set rot_angle $current_angle
        }
        2  { set do_copy $copyMirrorGGVal }
        3  { set do_copy $copyScaleGGVal }
        4  { set do_copy $copyAutoGGVal }
    }
    if !$do_copy {
        set num_copies 1
    }

    if {$EntityList(body) != ""} {
        foreach body $EntityList(body) {
            set EntityList(surface) [aie_get_entities_without_body surface $EntityList(surface) $body]
        }
    }

    set resume 0
    if ![ic_undo_suspended] {
        ic_undo_group_begin
        set resume 1
    }

    for {set current_copy 0} {$current_copy < $num_copies} {incr current_copy} {
        # other key words will be kept on appended.
        foreach ent $entities {
            set argList($ent) "ic_move_geometry $ent names"
        }
        if {$do_copy != 0} {
            foreach ent $entities { set nEntityList($ent) "" }
            set ext [aie_check_names_get_ext .$current_copy $ent $EntityList($ent)]
            foreach ent $entities {
                foreach i $EntityList($ent) {
                    # append $nname nitem. Now duplicate $i to $ nitem.
                    if {$ent == "body"} {
                        set nitem [ic_geo_duplicate_set_fam_and_data $ent $i ${i}$ext $transfrParts _$current_copy 1]
                    } else {
                        set nitem [ic_geo_duplicate_set_fam_and_data $ent $i ${i}$ext $transfrParts _$current_copy]
                    }
                    lappend nEntityList($ent) $nitem
                }
            }
        }

        #---------------------entity copying and organization finished------

        if {$do_copy == 0} {
            foreach ent $entities {
                lappend argList($ent) $EntityList($ent)
            }
        } else {
            foreach ent $entities {
                lappend argList($ent) $nEntityList($ent)
            }
        }

        switch -- $transfrmSurfsEGVal {
            0 {
                # Start Translating Geometry --------------
                switch -- $moveSurfsEGVal {
                    0 {
                        # translation by explicit offset goes here
                        foreach ent $entities {
                            lappend argList($ent) translate $off_set
                        }
                    }
                    1 {
                        # translate by 2 point vector goes here
                        # the direction vector will be calculated in ic_move_geometry in case of two selected points
                        if {[ic_geo_check_objects_exist point [lindex $pointList2 0]] != "" && [ic_geo_check_objects_exist point [lindex $pointList2 1]] != ""} {
                            foreach ent $entities {
                                lappend argList($ent) translate $pointList2 distance $to_move
                            }
                            set to_move [expr $to_add + (($current_copy + 1.0) * $to_add)]
                        } else {
                            foreach ent $entities {
                                lappend argList($ent) translate $off_set
                            }
                        }
                    }
                }
                set off_set [ic_vcalc sum $off_set $off_set_base]
            }
            1 {
                # Start rotating surfaces-------------------------------------
                switch -- $geomRotateAxisOptionEGVal {
                    0 { set rot_axis {1 0 0} }
                    1 { set rot_axis {0 1 0} }
                    2 { set rot_axis {0 0 1} }
                    3 {
                        if {$axisSurfList == "" || [llength $axisSurfList] != 2} {
                            mess "Select 2 points for vector\n" red
                            if $resume { ic_undo_group_end }
                            return
                        } else {
                             if {$axisSurfList != "" && [llength $axisSurfList] == 2} {
                                foreach p $axisSurfList {
                                    if {![va_is_triplet $p] && [ic_geo_check_objects_exist point $p] == ""} {
                                        mess "Vector: unknown point $p\n" red
                                        if $resume { ic_undo_group_end }
                                        return
                                    }
                                }
                             }
                        }
                        set rot_axis $axisSurfList
                    }
                }
                foreach ent $entities {
                    lappend argList($ent) rotate $current_angle rotate_axis $rot_axis
                }
                set current_angle [expr $current_angle+$rot_angle]
                # now fix the center of rotation-----
                switch -- $RotateGeomCenterEGVal {
                    0 { set transfCenter {0 0 0} }
                    1 { set transfCenter "centroid" }
                    2 {
                        if {![va_is_triplet $rotateCenterPnt] && ([ic_geo_check_objects_exist point $rotateCenterPnt] == "")} {
                            mess "\n Center not selected \n" red
                            if $resume { ic_undo_group_end }
                            return
                        }
                        set transfCenter $rotateCenterPnt
                    }
                }
                foreach ent $entities {
                    lappend argList($ent) cent $transfCenter
                }
            }
            # finish rotation business
            2 {
                switch -- $geomMirrorAxisOptionEGVal {
                    0 { set mirror_norm {1 0 0} }
                    1 { set mirror_norm {0 1 0} }
                    2 { set mirror_norm {0 0 1} }
                    3 {
                        # Start Mirroring Surfs; the direction vector will be calculated in ic_move_geometry
                        if {$normPointList == "" || [llength $normPointList] != 2} {
                            mess "Select 2 points for vector\n" red
                            if $resume { ic_undo_group_end }
                            return
                        }
                        set mirror_norm $normPointList
                    }
                }
                foreach ent $entities {
                    lappend argList($ent) mirror $mirror_norm
                }
                # now fix the center of Reflection-----
                switch -- $ReflectGeomCenterEGVal {
                    0 { set transfCenter {0 0 0} }
                    1 { set transfCenter "centroid" }
                    2 {
                        if {![va_is_triplet $reflectCenterPnt] && ([ic_geo_check_objects_exist point $reflectCenterPnt] == "")} {
                            mess "Center for Reflection not specified\n" red
                            if $resume { ic_undo_group_end }
                            return
                        }
                        set transfCenter $reflectCenterPnt
                    }
                }
                foreach ent $entities {
                    lappend argList($ent) cent $transfCenter
                }
            }
            3 {
                # Start Scaling Surfs
                set scaleFactor [list $xF $yF $zF]
                foreach ent $entities {
                    lappend argList($ent) scale $scaleFactor
                }
                # now fix the center of Reflection-----
                switch -- $ScaleGeomCenterEGVal {
                    0 { set transfCenter {0 0 0} }
                    1 { set transfCenter "centroid" }
                    2 {
                        if {![va_is_triplet $scaleCenterPnt] && ([ic_geo_check_objects_exist point $scaleCenterPnt] == "")} {
                            mess "Center for scaling not specified\n" red
                            if $resume { ic_undo_group_end }
                            return
                        }
                        set transfCenter $scaleCenterPnt
                    }
                }
                foreach ent $entities {
                    lappend argList($ent) 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
                        return
                    } else {
                        set reset_csys ""
                        set ta [tdv_active 0]
                        foreach ent $entities {
                            if {$do_copy == 0} {
                                if {$EntityList($ent) == ""} continue
                                ic_geo_move_lcs_lcs $cur_csys global $ent $EntityList($ent)
                            } else {
                                if {$nEntityList($ent) == ""} continue
                                ic_geo_move_lcs_lcs $cur_csys global $ent $nEntityList($ent)
                            }
                            lappend reset_csys $ent
                        }
                        tdv_active $ta
                        if {$reset_csys != ""} {
                            ic_csystem_set_current global
                        }
                    }
                }
            }
            4  {
                switch $transAutoEGVal {
                    0 {
                        if {[llength $rotateAutoList] != 6} {
                            mess "Select 6 locations\n" red
                            if $resume { ic_undo_group_end }
                            return
                        }
                        foreach "p00 p01 p02 p10 p11 p12" $rotateAutoList ""
                        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 $rotateAutoList] != 2} {
                            mess "Select two curves\n" red
                            if $resume { ic_undo_group_end }
                            return
                        }
                        foreach i "0 1" {
                            set crv [lindex $rotateAutoList $i]
                            if ![llength [ic_geo_check_objects_exist curve $crv]] {
                                mess "Select two curves!\n" red
                                if $resume { ic_undo_group_end }
                                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
                    }
                }
                # Check that each triplet is not on the same line:
                set ta [tdv_active 0]
                foreach ent $entities {
                    if {$do_copy != 0} { set EntityList($ent) $nEntityList($ent) }
                    if {[llength $EntityList($ent)] == 0} continue
                    ic_geo_move_lcs_lcs $from $to $ent $EntityList($ent)
                }
                tdv_active $ta
                status_message Done
                if $resume { ic_undo_group_end }
                aie_create_parts_in_tree_if_needed 
                aie_update_icons geom
                aie_part_update_nodes
                ic_geo_reset_data_structures
                return
            }
        }

        #---------------Consider copying and moving-----------------------------------

        busy 1
             
        if {$do_copy == 0 } {
            foreach ent $entities {
                if {[llength $EntityList($ent)] != 0} {
                    if {$detachFlag == 1} { lappend argList($ent) detach 0 }
                    eval $argList($ent)
                }
            }
            status_message "Move geometry done"
        } else {
            foreach ent $entities {
                if {[llength $nEntityList($ent)] != 0} {
                    if {$detachFlag == 1} { lappend argList($ent) detach 0 }
                    eval $argList($ent)
                }
            }
            if {$num_copies > 1} {
                status_message "Copy ([expr $current_copy + 1]) geometry done"
            } else {
                status_message "Copy geometry done"
            }
        }
        if $resume { ic_undo_group_end }
        busy 0
    }

    switch $transfrmSurfsEGVal {
        3 {
            if {[info exists reset_csys] && $reset_csys != ""} {
                set ta [tdv_active 0]
                foreach ent $reset_csys {
                    if {$do_copy == 0} {
                        ic_geo_move_lcs_lcs global $cur_csys $ent $EntityList($ent)
                    } else {
                        ic_geo_move_lcs_lcs global $cur_csys $ent $nEntityList($ent)
                    }
                }
                tdv_active $ta
                ic_csystem_set_current $cur_csys
                unset reset_csys; unset cur_csys
            }
        }
    }

    aie_create_parts_in_tree_if_needed 
    aie_update_icons geom
    aie_part_update_nodes
    ic_geo_reset_data_structures
    transformSurfsToolsDEZ setdirty
    # Strange behaviour, but needed to update the display style of new surface elements
    after 200 {
        foreach style {wire flat_wire solid flat} {
            if {[info exists aie_SurfStyle($style)] && $aie_SurfStyle($style)} {
                ic_geo_configure_one_attribute surface shade $style
                break
            }
        }
    }
    if [ic_hex_blocking_loaded] {
        hex_update_display
    }
}

proc aie_get_entities_without_body {type entities body} {
    if {$body == ""} { return $entities }
    set with_body ""
    set without_body ""
    foreach b $body {
        foreach {t n} [ic_geo_body_lower_entities $b] {
            if {"$t" == "$type"} { append with_body "$n " }
        }
        foreach s $entities {
            if {[lsearch $with_body $s] < 0} {
                append without_body "$s "
            }
        }
    }
    return $without_body
}

proc onrotateAutoFromLcsLoad {} {
	# must reset after load because at first call picker was not created 
	aie_reset_picker "" rotateAutoLcsFrom image Utils_LCS24.gif helptext "Select Coordinate System"
	aie_reset_picker "" rotateAutoLcsTo image Utils_LCS24.gif helptext "Select Coordinate System"
}

proc onrotateAutoLcsFromFinish {} {
	if $auto_pick_mode {
		if ![llength [ic_csystem_get $fromLCS]] return
		rotateAutoLcsTo pick
	}		
}

proc onrotateAutoLcsToFinish {} {
    return
	if $auto_pick_mode {
		if ![llength [ic_csystem_get $toLCS]] return
		transformSurfsToolsDEZ apply
		rotateAutoLcsFrom pick
	}		
}

proc onrotateAutoFromLcsLoad {} {
    if {$transfrmSurfsEGVal == 4 && $transAutoEGVal == 2} {
        if ![llength [ic_image get global]] {
            ic_image csys_im cartesian
        }
    }
}

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

proc ontransAutoEGILoad {} {
    if {$transfrmSurfsEGVal == 4 && $transAutoEGVal == 2} {
        if ![llength [ic_image get global]] {
            ic_image csys_im cartesian
        }
    }
}

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

proc ShowAllLCSProc {} {
	if ![llength [ic_image get global]] {
		ic_image csys_im cartesian
	} else {
		ic_image delete csys_im
	}
}

proc ontransformSurfsToolsDEZUnLoad {} {
	ic_highlight
	ic_image delete
	set surfaceList ""
	if [info exists LongList] { unset LongList }
	if {[trace vinfo numCopies] != ""} {
	    trace vdelete numCopies w aie_perCopyAngleRot
	}
    if [llength [ic_image get global]] {
        ic_image delete csys_im
    }
}

proc ontransformSurfsToolsDEZLoad {} {

    aie_default_topo_tolerance
    if ![info exists numCopies] {
        set copyFlag 0
        set numCopies 1
        set rot_angle 180	
    }
    set surfaceList ""
    set transfrParts ""
    set detachFlag 1
    if [info exists LongList] { unset LongList }
    if ![info exists transformSurfsToolsInit] {
        set transformSurfsToolsInit 1
        set name new_name
        set x 0;set y 0;set z 0
        set xF 1; set yF 1; set zF 1
        set entities {surface curve body density point}
        # set X axis as the default rotation axis
        set normSurfList {1 0 0}
        set copyTranslateGGVal 0
        set copyRotateGGVal 0
        set copyMirrorGGVal 0
        set copyScaleGGVal 0
        set copyAutoGGVal 0
        set transfrmSurfsEGVal 0
        set transAutoEGVal 0
    }
    if {$transfrmSurfsEGVal == 4 && $transAutoEGVal == 2} {
        if ![llength [ic_image get global]] {
            ic_image csys_im cartesian
        }
    }
}

proc ontransformSurfsToolsDEZAfterLoad {} {
	if {[trace vinfo numCopies] != ""} {
	    trace vdelete numCopies w aie_perCopyAngleRot
	}
    trace variable numCopies w aie_perCopyAngleRot
    if ![ic_geo_num_visible_objects entity] {
        set vis 0
        foreach s [ic_geo_subset_list] {
            set vis [expr [::AIEnv::GUIManagement::Tree::NodeVisibleStatus geom_subset $s] == 1]
            if $vis break
        }
        if !$vis {
            mess "Warning: No geometry objects visible\n" red
        }
    }
}

proc ontransfmoveSurfs2PPickFinish {} {
    if {[llength $pointList2] == 1} {
        set pointList2 [list "0 0 0" [lindex $pointList2 0]]
    }
    set movedistance [ic_vcalc distance [lindex $pointList2 0] [lindex $pointList2 1]]
}

proc ondeletePointsDEZAfterLoad {} {
    global IgnoreActiveReload

    set ::IgnoreActiveReload(deletePointsDEZ,pointsList) 1
    set ::AIEnv::GUIManagement::Picker::force_med_selection 1
    set DelNotSelFlag 0
    set DelUnattFlag 0
    set JoinCrvFlag  0
    set pointsList ""
    if [info exists LongList] { unset LongList }
    
    if $auto_pick_mode {deletePointsPick pick}
}
proc ondeletePointsDEZUnLoad {} {
    global IgnoreActiveReload

    catch { unset ::IgnoreActiveReload(deletePointsDEZ,pointsList) }
    set ::AIEnv::GUIManagement::Picker::force_med_selection 0
    aie_geo_set_grey deletePointsPick 0
    if [info exists LongList] { unset LongList }
}

proc ondeletePointsDEZOK {} {
    global aie_geoTypeVis

    set n 0
    if [info exists LongList] {
        set thelist $LongList
    } else {
        set thelist $pointsList
    }    
    busy 1
    if [array exists arr_fams] { unset arr_fams }
    if $JoinCrvFlag {
	    if [catch {ic_geo_pnt_mrg_inc_crv names $thelist} res] {
	        mess "Error: $res\n" red
	    } else {
	        if {$res != ""} {
		        mess "Created merge curve $res\n"
	        }
	    }
    }
 
    if $::vid_options(DelPerFlag) {
	    foreach p $thelist {
	        set fam [ic_geo_get_family point $p]
	        set arr_fams($fam) 1
	    }
	    set n [ic_delete_geometry point names $thelist 0 1]
    } else {
	    set pts_to_delete ""
	    set pts_to_dormant "" 
	    foreach p $thelist {
	        if [llength [ic_geo_incident point $p 1]] {
		        lappend pts_to_dormant $p
	        } else {
		        lappend pts_to_delete $p
		        set fam [ic_geo_get_family point $p]
		        set arr_fams($fam) 1			
	        }
	    }
	    if [llength $pts_to_delete] {
	        set n [ic_delete_geometry point names $pts_to_delete 0 1]
	    }
	    if [llength $pts_to_dormant] {
	        set msg [ic_geo_set_dormant_entity point $pts_to_dormant 1]
	    }	
    }
    
    set thelist ""
    if $DelUnattFlag {
        foreach p [ic_geo_get_objects point ""] {
            if {[llength [ic_geo_incident point $p 1]] == 0} {
		        lappend thelist $p
		        set fam [ic_geo_get_family point $p]
		        set arr_fams($fam) 1
	        }
	    }
	    set n [ic_delete_geometry point names $thelist 0 1]
    }
    # Now delete connectors from tree
    foreach fam [array names arr_fams] {
        set gname [aie_connectors_get_group_comprising $fam]
        if {$gname != ""} {
            aie_connectors_delete_group_directives $gname
        }
    }
    set pointsList ""
    set LongList ""
    if {[info exists aie_geoTypeVis(point)] && $aie_geoTypeVis(point)} {
        ::AIEnv::GUIManagement::Tree::ShowDormant point
    }

    if $n {
        if $::vid_options(DelPerFlag) {
            if [array exists arr_fams] {
                aie_delete_part_if_empty [array names arr_fams]
            }
        }
        mess "$n point(s) deleted\n" blue
    }
    busy 0  
}

proc ondeletePointsPickFinish {} {
    if {($pointsList != "") && $auto_pick_mode} {
        deletePointsDEZ apply
	    if ![ic_geo_num_objects point] return
        deletePointsPick pick
    }
}

proc ondeleteCurveDEZAfterLoad {} {
    global IgnoreActiveReload

    set ::IgnoreActiveReload(deleteCurveDEZ,curveList) 1
    set DelUnattFlag 0
    set DelNotSelFlag 0
    set curveList ""
    if $auto_pick_mode { deleteCurvePick pick }
}

proc ondeleteCurveDEZUnLoad {} {
    global IgnoreActiveReload

    catch { unset ::IgnoreActiveReload(deleteCurveDEZ,curveList) }
    aie_geo_set_grey deleteCurvePick 0   
    if [info exists LongList] { unset LongList }
}

proc ondeleteCurveDEZLoad {} {
    global env
    
    if {[ic_uns_is_loaded] && ![info exists env(AI_ENV_CFX)]} {
        if ![meshAutoDEZ isbuilt] {
	        meshAutoDEZ build
        }
        if ![mszGlobalDEZ isbuilt] {
	        mszGlobalDEZ build
        }
    }
    if [info exists LongList] { unset LongList }
}

proc ondeleteCurveDEZOK {} {
    global env aie_geoTypeVis

    if [info exists LongList] {
        set thelist $LongList
    } else {
        set thelist $curveList
    }
    busy 1
    set num_curvs 0
    if [array exists arr_fams] { unset arr_fams }
    if $::vid_options(DelPerFlag) {
        foreach c $thelist {
            set fam [ic_geo_get_family curve $c]
            set arr_fams($fam) 1
        }
	    set num_curvs [ic_delete_geometry curve names $thelist 0 1]
    } else {
	    set crvs_to_delete ""
	    set crvs_to_dormant ""
	    foreach c $thelist {
	        if {[ic_geo_crv_is_edge $c] || ([ic_geo_incident curve $c] != "")} {
	            lappend crvs_to_dormant $c
	        } else {
		        lappend crvs_to_delete $c
		        set fam [ic_geo_get_family curve $c]
		        set arr_fams($fam) 1			
	        }
	    }
	    if [llength $crvs_to_delete] {
	        set num_curvs [ic_delete_geometry curve names $crvs_to_delete 0 1]
	    }
	    if [llength $crvs_to_dormant] {
	        set msg [ic_geo_set_dormant_entity curve $crvs_to_dormant 1]
	        if {[ic_uns_is_loaded] && ![info exists env(AI_ENV_CFX)]} {
	            set attached_surfs ""
	            foreach c $crvs_to_dormant {
	                foreach s [ic_geo_incident curve $c] {
	                    lappend attached_surfs $s
	                }
	            }
	            if {$attached_surfs != ""} {
	                if ![tk_dialog .remesh_attached "Remesh ?" "Mesh exists. Remesh attached surfaces ?" "" -1 Yes No] {
                        foreach c $crvs_to_dormant {
                            set map [ic_uns_get_attached_elements curve $c]
                            if {($map != "") && ([ic_uns_subset_count_elements $map] > 0)} {
                                ic_delete_elements subset $map
                                mess "Removed mesh from curve: $c\n" blue
                                ic_uns_subset_delete $map
                            }                           
                        }
                        set delmaps ""
                        foreach s $attached_surfs {
                            set map [ic_uns_get_attached_elements surface $s]
                            lappend delmaps $s $map
                        }
                        set nquads 0; set ntris 0
                        foreach {s map} $delmaps {
                            if {($map != "") && ([ic_uns_subset_count_elements $map] > 0)} {
                                foreach el [ic_uns_subset_list_elements $map] {                                
                                    if {([regexp TRI_+ [lindex $el 0]]) == 1} {
                                        incr ntris
                                    } elseif {([regexp QUAD_+ [lindex $el 0]]) == 1} {
                                        incr nquads
				                    }
                                }                            
                                ic_delete_elements subset $map
                                mess "Removed mesh from surface: $s\n" blue
                                ic_uns_subset_delete $map
                            }
                        }
			            if {$nquads && !$ntris} {
			                set type "Quad w/one Tri"
			            } elseif {$ntris && !$nquads} {
			                set type "All Tri"
			            } else {
			                set type "Quad Dominant"
			            }
			            set type_number [aie_surface_get_mesh_type_number $type]
	                    meshAutoDEZ onmeshAutoSurfLoad
	                    mess "Remeshing surfaces: $attached_surfs using mesh type \"$type\"\n" blue
	                    set surfaces ""
	                    catch { unset surf_params }
	                    foreach s $attached_surfs {
	                        foreach {n v} [ic_get_meshing_params surface $s] {
	                            if {$n == "etyp"} {
                                    set surf_params($s) $v
                                    ic_set_meshing_params surface $s etyp $type_number
                                }
	                        }
	                        append surfaces "surface $s "	    
	                    }
	                    meshAutoDEZ set geomEnts "$surfaces"
	                    meshAutoDEZ aie_compute_surface_mesh
	                    meshAutoDEZ set geomEnts ""
	                    foreach s [array names surf_params] {
	                        ic_set_meshing_params surface $s etyp $surf_params($s)
	                    }
	                    catch { unset surf_params }
		                if {[ic_uns_dimension] == 3} {
		                    set has_hex 0; set has_prism 0
		                    foreach s $attached_surfs {
		                        if {$has_hex || $has_prism} break
		                        set map [ic_uns_get_attached_elements surface $s]
                                foreach t [ic_uns_subset_list_types $map] {
	                                if {[string range $t 0 3] == "HEXA"} { set has_hex 1 }
	                                if {[string range $t 0 4] == "PENTA"} { set has_prism 1 }
                                }
                            }
                            set const_mess "Making volume mesh consistent with surface mesh elements ?"
                            if {$has_hex || $has_prism} {
                                append const_mess "\nWarning: This operation will make the volume mesh inconsistent !"
                            }
	                        switch -- [tk_dialog .make_consistent "Make Volume Consistent" "$const_mess" "" -1 Yes No] {
                                0 {
                                    mess "Making volume mesh consistent with surface mesh elements\n" blue
                                    ic_uns_make_consistent all
                                }
                                -1 {
                                    if [winfo exists .make_consistent] { top_destroy .make_consistent }
                                }
	                        }
	                    }
                    }
                    if [winfo exists .remesh_attached] { top_destroy .remesh_attached }
	            } 
	        }
	    }	
    }
    set thelist ""
    if $DelUnattFlag {
	    foreach c [ic_geo_get_objects curve ""] { 
	        if {[llength [ic_geo_incident curve $c]] == 0} {
		        lappend thelist $c
		        set fam [ic_geo_get_family curve $c]
		        set arr_fams($fam) 1	
	        }
	    }
	    set num_curvs [ic_delete_geometry curve names $thelist 0 1]
    }
    foreach fam [array names arr_fams] {
        set gname [aie_connectors_get_group_comprising $fam]
        if {$gname != ""} {
            aie_connectors_delete_group_directives $gname
        }
    }
    
    if {[info exists aie_geoTypeVis(curve)] && $aie_geoTypeVis(curve)} {
        ::AIEnv::GUIManagement::Tree::ShowDormant curve
    }
    busy 0
    set curveList "" 
    set LongList ""
    if $::vid_options(DelPerFlag) {
        if {[string is integer -strict $num_curvs] && $num_curvs > 0} {
            if [array exists arr_fams] {
                aie_delete_part_if_empty [array names arr_fams]
            }
            mess "$num_curvs curve(s) deleted\n" blue
        }
    }
}

proc ondeleteCurvePickFinish {} {

    if {($curveList != "") && $auto_pick_mode} {
	    deleteCurveDEZ apply
	    if ![ic_geo_num_objects curve] return
	    deleteCurvePick pick
    }
}

proc ondeleteSurfDEZOK {} {

    set n 0
    if [info exists LongList] {
        set thelist $LongList
    } else {
        set thelist $surfList
    }
    if [array exists arr_fams] { unset arr_fams }
    if {$thelist != ""} {
        if ![aie_detect_surface_bodies_to_delete $thelist] return
        busy 1
        if {$thelist == "all" || $thelist == "visible" || $thelist == "blanked"} {            
            set n [ic_delete_geometry surface $thelist]
        } else {
	        foreach p $thelist {
	            set fam [ic_geo_get_family surface $p]
	            set arr_fams($fam) 1
	        }
            set n [ic_delete_geometry surface names $thelist 0]
        }
        busy 0
        set surfList ""
        if $n {
            if [array exists arr_fams] {
                aie_delete_part_if_empty [array names arr_fams]
            }
            mess "$n surface(s) deleted\n" blue
        }
    }
}

proc aie_detect_surface_bodies_to_delete {thelist} {

    set bodies_to_delete ""
    if {$thelist == "all" || $thelist == "visible" || $thelist == "blanked"} {
        set objs ""
        foreach t [ic_geo_lookup surface $thelist] {
            lappend objs [lindex $t 1]
        }
    } else {
        set objs $thelist
    }
    foreach b [ic_geo_get_objects body] {
        foreach "t e" [ic_geo_body_lower_entities $b] {
            if {$t == "surface"} {
                if {[lsearch $objs $e] > -1} {
                    if {[lsearch $bodies_to_delete $b] < 0} { lappend bodies_to_delete $b }
                }
            }
        }
    }
    if {$bodies_to_delete != ""} {
        switch -- [tk_dialog .deletebody "Delete bodies?" "Warning: this will delete all bodies\
            which belong to the selected surface(s)" "" -1 "Continue" "Cancel"] {
            -1 { if [winfo exists .deletebody] { top_destroy .deletebody; return 0 } }
            0 {
                ic_delete_geometry body names $bodies_to_delete 0
                mess "[llength $bodies_to_delete] bodies deleted\n" blue
                return 1
            }
            1 { return 0 }
        }
    }
    return 1
}

proc ondeleteSurfPickFinish {} {
    if {($surfList != "") && $auto_pick_mode} {
	    deleteSurfDEZ apply
	    if ![ic_geo_num_objects surface] return
	    deleteSurfPick pick
    }
}

proc ondeleteSurfDEZAfterLoad {} {
    global IgnoreActiveReload

    set ::IgnoreActiveReload(deleteSurfDEZ,surfList) 1
    if [info exists LongList] { unset LongList }
	set surfList ""
    if $auto_pick_mode {deleteSurfPick pick}
}

proc ondeleteSurfDEZUnLoad {} {
    global IgnoreActiveReload

    catch { unset ::IgnoreActiveReload(deleteSurfDEZ,surfList) }
    if [info exists LongList] { unset LongList }
}

proc onmoveBodyDEZLoad {} {
    set moveBodyOffsetGGVal 0
}

proc ondeleteBodyPickFinish {} {
    if {($bodyList != "") && $auto_pick_mode} {
	    deleteBodyDEZ apply
	    if ![ic_geo_num_objects material] return
	    deleteBodyPick pick
    }
}

proc ondeleteBodyDEZOK {} {

    if {$bodyList != ""} {
        if [array exists arr_fams] { unset arr_fams }
	    foreach p $bodyList {
	        set fam [ic_geo_get_family body $p]
	        set arr_fams($fam) 1
	    }
        set n [ic_delete_geometry body names $bodyList 0]
        if $n {
            if [array exists arr_fams] {
                aie_delete_part_if_empty [array names arr_fams]
                aie_delete_part_if_empty "SHELL LUMP"
            }
            mess "$n bodies deleted\n" blue
        }
        set bodyList ""
    }
}

proc ondeleteBodyDEZAfterLoad {} {
    global IgnoreActiveReload
    
    set bodyList ""
    set ::IgnoreActiveReload(deleteBodyDEZ,bodyList) 1
    if {$auto_pick_mode && [ic_geo_num_objects material]} {
        deleteBodyPick pick
    }
}

proc ondeleteBodyDEZCancel {} {
    global IgnoreActiveReload
    
    catch { unset ::IgnoreActiveReload(deleteBodyDEZ,bodyList) }
}

proc ondeleteEntityDEZAfterLoad {} {
    global IgnoreActiveReload

    set ::IgnoreActiveReload(deleteEntityDEZ,entityList) 1
    set entityList ""
    set DelUnattFlag 0
    set DelNotSelFlag 0
    if $auto_pick_mode {deleteEntityPick pick}
}

proc ondeleteEntityDEZUnLoad {} {
    global IgnoreActiveReload
    catch { unset ::IgnoreActiveReload(deleteEntityDEZ,entityList) }
    aie_geo_set_grey deleteEntityPick 0
}

proc ondeleteEntityDEZOK {} {
    global aie_geoTypeVis
    
    busy 1
    if ![ic_undo_suspended] {
        ic_undo_group_begin
        set resume 1
    } else {
        set resume 0
    }
    set list(curve) ""
    set list(surface) ""
    set list(point) ""
    set list(body) ""
    set list(density) ""
    if [array exists arr_fams] { unset arr_fams }
    foreach {type name} $entityList {
        lappend list($type) $name
        set fam [ic_geo_get_family $type $name]
	    set arr_fams($fam) 1
    }
    if {$list(point) != ""} {
        if $::vid_options(DelPerFlag) {
            ic_delete_geometry point names $list(point) 0 1
        } else {
            set pts_to_delete ""
            set pts_to_dormant ""
            foreach p $list(point) {
                if [llength [ic_geo_incident point $p]] {
                    lappend pts_to_dormant $p
                    ic_geo_set_dormant_entity point $p 1
                } else {
                    lappend pts_to_delete $p
                }
            }
            if [llength $pts_to_delete] {ic_delete_geometry point names $pts_to_delete 0 1}
            if [llength $pts_to_dormant] {
                set msg [ic_geo_set_dormant_entity point $pts_to_dormant 1]
            }
        }
    }
    if {$list(curve) != ""} {
        if $::vid_options(DelPerFlag) {
            ic_delete_geometry curve names $list(curve) 0 1
        } else {
            set crvs_to_delete ""
            set crvs_to_dormant ""
            foreach c $list(curve) {
                if [llength [ic_geo_incident curve $c]] {
                    lappend crvs_to_dormant $c
                } else {
                    lappend crvs_to_delete $c
                }
            }
            if [llength $crvs_to_delete] {ic_delete_geometry curve names $crvs_to_delete 0 1}
            if [llength $crvs_to_dormant] {
                set msg [ic_geo_set_dormant_entity curve $crvs_to_dormant 1]
            }
        }
    }
    if {$list(body) != ""} {ic_delete_geometry body names $list(body) 0}
    if {$list(surface) != ""} {
        if ![aie_detect_surface_bodies_to_delete $list(surface)] return
        ic_delete_geometry surface names $list(surface) 0
    }
    if {$list(density) != ""} {ic_delete_geometry density names $list(density) 0}
    if $DelUnattFlag {ic_geo_delete_unattached}
    set entityList ""
    foreach t {point curve} {
        if {[info exists aie_geoTypeVis($t)] && $aie_geoTypeVis($t)} {
            ::AIEnv::GUIManagement::Tree::ShowDormant $t
        }
    }
    if [array exists arr_fams] {
        if $::vid_options(DelPerFlag) {
            aie_delete_part_if_empty [array names arr_fams]
        }
    }
    if $resume { ic_undo_group_end }
    busy 0
}

proc ondeleteEntityPickFinish {} {
    # automatic apply when middle mouse button is pressed
    if {($entityList != "") && $auto_pick_mode} {
	    deleteEntityDEZ apply
	    deleteEntityPick pick
    }
}

proc onRestoreEntityDEZAfterLoad {} {
    global restore aie_ShowDormant
    
    mess "Detecting dormant points/curves..."
    foreach type {curve point} {
        set DORMANT($type) 0
        set restore(display_option,dormant,$type) $aie_ShowDormant($type)
        set tmp($type) [ic_geo_get_dormant $type]
        set len [llength $tmp($type)]
        if $len {
	        set aie_ShowDormant($type) 1
	        ::AIEnv::GUIManagement::Tree::ShowDormant $type
	        incr DORMANT($type) $len          
        }
    }
    mess "done\n"
    if {!$DORMANT(point) && !$DORMANT(curve)} {
	    mess "No dormant entities\n" red
	    restoreEntityDEZ cancel
    } else {
        if $DORMANT(point) {
            mess "Found $DORMANT(point) dormant point(s)\n"
        }
        if $DORMANT(curve) {
            mess "Found $DORMANT(curve) dormant curve(s)\n"
        }
    }
}
proc onRestoreCPickPick {} {
	set dclist [ic_geo_get_dormant curve]
	if ![llength $dclist] {
		ic_mess "No dormant curves\n" red
		return cancelpick
	} 
	ic_geo_set_tag clear "" dormant.curve 0			
	foreach c $dclist {
		ic_geo_set_tag curve $c dormant.curve 1
#		ic_geo_configure_one_object curve $c width 2				
    }
}
proc onRestorePPickPick {} {
	set dplist [ic_geo_get_dormant point]
	if ![llength $dplist] {
		ic_mess "No dormant points\n" red
		return cancelpick
	} 
	ic_geo_set_tag clear "" dormant.point 0			
	foreach c $dplist {
		ic_geo_set_tag point $c dormant.point 1
#		ic_geo_configure_one_object point $c width 2				
    }
}

proc onRestoreCPickFinish {} {
		foreach c $dclist {
#			ic_geo_configure_one_object curve $c width 1				
		}
    if {($curveList != "") && $auto_pick_mode} {
	restoreEntityDEZ apply
	restoreCPick pick
    }
}
proc onRestorePPickFinish {} {
		foreach c $dplist {
#			ic_geo_configure_one_object point $c width 1				
		}
    if {($pointList != "") && $auto_pick_mode} {
	restoreEntityDEZ apply
	restorePPick pick
    }
}
proc onRestoreEntityDEZUnLoad {} {
    global restore aie_ShowDormant
    foreach type {curve point} {
	if [info exists restore(display_option,dormant,$type)] {
	    set aie_ShowDormant($type) $restore(display_option,dormant,$type)
	    ::AIEnv::GUIManagement::Tree::ShowDormant $type
	    unset restore(display_option,dormant,$type)
	}	
    }
}

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

proc onRestoreEntityDEZOK {} {
	# Restore only in original family.
    foreach p $pointList  {
	ic_geo_set_dormant_entity point $p 0
    }
    set pointList ""
    foreach c $curveList  {
	ic_geo_set_dormant_entity curve $c 0
    }
    set curveList ""
}

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

proc onunitsGeometryDEZLoad {} {
    set units [ic_geo_get_units]
    if {$units == ""} {set units unitless}
}

proc onunitsGeometryDEZOK {} {
    if {$units != ""} {
        if {$units == "unitless"} {
            ic_geo_set_units ""
        } else {
            ic_geo_set_units $units
        }
    }
}

#================================================helping routines=================================
proc va_proj_point_on_surface {pnt surf new_pnt_fam new_pnt_name} {
    global tdv_default

    ic_geo_new_family $new_pnt_fam
    if {[llength $pnt] == 1} { set pnt [ic_geo_get_point_location $pnt] }
    set vn [ic_vcalc nrm [lindex [$tdv_default screen2world 100 100] 1]]
    set p2 [ic_vcalc sum $pnt $vn]

    set line [ic_geo_create_unstruct_curve_from_points TEMP_LINE $new_pnt_fam "\{$pnt\} \{$p2\}"]
    set line_1 [ic_geo_cre_crv_test_project_surface $new_pnt_fam TEMP_LINE_1 $surf $line $vn]
    if {$line_1 == ""} {
	ic_delete_geometry curve names $line
	return
    }
    set pts [ic_geo_extract_points $line_1 90]
    ic_delete_geometry curve names "$line $line_1"
    if {$pts == ""} return
    set p [ic_get_point_location [lindex $pts 0]]
    ic_delete_geometry point names "$pts" 0 1
    return $p
    #  set new_pnt [ic_geo_cre_pnt $new_pnt_fam $new_pnt_name $p]
    #  return $new_pnt
}

# -------------------------------------------
# 
proc aie_try_change_entry_configure {group entry option conf_on_0 conf_on_1 args} {
    # this is a simple temporary proc 
    # group  : e.g., createPoints_xyz
    # entry  :      "x" (3-rd parameter of textEntry)
    # (Cannot use label, 2-nd param, because this is what we want change)
    #  
    # It seems, DEZ names are not converted tolower, but EXG does...???
    
    if {[string first DEZ $group] < 0} {set group [string tolower $group]}
    set adg aie_dialog.$group
    global va_set
    # Next block remember windows to minimize search
    if ![info exists va_set($adg)] {
	foreach w [info commands *${group}*] {
	    if {[string first $group $w] < 0} continue
	    if ![winfo exists $w] continue
	    #			if {[winfo class $w] != "Entry"} continue
	    lappend va_set($adg) $w
	}
    }
    if ![info exists va_set($adg)] {return "1"}
    set elen [string length $entry]
    foreach w $va_set($adg) {
	set k [expr [string length $w] -4]
	if {[string range $w $k end] != "text"} continue
	if ![winfo exists $w] continue
	set conf [$w configure -textvar]
	set from [expr [string length $conf] - $elen]
	if {[string range $conf $from end] != $entry} continue
	# Intentionally keep similar to next procedure: can combine in next version
	if {$option == "0"} {
	    set cnf $conf_on_0
	} else {
	    set cnf $conf_on_1
	}
	set res [catch {eval $w configure $cnf}]
	if $res {ic_mess "$w configure $cnf\n"}
	return Catch$res
    }
}
# -------------------------------------------
proc aie_try_change_entry_label {group entry newlabel} {
    # this is a simple temporary proc 
    # group  : e.g., createPoints_xyz
    # entry  :      "x" (3-rd parameter of textEntry)
    # (Cannot use label, 2-nd param, because this is what we want change)
    #  
    # It seems, DEZ names are not converted tolower, but EXG does...???
    
    if {[string first DEZ $group] < 0} {set group [string tolower $group]}
    set adg aie_dialog.$group
    global va_set
    if ![info exists va_set($adg)] {
	foreach w [info commands *${group}*] {
	    if {[string first $group $w] < 0} continue
	    if ![winfo exists $w] continue
	    #			if {[winfo class $w] != "Entry"} continue
	    lappend va_set($adg) $w
	}
    }
    if ![info exists va_set($adg)] {return "1"}
    set elen [string length $entry]
    foreach w $va_set($adg) {
	set k [expr [string length $w] -4]
	if {[string range $w $k end] != "text"} continue
	if ![winfo exists $w] continue
	set conf [$w configure -textvar]
	set from [expr [string length $conf] - $elen]
	if {[string range $conf $from end] != $entry} continue
	set lab [string replace $w $k end label]
	if ![winfo exists $lab] continue
	$lab configure -text $newlabel
	return $newlabel
    }
}
#-------------------------------------------
proc aie_on_change_LCS {which names labs args} {
    set v ${which}::LCS
    set id [lindex [split $which :] end]
    if ![info exists $v] return
    set cs [set $v]
    set cstype [string range [ic_csystem_get $cs] 0 2] 
    if ![llength $cstype] {
	set cstype car
    }
    switch -- $cstype {
	car {set newlab(X) X; set newlab(Y) Y;     set newlab(Z) Z}
	cyl {set newlab(X) R; set newlab(Y) Theta; set newlab(Z) Z}
	sph {set newlab(X) R; set newlab(Y) Theta; set newlab(Z) Phi}
	default { error "unknown coord system type $cstype" }
    }
    foreach name $names lab $labs {
	set last [string index $lab end]
	if ![info exists newlab($last)] continue
	set lab [string replace $lab end end $newlab($last)]		 
	aie_try_change_entry_label $id $name $lab
    }
}
#--------------------------------------------
proc aie_set_faceted {faceted type list} {
    # This proc return faceted (if $faceted) or NURB curves or surfaces
    # For faceted it also set tag  "geo_select_segment"
    set subset ""
    if {$faceted != "1"} {set faceted 0}
    ic_geo_set_tag clear "" geo_select_segment all
    foreach ent $list {
	set sel_type [lindex [ic_geo_get_entity_types $ent] 0]
	if {$type != $sel_type} continue
	if {[ic_geo_check_objects_exist $type $ent] == ""} continue
	set obj_type [ic_geo_get_object_type $type $ent]
	if {$obj_type == "mesh"} {
	    if !$faceted continue
	    lappend subset $ent
	    ic_geo_set_tag $type $ent geo_select_segment 1				
	} else {
	    if $faceted continue
	    lappend subset $ent			
	}
    }
    return $subset
}
proc aie_select_move_geo_nodes {type incr} {
    # Note: cannot use for many nodes
    # select_move_geo_nodes surface $srf $nodes none ""
    # because may ask questions for each node; GUI embedded
    # Next is a way around:
    
    if {[lsearch "surface curve" $type] < 0} {return ErrType} 
    set ename [geo_select $type 1]
    if {[llength $ename] > 1} {
        ic_mess "You selected more than one $type. Only one is allowed.\n" red
	return
    }    
    set ename [aie_set_faceted 1 $type $ename]
    if ![llength $ename] {
	ic_mess "Select faceted $type" red
	return
    }
    set nodes [geo_select_segments $type $ename node 0 0]
    if ![llength $nodes] {return ErrNodes}
    # May be multiply selections of the same node. To prevent extra motion use array.
    if [info exists n_loc] {unset n_loc}
    foreach n $nodes {
	set n_loc($n) [ic_geo_get_node $type $ename $n]
    }
    if ![va_is_triplet $incr] {
	ic_mess "Set increment" red
	return ErrIncr
    }
    foreach n [array names n_loc] {
	set newxyz [ic_vcalc sum $n_loc($n) $incr]
	ic_geo_move_node $type $ename $n $newxyz
    }
}

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

proc aie_blank_geometry {what} {
    while 1 {
	set geo [geo_select $what 0 "entities to blank"]
	if {$geo == ""} return
        ic_geo_temporary_visible $what $geo 0
    }
}

proc aie_unblank_geometry {what} {
    ic_geo_temporary_visible $what all 1
}

proc aie_restrict_geometry {what} {
    set geo [geo_select $what 0 "entities to keep visible"]
    if {$geo == ""} return
    ic_show_geo_selected $what $geo 0
    foreach g $geo { set keep($g) 1 }
    foreach g [ic_geo_get_objects $what] {
        if ![info exists keep($g)] {
            ic_geo_temporary_visible $what $g 0
        }
    }
}

proc aie_restrict_geometry_by_angle {} {
    global aie_ShowDormant curve_limit_angle
    
    if [info exists curve_limit_angle] {
        set angle [question "Sharp Curves\nlimit angle?" $curve_limit_angle]
    } else {
        set angle [question "Sharp Curves\nlimit angle?" 90.0]
    }
    if {(![string is integer -strict $angle] && ![string is double -strict $angle])} {
        mess "Invalid angle: \"$angle\"" red
        return
    }
    set curve_limit_angle $angle
    set geo [ic_geo_find_ngh_curves_angle_limit $angle $aie_ShowDormant(curve)]
    set num [lindex $geo 0]
    if {$num == "0"} {
        mess "No curves found with a sharp angle < $angle\n"
        return
    }
    set geo [lrange $geo 1 end]
    regsub -all "{" $geo "" geo
    regsub -all "}" $geo "" geo
    catch { array unset keep; unset show }
    foreach "g1 g2 a p" $geo {
        if ![info exists keep($g1)] { set keep($g1) 1; append show "$g1 " }
        if ![info exists keep($g2)] { set keep($g2) 1; append show "$g2 " }
    }
    mess "Showing [llength $show] curves with a sharp angle < $angle\n"
    ic_show_geo_selected curve [list $show] 0
    foreach g [ic_geo_get_objects curve] {
        if ![info exists keep($g)] {
            ic_geo_temporary_visible curve $g 0
        } else {
            ic_geo_temporary_visible curve $g 1
        }
    }
}

# If what is curve, shows surfaces, and vice versa
# Dormant entities visibility rule: show if "which" Dormant type is visible

# Note: "ic_geo_boundary" - return "list of lists"; "ic_geo_incident" return "list"
#  
proc aie_show_attached_geometry {what {which "incident"}} {
    global aie_ShowDormant vam_events
    # force do not use preselect: ic_highlight with temporary visibility
    set was_preselection $vam_events(do_onMotion)
    set vam_events(do_onMotion) 0     
    while 1 {
	set geo [geo_select $what 0 "${what}(s) to unblank attached ${which}(s)"]
	if {$geo == ""} return
	ic_show_geo_selected $what $geo 0
	switch -- $what {
	    surface {
	        if {$which == "curve"} {
				set crvs [join [ic_geo_boundary surface $geo 0 $aie_ShowDormant(curve) 1]]	
				ic_geo_temporary_visible curve $crvs 1 1
		} else {
		   foreach srf $geo {
					set pnts [ic_geo_surface_get_objects $srf]
					ic_geo_temporary_visible point $pnts 1 1
				}	
				set crvs [join [ic_geo_boundary surface $geo 0 1 1]]					
				set pnts [join [ic_geo_boundary curve $crvs 0 $aie_ShowDormant(point) 1]]
				ic_geo_temporary_visible point $pnts 1 1
		}
	    }
	    curve {
		switch $which {
		    incident {
		        set srfs [ic_geo_incident curve $geo $aie_ShowDormant(curve)]
		        ic_geo_temporary_visible surface $srfs 1 1
		    }
		    boundary {
				set pnts [join [ic_geo_boundary curve $geo 0 $aie_ShowDormant(point) 0]]
				ic_geo_temporary_visible point $pnts 1 1
		    }
		}
	    }
	    point {
		if {$which == "curve"} {
			set crvs [ic_geo_incident point $geo $aie_ShowDormant(point)]
		    ic_geo_temporary_visible curve $crvs 1 1
		} else {
			#embedded points: must create C function to make it faster
		    foreach srf [ic_geo_get_objects surface] {
		        foreach point [ic_geo_surface_get_objects $srf] {
		            if {[lsearch $geo $point] >= 0} {
		                ic_geo_temporary_visible surface $srf 1 1
		            }
		        }
		    }
		    set crvs [ic_geo_incident point $geo 1]
		    set srfs [ic_geo_incident curve $crvs] 
		    ic_geo_temporary_visible surface $srfs 1 1		    
		}
	}
    }
    }
    set vam_events(do_onMotion) $was_preselection
}

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

proc aie_va_dynamic {what how} {
    global va_set
    set va_set(do_when_create_xyz_start) va_auto_name

    if {$what == "isocurve"} {
	if ![info exists va_set(selected)] return
	set srf $va_set(selected)
	if ![llength [ic_geo_check_objects_exist surface $srf]] return
	if {$how == "edge"} {
	    set va_set(do_when_create_xyz_continue) {
		{va_do_create_edge_isocurve $va_set(xyz_xyz)}
		{ic_highlight color "" names $va_set(name)}
		{ic_geo_set_tag surface $va_set(selected) geo_select_segment 1}
	    }
	    set va_set(do_when_create_xyz_end) {
		{va_do_create_edge_isocurve $va_set(xyz_xyz)}
		{ic_highlight color "" names $va_set(name)}
	    }
	}
    }				
}

proc va_do_create_2pts_isocurve {pts srf {set_name ""}} {
    global va_set
    if {$set_name != ""} {
		set va_set(name) $set_name
		va_auto_name curve
	}
	if {[ic_geo_check_objects_exist surface $srf] == ""} {return 1}
    if {[llength $pts] != 2} {return 2} 
    set uv0 [ic_geo_find_nearest_srf_pnt $srf [lindex $pts 0]]
    set uv1 [ic_geo_find_nearest_srf_pnt $srf [lindex $pts 1]]
    set du [expr abs([lindex $uv0 0] - [lindex $uv1 0])]
    set dv [expr abs([lindex $uv0 1] - [lindex $uv1 1])]
    if {$du > $dv} {
	set dir 1
	set par [lindex $uv0 1]
    } else {
	set dir 0
	set par [lindex $uv0 0]
    }	 
    set ecode [catch {ic_geo_cre_crv_iso_crv $va_set(fam) $va_set(name) $srf $par $dir 0 1} res]
    if !$ecode {
	busy reset
	ic_highlight color "" names $res
	return $va_set(name)
    }
} 

proc va_do_create_edge_isocurve {pnt {srf ""} {set_name ""}} {
    global va_set
    if ![llength $srf] {
		if ![info exists va_set(selected)] return
    set srf $va_set(selected)
	}
	if {[ic_geo_check_objects_exist surface $srf] == ""} return
    if {$set_name != ""} {
		va_auto_name curve $set_name
	}
	if {[llength $pnt] == 1} {set pnt [lindex $pnt 0]}
    set pntParList [ic_geo_find_nearest_srf_pnt $srf $pnt]
    set  par [lindex $pntParList 0]
    set dir 0
    set vpar [lindex $pntParList 1]
    if {[expr abs(0.5-$vpar)] < [expr abs(0.5-$par)]} {
	set par $vpar
	set dir 1
    }
    ic_delete_geometry curve names $va_set(name) 0
    set ecode [catch {ic_geo_cre_crv_iso_crv $va_set(fam) $va_set(name) $srf $par $dir 0 1} res] 
    if !$ecode {
	busy reset
	return $va_set(name)
    }
    return ""
}
proc aie_get_scale {} {
    # Return 0.1 of bbox diagonal or 1 to use for geometry scale
    global tdv_default
    set ab [$tdv_default bbox interesting]
    if {$ab == ""} { return 1 }
    set d [ic_vcalc distance [lindex $ab 0] [lindex $ab 1]]
    if {$d == ""} {return 1}
    set d [expr 0.1*$d]
    if {$d < 1} {return 1}
    return [string trim [va_round $d 3]]
}
proc aie_3_pts_on_line {pts} {
	set v1 [ic_vcalc diff [lindex $pts 1] [lindex $pts 0]]
	set v2 [ic_vcalc diff [lindex $pts 1] [lindex $pts 2]]
	set len [ic_vcalc len [ic_vcalc product $v1 $v2]]
	if {($len == "") || ($len < 0.001)} {return 1}
	return 0
}
proc aie_geo_modify_movenode {what proj_to args} {
    
    global geo_modify
    global tdv_default
    set arg0 [lindex $args 0]
    if {$proj_to == "loc"} {
	# This one is different.  Move nodes from all surfaces to a selected
	# location.
	set pt $arg0
	if ![va_is_triplet $pt] {
	    mess "Select location!\n"
	    return
	}
	set im [tdv_point_im -point $pt -size 3 -color white]
	$tdv_default add_image $im
	set nodes [geo_select_segments all_${what}s "" node 0 0 0 0]
	foreach nn $nodes {
	    if 0 {
		set obj [lindex $nn 0]
		set name [object_name_of_image $obj]
	    } else {
		set name [lindex $nn 0]
	    }
	    ic_geo_highlight_segments $what $name remove node all
	    ic_geo_move_node $what $name [lindex $nn 1] $pt
	    ic_geo_finish_edit $what $name
	}
	$im delete
	return
    }  
    switch -- $proj_to {
	plane {
	    if ![va_is_triplet $arg0] {
		mess "Select vector to define normal plane\n" red
		return
	    }
	    eval lappend proj_to $arg0
	}
	line {
	    if {[llength $arg0] != 2} {
		mess "Select two points\n" red
		return
	    }
	    set p1 [lindex $arg0 0]
	    set p2 [lindex $arg0 1]
	    set im [tdv_line_im -point1 $p1 -point2 $p2 -width 1 -color white]
	    $tdv_default add_image $im
	    
	    append proj_to " " $p1 " " $p2  
	}
	surface {
	    if {[ic_geo_check_objects_exist surface $arg0] == ""} {
		mess "Select constraint surface\n" red
		return
	    }
	    lappend proj_to $arg0
	}
    }
    set surf [geo_select $what 1 "" 0 1]
    if {$surf == ""} return
    if {[llength $surf] > 1} {
        mess "You selected more than one $what. Only one is allowed.\n" red
        aie_reset_geo_selected
        return
    }
    geo_show_edit $what $surf 0 
    ic_highlight names $surf color "" 
    select_geometry_bindings node 0
    while 1 {
	set pts [geo_select_segments $what $surf node 1 0 0 0 1]
	if {[lindex $pts 0] == ""} break
	select_move_geo_nodes $what $surf [lindex $pts 0] \
	    $proj_to [lindex $pts 1] 1
	ic_geo_highlight_segments $what $surf remove nodes all
    }
    select_geometry_bindings ""
    ic_highlight
    ic_geo_finish_edit $what $surf
#    geo_show_edit $what $surf 0
    if [info exists im] {catch "eval $im delete"} 
}


#=======================================
proc aie_delete_exterior_surfaces {fam} {
# After build_topo!
	set crvs [ic_geo_get_objects curve $fam]
	if ![llength $crvs] {return ""}
	set srfs [ic_geo_get_objects surface $fam]
	if {[llength $srfs] <= 1} {return ""}
	foreach srf $srfs {set mark_delete($srf) 0}
	foreach crv $crvs {
		set ss [ic_geo_incident curve $crv]
		if {[llength $ss] == 1} {
			set mark_delete($ss) 1
		}
	}
	foreach srf $srfs {
		if $mark_delete($srf) {
			ic_delete_geometry surface names $srf 0
			unset mark_delete($srf)
		}
	}
	ic_delete_geometry curve names $crvs 0
	return [array names mark_delete]
} 
#==========================================
proc aie_close_crvs_on_plane {fam} {
	global va_set
	set crvs ""
	set dirty_crvs [ic_geo_objects_in_family curve $fam]
va_debug 1 "dirty_crvs=$dirty_crvs" 
# In some cases above function returns old deleted curves!
	foreach name $dirty_crvs {
		if [llength [ic_geo_check_objects_exist curve $name]] {
			lappend crvs $name
		}
	}
# This function must fix curves to create closed loop on the surface
# Because curves are not boundaries, we cannot use topology, incident,etc.
	set index 0
	foreach crv $crvs {
		foreach v {0 1} {
			set xyz [lindex [ic_geo_get_crv_pos $v $crv] 0]	
			foreach i [array names p_arr] {
				set dist [ic_vcalc distance $p_arr($i) $xyz]
				if {$dist < 0.01} {
					va_debug 1 "Deleted $i"					
					unset p_arr($i)
					unset xyz
					break
				}
			}
			if [info exists xyz] {
				set p_arr($index) $xyz
			}
			incr index 
		}
	}
	set ends  [lsort -integer [array names p_arr]]
	set nends [llength $ends]
va_debug 1 "Found nends=$nends"
	if !$nends {return $crvs}
#--------------	
# which curves have not-connected ends does not matter
# For now consider simplest cases 2 or 4 ends
# Case: 2 not connected ends of one or more curves
# Case: 4 -> 2 curves
# 5.1 If more than 4 ends try use 4 ends; it may be not correct...
#
	if {$nends > 4} {
	va_debug 1 "Too many intersections. Result may be wrong"
		set nends 4
	}	
	set p0 $p_arr([lindex $ends 0])
	set p1 $p_arr([lindex $ends 1])
	case $nends {
		default {return ""}
		2 { 
			lappend crvs [ic_geo_cre_bsp_crv_n_pnts $fam tmp_00_1 [list $p0 $p1]]
			return $crvs
			}
		4 { 
			set p2 $p_arr([lindex $ends 2])
			set p3 $p_arr([lindex $ends 3])
		# must be 2 curves?
		# Connect pair with min distance
			set mindist 1e8
			foreach {pp0 pp1} {p0 p2 p0 p3 p1 p2 p1 p3} {
				set dist [ic_vcalc distance [set $pp0] [set $pp1]]
				if {$dist < $mindist} {
					set mindist $dist
					set minpp0 $pp0
					set minpp1 $pp1
				}
			}
		# Find another pair excluding $minpp0 & $minpp1
		set pair2 "p0 p1 p2 p3"
		set i [lsearch $pair2 $minpp0]
		set pair2 [lreplace $pair2 $i $i]
		set i [lsearch $pair2 $minpp1]
		set pair2 [lreplace $pair2 $i $i]
		set pp0 [set $minpp0]
		set pp1 [set $minpp1]
		set pp2 [set [lindex $pair2 0]]
		set pp3 [set [lindex $pair2 1]]

			if {[ic_vcalc distance $pp0 $pp1] > 0.001} {
				lappend all_crvs [ic_geo_cre_bsp_crv_n_pnts $fam tmp_00_2 [list $pp0 $pp1]]
			}
			if {[ic_vcalc distance $pp2 $pp3] > 0.001} {
				lappend all_crvs [ic_geo_cre_bsp_crv_n_pnts $fam tmp_00_3 [list $pp2 $pp3]]
			}
		} $fam $name $newlist 0.001
	}
	return $crvs
}
#---------------------------------------------------------
proc aie_cre_pnt_norm_plane {fam name pnt vec side {circle 0} {crv_only 0}} {
	global va_set

	if !$circle {
		set rad      [expr sqrt(2.0*$side*$side)/2.0]
	} else {
		set rad $side
	}
	set x_dir    [ic_vcalc vec_norm $vec]
	set x_dir    [ic_vcalc smult [ic_vcalc nrm $x_dir] $rad]
	set p1 [ic_vcalc sum $x_dir $pnt]

# For circle it's enough
	if $circle {
#		ic_delete_geometry curve names tmpc1 0		
		set tmp_crv [ic_geo_cre_crv_arc_ctr_rad $fam tmpc1 $pnt $x_dir $vec $rad 0 360]
		if !$crv_only {		
			set surf_name [ic_geo_create_surface_from_curves $fam $name $::geo_cad(toler) $tmp_crv 1]
			set va_set(srfplane) $surf_name
#		ic_delete_geometry curve names tmpc1 0
		}
		return
	}
# For plane we use 3 more points 

	set y_dir    [ic_vcalc product $vec $x_dir]
	set y_dir    [ic_vcalc smult [ic_vcalc nrm $y_dir] $rad]

	set p2 [ic_vcalc sum $y_dir $pnt]
	set p3 [ic_vcalc diff $x_dir $pnt]
	set p4 [ic_vcalc diff $y_dir $pnt]

	set surf_name [ic_surface 4pts $fam $name [list $p1 $p2 $p3 $p4]]
	set va_set(srfplane) $surf_name
}
#=======
proc aie_get_locations_on_crv {crv end num incr} {
# if incr is too big, use uniform set of params along curve
	set incr [expr abs($incr)]
	if {[expr $num*$incr] > 1} {
		set incr [expr 1.0/$num]
	}  
	if {$end != 0} {
		set end 1
		set incr [expr -$incr]
	}
	for {set i 0} {$i < $num} {incr i} {
		lappend res [lindex [ic_geo_get_crv_pos $end $crv] 0]
		set end [expr $end + ($incr)]
	}
	return $res
}
proc aie_get_3pnt_center {p1 p2 p3} {
# TEMPORARY body: uses old virtual commands.
# Body will be replaced for 5.2
	set angle [ic_vcalc angle $p1 $p2 $p3]
	if {$angle == 0 || $angle == 180} {return ""}
	ic_virtual define point _V1 $p1 1
	ic_virtual define point _V2 $p2 1
	ic_virtual define point _V3 $p3 1
	ic_virtual define point _V "_V1 _V2 _V3 radius 0 angle 0 offset 0" 1
	if ![ic_virtual check point _V 1] {
		return [lindex [ic_virtual] 0]
	}
	return ""
}
proc aie_get_3pnt_arc_pnt {c p1 p2 pcheck} {
	set mid [ic_vcalc sum_smult $p1 $p2 0.5]
	set rad [ic_vcalc distance $c $p1]
	set dir [ic_vcalc dir $c $mid]
	set a   [ic_vcalc angle $c $mid $p1]
	set ac  [ic_vcalc angle $c $mid $pcheck]
	if {$a > $ac} {set dir [ic_vcalc smult $dir -1]}
	set add [ic_vcalc smult $dir $rad]
	return  [ic_vcalc sum $c $add]
}
proc aie_get_csystem_direction {which} {
#
# return normalized direction (X or Y or Z)
# if not cartesian -> return direction for global
#
	set i [lsearch "X Y Z" $which]
	if {$i < 0} {return "1 0 0"}
	set csys_name [ic_csystem_get_current]
	set csys [ic_csystem_get $csys_name]
	set csys_type [lindex $csys 0]
	if {$csys_type != "cartesian"} {
		return [lindex "{1 0 0} {0 1 0} {0 0 1}" $i]
	}
	incr i 2
	set dir [lindex $csys $i]
	return [ic_vcalc nrm $dir]
} 
#===================================
proc aie_project_crvs_and_trim_srfs {fam crvs_list srfs_list {entname ""} {do_projection 1}} {	
    # always do projection or build_topo may delete existing curves
    global vid_options

    set build_topo 0
    if {[info exists vid_options(new_srf_topo)] && $vid_options(new_srf_topo)} {
        set build_topo 1
    }
    foreach var "newcrvlist newseg newpar crvs srfs param_srfs mesh_srfs" {
        set $var ""
    }
    foreach cc $crvs_list {
        if [llength [ic_geo_check_objects_exist curve $cc]] {lappend crvs $cc}
    }
    foreach cc $srfs_list {
        if [llength [ic_geo_check_objects_exist surface $cc]] {lappend srfs $cc}
    }
    foreach s $srfs {
        switch [ic_geo_get_object_type surface $s] {
            "mesh"  {lappend mesh_srfs  $s}
            "param" {lappend param_srfs $s}
        }
    }
    if {($crvs == "") || ($srfs == "")} return 
    if {$mesh_srfs != ""} {
        foreach srf $mesh_srfs {
            set newcrvlist [ic_geo_project_curve_to_surface $crvs $srf tmp00 $fam 0 0]
            if {$newcrvlist == ""} continue
            set newseg [ic_geo_create_surface_segment $srf curve angle 0 mintri 0 \
                plane_p {0 0 0} plane_n {0 0 1} keep_old 0 curves $newcrvlist]
            if {$build_topo && [llength $newseg]} {
                ic_build_topo $::geo_cad(toler) -surfaces $newseg -curves $newcrvlist
            } else {
                ic_delete_geometry curve names $newcrvlist 0
            }
        }
    }
    if {$param_srfs != ""} {	
        foreach srf $param_srfs {	
            set newcrvlist [ic_geo_project_curve_to_surface $crvs $srf tmp00 $fam 0 0]	
            if {$newcrvlist == ""} continue
            lappend newpar [ic_geo_trim_surface $srf $newcrvlist $build_topo]
            if !$build_topo {
                ic_delete_geometry curve names $newcrvlist 0
            }
        }
    }
    return "$newpar $newseg"
}

proc aie_update_curve_color_if_on {} {
    if ![ic_hex_blocking_loaded] {
    # update curve color if "On"
        set cvar ::aie_CurveColorByCount
        set ccom ::AIEnv::GUIManagement::Tree::CurveColorByCount
        if [set $cvar] {
            set $cvar 0
            $ccom
            set $cvar 1
            $ccom
        }
    }
    # end update curve color
}

proc ontransfmoveSurfesPickFinish {} {
    if [info exists LongList] {
        set thelist $LongList
    } else {
        set thelist $surfaceList
    }
    if {$thelist != ""} {
        set data ""
	    set arr_list tmp_arr
	    foreach type $entities {
	        lappend arr_list tmp_$type
	    } 
	    foreach arr $arr_list {
	        if [info exists $arr] { unset $arr }
	    }
	    foreach {type name} $thelist {
            if {[lsearch $entities $type] < 0} continue
	        lappend data "$type $name" 
	        set fam [ic_geo_get_family $type $name]
	        set tmp_arr($fam) 1
	        set tmp_${type}($name) 1
	    }
	    set bbox [ic_geo_bbox_of_entities $data]
	    set preselected_parts [array names tmp_arr]
	    set transfrParts ""
	    if {[expr [llength $thelist] / 2] != [llength [ic_geo_get_objects "surface curve point body density"]]} {
	        set detachFlag 0
	    }
    }
}

proc aie_perCopyAngleRot {var args} {
    set dez $::AIEnv::GUIManagement::ActiveDEZ
    if {$dez != "transformSurfsToolsDEZ"} return
    if {[transformSurfsToolsDEZ get transfrmSurfsEGVal] != "1"} return
    if ![transformSurfsToolsDEZ get copyRotateGGVal] return
    set n [transformSurfsToolsDEZ get numCopies]
    set angle [expr 360.0/($n+1)]
    transformSurfsToolsDEZ set rot_angle $angle
}

proc aie_check_names_get_ext {ext type list} {
	set was $ext
	set exists 1
	set add 0
	while $exists {
		foreach {type name} $list {
			if {[ic_geo_check_objects_exist $type ${name}$ext] != ""} {
				set ext _${add}$ext
				break
			}
		}
		if {$was != $ext} {
#			ic_mess "Using new items extension $ext instead of $was\n"
		}  
		return $ext
	}
}

proc aie_set_part_and_new_names {type list part entname} {
# Usage: if several new entities were created with "wrong" names, fam 
	if ![llength $list] return 
	set nnames ""   
	foreach nm $list {
		set n [va_auto_name $type $entname]
		lappend nnames [ic_geo_set_name $type $nm $n]
	}
    if {$part != ""} {
		ic_geo_set_family $type $part names $nnames 0
	}
	return $nnames
}

proc aie_preview_cr_corner_curve {} {
    global va_set
#    set curve_name $va_set(curve_name)
#    set n_slice $va_set(n_slice)
#    set width $va_set(width)
    set curve_name [createFacetedDEZ get ref_curve]
    set surf_name [createFacetedDEZ get ref_surf]
    set n_slice [createFacetedDEZ get n_slice]
    set width [createFacetedDEZ get width]
#    set poly [createFacetedDEZ get SplineFlag]
#    set fillet [createFacetedDEZ get FilletFlag]
    set fillet 0
#    set tolerance [createFacetedDEZ get tolerance]
    set ret [ic_preview_cr_corner_curve $curve_name $n_slice $width "" $surf_name $fillet]
    set va_set(spline_list) [lindex $ret 0]
    set va_set(hard_spline) [lindex $ret 1]
    set va_set(surf_curvelist1) [lindex $ret 2]
    set va_set(surf_curvelist2) [lindex $ret 3]
    foreach i [list curve_name surf_name n_slice width fillet] {
	set va_set($i) [subst $[subst $i]]
    }
    #Update Display
    if [llength [info command aie_refresh_screen]] aie_refresh_screen
#    ic_highlight names $va_set(hard_spline) width 3 color red
    ic_highlight names [concat [lreplace $va_set(surf_curvelist1) 0 0 ] [lreplace $va_set(surf_curvelist2) 0 0]] width 3 color yellow
    ic_highlight add $va_set(spline_list) width 5 color red
}


#This is copied from Mesh Prototyper stuff.......................................................
#This used to be va_cr_corner_curve
#width supports multiple values
#width2 is optional and provides a second width for second endpoint
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
proc ic_preview_cr_corner_curve {curve_name n_slice width {width2 ""} \
	{surf_name ""} {fillet 0} {tolerance 0.001} {poly 0} {debug 0}} {
    global geom_visible

    if {$n_slice == 0} return
    if {$width2 == ""} {set width2 $width}
    if {[ic_geo_check_objects_exist curve $curve_name] == ""} return
    if {[ic_geo_check_objects_exist surface $surf_name] == ""} return

    global tdv_active
    tdv_active 0
    busy 1

#First step is to clear out any original stuff so that if somebody is updating the preview it works...
    ic_delete_geometry all families MPCHAR 1 1
    ic_delete_geometry all families MPTPTS 1 1
    ic_delete_geometry all families MPGUIDE 1 1
#Should be clean at this point.


#This I think is for endpoint handling.  Need to readd later -->Ben
if 0 {
   if {$va_set(pt_name) != ""} {
	if {$va_set(usepts_1st) != ""} {
	    if {$va_set(usepts_1st) == [lindex $va_set(pt_name) 0]} {
		set va_set(pt_name) [lreplace $va_set(pt_name) 0 0]
	    }
	    set va_set(usepts_1st) ""  
	}
	if {$va_set(usepts_end) != ""} {
	    set index [expr [llength $va_set(pt_name)]-1]
	    if {$va_set(usepts_end) == [lindex $va_set(pt_name) $index]} {
		set va_set(pt_name) [lreplace $va_set(pt_name) $index $index]
 	    }
	    set va_set(usepts_end) ""  
	}   
	va_del_pt $va_set(pt_name)
	set va_set(pt_name) ""
     }

    set w_l1 [lsort -decreasing -real $width]
    if {$width2 != ""} {
	set w_l2 [lsort -decreasing -real $width2]
	if {[lindex $w_l1 0] < [lindex $w_l2 0]} {
	    set w_l1 [lsort -decreasing -real $width2]
	    set w_l2 [lsort -decreasing -real $width] 
	}
	 if {$w_l1 == $w_l2 || $w_l2 == 0} {
	    set w_l2 ""
	}
    } else {
	set w_l2 ""
    }
    if {$w_l2 != ""} {
	set g_p ""
	for {set i 1} {$i < 100} {incr i} {
#I think this is supposed to provide some user control to define the short side, but not sure.
	    set g_p [lindex [va_select_points 1 "shorter side" "" 1] 0]
	    if {[llength $g_p] != "0"} break
	}
	set par [ic_geo_find_nearest_crv_pnt $curve_name $g_p ]
	set pnt [ic_geo_cre_pnt_on_crv_at_par MPTEMP "" $par $curve_name]
	set loc [ic_geo_get_point_location $pnt]
	ic_delete_geometry point names $pnt 0
#	set diff [val_vector_sub $g_p $loc]
	set diff [ic_vcalc diff $loc $g_p]
    } else {
	set diff ""
    }
} ; #######################
    set w_l1 [lsort -decreasing -real $width]
    set w_l2 ""
    set diff ""
    set steps 0
#    set flip 0
    set usepts_1st ""
    set usepts_end ""
    for {set i 1} {$i <= $n_slice} {incr i} {
	set check 0
	if {$i == "1" && $usepts_1st != ""} {
	    set check 1
 	}
	if {$i == $n_slice && $usepts_end != ""} {
	    set check 2
 	}
	set n_step [expr $steps+.001]   
	if {$n_step >= 1} {
	    set steps 0.999
	    set n_step 1.0
	}
	if {$check == 0} {
	    set p [ic_geo_cre_pnt_on_crv_at_par MPTPTS s_point $steps $curve_name]
	    set n [ic_geo_cre_pnt_on_crv_at_par MPTPTS s_point $n_step $curve_name]
	    if {$p != ""} {
		set cor_p [ic_geo_get_point_location $p]
	    } else {
		return
	    }
	    if {$n != ""} {
		set cor_n [ic_geo_get_point_location $n]
	    } else {
		return 
	    }
	    ic_delete_geometry point names "$p $n" 0

	    set ret [aie_cr_corner_point $cor_p $cor_n 0 $w_l1 $w_l2 $diff $surf_name $debug]
	    lappend spline_list [lindex $ret 0]
	    lappend start_list [lindex $ret 1]
	    lappend end_list [lindex $ret 2]
	}
       
	if {$check == 1} {
	    set pt_name $usepts_1st
	} elseif {$check == 2} {
	    lappend pt_name $usepts_end
	}
	set steps [expr (1.0/($n_slice-1.0))+$steps]
     }
#    mess "running aie_mp_final_spline $curve_name 1\n"
    set ret [aie_mp_final_spline $curve_name $spline_list $start_list $end_list $fillet $debug]
#return list is [list $bsp_main $bsp_sta $bsp_end $bsp_s1_sta $bsp_s1_end $bsp_s2_sta  $bsp_s2_end]
    set hard_spline [lindex $ret 0]
    set surf1_bound [list $hard_spline [lindex $ret 3] [lindex $ret 1] [lindex $ret 4]]
    set surf2_bound [list $hard_spline [lindex $ret 5] [lindex $ret 2] [lindex $ret 6]]

    tdv_active 1
    busy reset
    return [list $spline_list $hard_spline $surf1_bound $surf2_bound]
#-----
}

#This is copied from Mesh Prototyper stuff.......................................................
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
proc aie_cr_corner_point {p1 p2 add w_l1 w_l2 diff {surf_name ""} {debug 0}} {
#global va_set

#   ic_visible geometry point 0

#For 2 widths we need to take the sta_dir and end_dir into account as 1 is 1 width and the other is other width.
#  We should then create curves on one side of different width than other side.
#Should probably take the bigger side and create the circle and then build everything off that.

    if {$w_l1 == $w_l2} {set width $w_l1} else {
	#Need to improve this
	set width $w_l1
    }
    set l_width [llength $width]
    set rad [lindex $width 0]
    if {$l_width == 1} {
	set rad_pt2 [expr 2*$rad/3.0]
	set rad_pt3 [expr $rad/3.0]
    }
    if {$l_width == 2} {
	set rad_pt3 [lindex $width 1]
	set rad_pt2 [expr ($rad_pt1+$rad)/2.0]
    }
    if {$l_width > 2 } {
	    set rad_pt2 [lindex $width 1]
	    set rad_pt3 [lindex $width 2]
    }
#mess "rad_pt2 is $rad_pt2\n"
#mess "rad_pt3 is $rad_pt3\n"
#mess "running aie_create_circle $p1 $p2 $rad  MPTPTS 1\n"
    set ret [aie_create_circle_section $p1 $p2 $rad $rad_pt2 $rad_pt3 MPTPTS $surf_name]
    set sta_1 [lindex $ret 0]
    set sta_2 [lindex $ret 1]
    set sta_3 [lindex $ret 2]
    set end_1 [lindex $ret 3]
    set end_2 [lindex $ret 4]
    set end_3 [lindex $ret 5]

    foreach m "sta end"  {
	set p1_nm [subst $[subst  ${m}_1]]
	set p2_nm [subst $[subst  ${m}_2]]
	set p3_nm [subst $[subst  ${m}_3]]
	if {$p1_nm == "" || $p2_nm == "" || $p3_nm == ""} {
	    if {$p1_nm != ""} {ic_delete_geometry point names $p1_nm 0}
	    if {$p2_nm != ""} {ic_delete_geometry point names $p2_nm 0}
	    if {$p3_nm != ""} {ic_delete_geometry point names $p3_nm 0}          
	    return
	}
	set p1_cor [ic_geo_get_point_location $p1_nm]
	set p2_cor [ic_geo_get_point_location $p2_nm]
	set p3_cor [ic_geo_get_point_location $p3_nm]
	if {$p1_cor != $p2_cor && $p1_cor != $p3_cor && $p2_cor != $p3_cor} {
	    set arc_$m $m
	    set vect1 [ic_vcalc dir $p1_nm $p2_nm]
	    set vect2 [ic_vcalc dir $p1_nm $p3_nm]
	    if {$vect1 == $vect2} {
		set dis [ic_vcalc distance $p3_nm $p1_nm]
		set cof [expr ($rad_3*2.0)/$dis]
		set p_ex [ic_v_calc point create "$p3_nm $p1_nm $cof"]
		set line_$m [ic_geo_cre_line MPTPTS ARC_$m $p1_cor [lindex $p_ex 0] ]
	    } else {
		set cnt  [ic_v_calc point create "$p3_nm $p2_nm $p1_nm radius 0 angle 45 offset 0"]
 		set cnt_p [ic_geo_cre_pnt MPTPTS cnter [lindex $cnt 0]]
		set radi [lindex [ic_v_calc value distance "$p3_nm $cnt_p"] 0]
		set p_ex   [ic_v_calc point create "$p3_nm $p2_nm $p1_nm radius $radi angle 120 offset 0"]
		set arc_$m [ic_geo_new_name curve ARC]
		set arc_name [subst $[subst arc_$m]]
		ic_geo_cre_arc_from_pnts MPTPTS $arc_name $p3_cor $p1_cor [lindex $p_ex 0]
		ic_delete_geometry point names $cnt_p 0
	    }
	} else { 
	    set arc_$m "" 
	}
    }

    if { $arc_sta != "" && $arc_end != ""} {
	set length 0
	foreach obj "$arc_sta $arc_end" {
	    set length [expr $length+[ic_geo_feature_size curve $obj]]
	}
	set ave_length [expr $length/2.0]
	set tol [expr $ave_length/1.0]

	set pt_int [ic_geo_create_points_curveinter \
	    "$arc_sta $arc_end" $tol MPCHAR MPCHAR]
    } else {
	set pt_int ""
    }
    if !$debug {
	ic_delete_geometry curve families MPTPTS
    }
    #returns list of intersection point for spline followed by list of start_points and end_points
    return [list $pt_int [list $sta_1 $sta_2 $sta_3] [list $end_1 $end_2 $end_3]] 

}

#This is copied from Mesh Prototyper stuff.......................................................
#================================================= 
proc aie_create_circle_section {p1 p2 r r2 r3 fam int_srf} {
#global va_set pi
    global pi
    set z [ic_vcalc nrm [ic_vcalc dir $p1 $p2]]
    set xt [ic_vcalc mult $z "1 0 0"]
    if {[ic_vcalc len $xt] < 0.3} { 
	set xt [ic_vcalc mult $z "0 1 0"]
	set flip 1
    } else {set flip 0}
    
    
    set x [ic_vcalc nrm $xt]
    set y [ic_vcalc mult $z $x]
    for {set i 0} {$i < 8} {incr i} {
	set angle [expr $pi/4.0*$i]
	set xp [expr $r*sin($angle)]
	set yp [expr $r*cos($angle)]
#    set p_$i [val_transform_cs_back $x $y $z $p1 "$xp $yp 0"]
	set p_$i [ic_vcalc sum [aie_mult_matrixes [aie_transp_matrix [list $x $y $z]] "$xp $yp 0" ]  $p1]
#    ic_geo_cre_pnt $fam $fam/p$i $p
    }
    if !$flip {
	ic_geo_cre_arc_from_pnts $fam $fam/c1 $p_0 $p_1 $p_2
	ic_geo_cre_arc_from_pnts $fam $fam/c2 $p_2 $p_3 $p_4
	ic_geo_cre_arc_from_pnts $fam $fam/c3 $p_4 $p_5 $p_6
	ic_geo_cre_arc_from_pnts $fam $fam/c4 $p_6 $p_7 $p_0
    } else {
	ic_geo_cre_arc_from_pnts $fam $fam/c3 $p_0 $p_1 $p_2
	ic_geo_cre_arc_from_pnts $fam $fam/c4 $p_2 $p_3 $p_4
	ic_geo_cre_arc_from_pnts $fam $fam/c1 $p_4 $p_5 $p_6
	ic_geo_cre_arc_from_pnts $fam $fam/c2 $p_6 $p_7 $p_0
    }
    set srf [ic_geo_create_surface_from_curves $fam $fam/s1 1.0 "$fam/c1 $fam/c2 $fam/c3 $fam/c4"]

#Find sides:
    global tdv_default
    set screen_normal [lindex [$tdv_default screen2world 100 100] 1]
    set crv_normal [ic_vcalc nrm [ic_vcalc dir $p1 $p2]]
    set side_check [ic_vcalc product $screen_normal $crv_normal]
#mess "screen_normal is $screen_normal  \n"

    set circle $srf
    set curves [list $fam/c1 $fam/c2 $fam/c3 $fam/c4]
    set intr_sec [ic_geo_intersect_surfaces MPTPTS [list $circle $int_srf]]
    set extract_p [ic_geo_extract_points  $intr_sec 90]
#mess "extract_p is $extract_p\n"
    set pt_dist_list ""
    foreach p $extract_p {
	    set oloc [ic_geo_get_point_location $p]
	    set ccc [b scrib_lib_geo_nearest_curve_list $oloc $curves ]
	    set poloc [ic_geo_project_point curve $ccc $p]
	    set dist($p) [ic_vcalc distance $oloc $poloc]
#mess "oloc is $oloc ; ccc is $ccc ; poloc is $poloc ; dist is $dist\n"
	    lappend pt_dist_list [list $p $dist($p)]
    }
    set pt_dist_list [lsort -index 1 -real -increasing $pt_dist_list]
    set side1 [lindex [lindex $pt_dist_list 0] 0]
    set side2 [lindex [lindex $pt_dist_list 1] 0]
    #If points are on boundary, 1 or 2 points may not intersect in which case use a sphere.
    if {($dist($side1) > 0.1) || ($dist($side2) > 0.1) } {
	set sphere [ic_surface sphere $fam $fam [list $p1 $p_0  $r 0 180]]
	set intr_sec2 [ic_geo_intersect_surfaces MPTPTS [list $sphere $int_srf]]
	set extract_p2 [ic_geo_extract_points  $intr_sec2 90]

	set pt_dist_list2 ""
	foreach p $extract_p2 {
	    set oloc [ic_geo_get_point_location $p]
	    set ccc [b scrib_lib_geo_nearest_curve_list $oloc $curves ]
	    set poloc [ic_geo_project_point curve $ccc $p]
	    set dist($p) [ic_vcalc distance $oloc $poloc]
#mess "oloc is $oloc ; ccc is $ccc ; poloc is $poloc ; dist is $dist\n"
	    lappend pt_dist_list2 [list $p $dist($p)]
	}
	set pt_dist_list2 [lsort -index 1 -real -increasing $pt_dist_list2]
	set side1 [lindex [lindex $pt_dist_list2 0] 0]
	set side2 [lindex [lindex $pt_dist_list2 1] 0]

	foreach p [lreplace $pt_dist_list2 0 1] {
	    ic_delete_geometry point names [lindex $p 0]
	}
	ic_delete_geometry surface names $sphere
    } 

    set side1_dir [ic_vcalc dir $p1 $side1]
    set side2_dir [ic_vcalc dir $p1 $side2]

    set ang1 [ic_vcalc angle $side_check $side1_dir]
    set ang2 [ic_vcalc angle $side_check $side2_dir]

    if {$ang1 > $ang2} {
	set sta_3 $side1 ; set end_3 $side2
	set sta_dir $side1_dir ; set end_dir $side2_dir
    } else {
	set sta_3 $side2 ; set end_3 $side1
	set sta_dir $side2_dir ; set end_dir $side1_dir
    }

    foreach p [lreplace $pt_dist_list 0 1] {
	ic_delete_geometry point names [lindex $p 0]
    }

#mess "sta_3 is $sta_3 ; end_1 is $end_1 \n"
#mess "sta_dir is $sta_dir ; end_dir is $end_dir\n"

    set sta_2 [ic_point projsurf MPTPTS start \
		[list [ic_vcalc sum $p1 [ic_vcalc smult $sta_dir [expr $r / $r2]]] $int_srf]]
    set end_2 [ic_point projsurf MPTPTS end \
		[list [ic_vcalc sum $p1 [ic_vcalc smult $end_dir [expr $r / $r2]]] $int_srf]]

    set sta_1 [ic_point projsurf MPTPTS start \
		[list [ic_vcalc sum $p1 [ic_vcalc smult $sta_dir [expr $r / $r3]]] $int_srf]]
    set end_1 [ic_point projsurf MPTPTS end \
		[list [ic_vcalc sum $p1 [ic_vcalc smult $end_dir [expr $r / $r3]]] $int_srf]]
#mess "sta_3 is $sta_3 ; end_3 is $end_3\n"

    if [llength $curves] {
	    ic_delete_geometry curve names $curves 0
    }
    ic_delete_geometry curve names $intr_sec
    ic_delete_geometry surface names $circle

    return [list $sta_1 $sta_2 $sta_3 $end_1 $end_2 $end_3]
}

#This is copied from Mesh Prototyper stuff.......................................................
#This is modified to create curves from lists of spline_pts --> The center line points to create hard edge
#curve_name -> original curve that represents the approximate location of centerline.
#spline_pts -> points for spline at hard edge that will be created
#side1_list -> the list of points (3 pts) on start side
#side2_list -> the list of points (3 pts) on end side
#poly -> Whether to create a Bspline or Faceted curve
#fillet
#tolerance
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
proc aie_mp_final_spline {curve_name {spline_pts ""} {side1_pts ""} {side2_pts ""} {fillet 0} {debug 0}} {
    global geom_visible fam_visible
 
    if { [llength $spline_pts] == 0 } {
	return
    }
    if { [llength $spline_pts] < 2} {
	ic_mess "Require two or more intersection points.\n" red
	return
    }
    set spline_length [llength $spline_pts]
    set side1_length [llength $side1_pts]
    set side2_length [llength $side2_pts]
    if {($spline_length != $side1_length) || ($side1_length != $side2_length)} {
	ic_mess "Not getting proper configuration from sides\n" red
	return
    }

    set i 0
    set point_cor ""
    set point_sta ""
    set point_end ""
    while { $i < $spline_length } {
	lappend point_cor [ic_geo_get_point_location [lindex $spline_pts $i]]
	lappend point_sta [ic_geo_get_point_location [lindex [lindex $side1_pts $i] end]]
	lappend point_end [ic_geo_get_point_location [lindex [lindex $side2_pts $i] end]]
	incr i
    }
    #Create the curves that run along the length of the hard edge.
    set bsp_main [ic_curve point MPCHAR MPCHAR $point_cor ]
   
    set bsp_sta  [ic_curve point MPGUIDE s1 $point_sta]
    set bsp_end  [ic_curve point MPGUIDE s2 $point_end]

    #Create the start and end curves.
    set bsp_s1_sta [ic_curve point  MPGUIDE  MPGUIDE [list [lindex $spline_pts 0] [lindex [lindex $side1_pts 0] 0] [lindex [lindex $side1_pts 0] end]] ]
    set bsp_s2_sta [ic_curve point  MPGUIDE  MPGUIDE [list [lindex $spline_pts 0] [lindex [lindex $side2_pts 0] 0] [lindex [lindex $side2_pts 0] end]] ]
    set bsp_s1_end [ic_curve point  MPGUIDE  MPGUIDE [list [lindex $spline_pts end] [lindex [lindex $side1_pts end] 0] [lindex [lindex $side1_pts end] end]] ]
    set bsp_s2_end [ic_curve point  MPGUIDE  MPGUIDE [list [lindex $spline_pts end] [lindex [lindex $side2_pts end] 0] [lindex [lindex $side2_pts end] end]] ]

    if $fillet {
 	va_cr_fillet_all
    }
    if !$debug {
	ic_delete_geometry point families MPTPTS
    }
    return [list $bsp_main $bsp_sta $bsp_end $bsp_s1_sta $bsp_s1_end $bsp_s2_sta  $bsp_s2_end]
}

#This is copied from Mesh Prototyper stuff.......................................................
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-==-=-=-=-
proc aie_create_character_curve {curve_name surf_name part_name n_slice width {fillet 0} \
	{trim_surf 0} {remove_surf 0} {project_edge 0} {width2 ""} {tolerance 0.001} {debug 0}} {
global va_set tdv_active

    #Someone could come into this without having run the preview.
    set create_hardedge 0
    foreach i [list curve_name surf_name n_slice width fillet] {
	if {![info exists va_set($i)] || ($va_set($i) != [subst $[subst $i]] ) } { 
	    set create_hardedge 1 
	    break
	}
    }
    if $create_hardedge {
	set ret [ic_preview_cr_corner_curve $curve_name $n_slice $width "" $surf_name $fillet]
	set spline_list [lindex $ret 0]
	set hard_spline [lindex $ret 1]
	set surf_curvelist1 [lindex $ret 2]
	set surf_curvelist2 [lindex $ret 3]
    } else {
	set spline_list $va_set(spline_list)
	set hard_spline $va_set(hard_spline)
	set surf_curvelist1 $va_set(surf_curvelist1)
	set surf_curvelist2 $va_set(surf_curvelist2)
    }
  
    if {$n_slice == 0} return
    if {$width2 == ""} {set width2 $width}
    if {[ic_geo_check_objects_exist curve $curve_name] == ""} return
    if {[ic_geo_check_objects_exist surface $surf_name] == ""} return

    tdv_active 0
    busy 1

    if $fillet {
	va_cr_fillet_surfs
	busy reset
	ic_delete_geometry curve names "$va_set(bsp_main)"
	return
    }

    set side1_crvs [lreplace $surf_curvelist1 0 0]
    set side2_crvs [lreplace $surf_curvelist2 0 0]
    if $trim_surf {
	set proj_crv_side1 ""
	foreach c $side1_crvs {
		set nc [ic_geo_project_curve_to_surface $c $surf_name trim_curves $part_name]
		set ncr [ic_geo_modify_curve_reappr $nc 1 0]
		lappend proj_crv_side1 $ncr
	}
	set surf1 [ic_surface bsinterp $part_name $part_name [concat $hard_spline $proj_crv_side1]]
	set proj_crv_side2 ""
	foreach c $side2_crvs {
		set nc [ic_geo_project_curve_to_surface $c $surf_name trim_curves $part_name]
		set ncr [ic_geo_modify_curve_reappr $nc 1 0]
		lappend proj_crv_side2 $ncr
	}
	ic_geo_set_part curve $proj_crv_side1 $part_name 0
	ic_geo_set_part curve $proj_crv_side2 $part_name 0
#	ic_build_topo $::geo_cad(toler) -angle 30 -no_concat -surfaces $surf_name
#	ic_build_topo $::geo_cad(toler) -angle 30 -no_concat -surfaces $surf_name -curves [concat $proj_crv_side1 $proj_crv_side2]
    }
    catch {set surf1 [ic_geo_create_surface_from_curves $part_name $part_name $tolerance $surf_curvelist1 ]} err_1
    catch {set surf2 [ic_geo_create_surface_from_curves $part_name $part_name $tolerance $surf_curvelist2 ]} err_2
    ic_geo_set_part curve $side1_crvs $part_name 0
    ic_geo_set_part curve $side2_crvs $part_name 0
    ic_geo_set_part curve $hard_spline $part_name 0
         
    if {[llength $err_1] > 1} {set surf1 ""}
    if {[llength $err_2] > 1} {set surf2 ""}

    foreach i [list curve_name surf_name n_slice width fillet] {
	set va_set($i) ""
    }

    if !$debug {
	 ic_delete_geometry point names $spline_list
    }
    tdv_active 1
    busy 0
}

proc aie_smooth_facet_edge_align_to_curve {{type "edge"} } {
    set surf [geo_select surface 1]
    if {$surf == ""} return	
    if {[llength $surf] > 1} {
        mess "You selected more than one surface. Only one is allowed.\n" red
        return
    }	
    set crv [geo_select curve 1]
    if {$crv == ""} return
    if {[llength $crv] > 1} {
        mess "You selected more than one curve. Only one is allowed.\n" red
        return
    }
    switch $type {
	edge {
	    set surfnodes [geo_select_segments surface $surf bound_edge]
	    if {$surfnodes == ""} {
		return
	    }
	    busy 1
	    set nnodes [llength $surfnodes]

	    set i 0
	    set nodeloc ""
	    while {$i < $nnodes} {
		set value [lindex $surfnodes $i]
		lappend nodeloc [ic_geo_get_node surface $surf $value]
		incr i
	    }
					
	    ic_undo_group_begin
	    set npos ""
	    set num ""
	    foreach node $surfnodes {
		set nodeloc [ic_geo_get_node surface $surf $node]  
		set npos [ic_geo_project_point curve $crv $nodeloc]
		ic_geo_set_node surface $surf $node $npos 
	    }  
	    ic_undo_group_end
	}
	node {
	    set surfnodes [geo_select_segments surface $surf node 0]
	    if {$surfnodes == ""} {
		return
	    }
	    busy 1
	    ic_undo_group_begin
	    foreach node $surfnodes {
		set nodeloc [ic_geo_get_node surface $surf $node]
		set npos [ic_geo_project_point curve $crv $nodeloc]
		ic_geo_move_node surface $surf $node $npos
		ic_geo_finish_edit surface $surf    
	    }
	    ic_undo_group_end
	}
	default {
	    mess "aie_smooth_facet_edge_align_to_curve called with unsupported type $type\n"
	    return
	}
			
    }
#    ic_highlight names $surf color
#    ic_highlight names $crv color
    busy reset 
}

proc aie_smooth_facet_edges {{smooth_tol 1}} {
    global geom_visible
    if {$smooth_tol == ""} {set smooth_tol 1}
    set surf [geo_select surface 1]
    if {$surf == ""} return
    if {[llength $surf] > 1} {
        mess "You selected more than one surface. Only one is allowed.\n" red
        return
    }		
    set surfnodes [geo_select_segments surface $surf bound_edge]  
    if {$surfnodes == ""} return
    busy 1
    set surfnodes [aie_smooth_order_surface_nodes $surfnodes]
    if {$surfnodes == "" } {
	ic_mess "Invalid surface segment selection.\n" red
	busy reset
	return
    }
    # create list of nodes locations for surface nodes
    set nnodes [llength $surfnodes]
    set i 0
    set nodeloc ""
    while {$i < $nnodes} {
	set value [lindex $surfnodes $i]
	lappend nodeloc [ic_geo_get_node surface $surf $value]
	incr i
    }
    # Create smoother curve
    set fam "MPEDGE"
    if {$nnodes <  1} {
        set crv_nm ""
    }
     if {$nnodes == 2} {
	set crv_nm [ic_geo_cre_line $fam ${fam}// [lindex $nodeloc 0] [lindex $nodeloc 1]]
	ic_highlight width 3 names $crv_nm
    }
    if {$nnodes == 3} {
	set crv_nm [ic_geo_cre_arc_from_pnts $fam ${fam}// [lindex $nodeloc 0] [lindex $nodeloc 1] [lindex $nodeloc 2]]
	ic_highlight width 3 names $crv_nm
    }
    if {$nnodes >  3} {
	set crv_nm [ic_geo_cre_bsp_crv_n_pnts $fam ${fam}// $nodeloc $smooth_tol]
	ic_highlight width 3 names $crv_nm
    }

    if {$geom_visible(curve) == 0} {
	set geom_visible(curve) 1
	update_geom_visible curve v
    }   
    set i 0
    set nodeloc ""
    set pntname ""
    while {$i < $nnodes} {
	set value [lindex $surfnodes $i]
	lappend nodeloc [ic_geo_get_node surface $surf $value]
	incr i
    } 
    ic_undo_group_begin
    set npos ""
    set num ""
    foreach node $surfnodes {
	set nodeloc [ic_geo_get_node surface $surf $node]  
	set npos [ic_geo_project_point curve $crv_nm $nodeloc]
	ic_geo_set_node surface $surf $node $npos 
    } 
    ic_delete_geometry curve names $crv_nm
    ic_undo_group_end
    busy reset 
    # phase_enable 1
    ic_highlight
}

#This comes from mp_smooth_order_surface_nodes in mesh prototyper
proc aie_smooth_order_surface_nodes { {surfnodes ""} } {
    set newlist ""
    set  first [lindex $surfnodes 0]
    set second [lindex $surfnodes 1]
    lappend newlist $first
    lappend newlist $second
    set surfnodes [lreplace $surfnodes 0 1] 
    set remain [expr [llength $surfnodes]-1]
  
    for {set i 0} {$i < $remain} {incr i 2} {
	set added [expr $i+1] 
	set scan1 [lindex $surfnodes $i]
	set scan2 [lindex $surfnodes $added]
	set new [expr [llength $newlist]-1]
	set flag 1
	for {set j 0} {$j < $new} {incr j 2} {
	    set addedj [expr $j+1]
	    set one [lindex $newlist $j]
	    set two [lindex $newlist $addedj]
	    if {$one == $scan1 && $two == $scan2 } {set flag 0} 
	}
       
	if $flag {
	   lappend newlist $scan1
	   lappend newlist $scan2
	}    
    } 

    set surfnodes $newlist

    # detect for breaks in the loop
  
    # Order boundary surface nodes
    set begin [lindex $surfnodes 0]
    set end [lindex $surfnodes 1]
    set newnodes [concat $begin $end]
    set surfnodes [lreplace $surfnodes 0 1]
    set remain [llength $surfnodes]
    set previous [llength $surfnodes]
    while {$remain > 0} { 
	for {set i 0} {$i < $remain} {incr i} {
	    set added [expr $i+1]
	    set one [lindex $surfnodes $i]
	    set two [lindex $surfnodes $added]
	    #ic_mess "$one--$two\n" blue
	     if { $one == $begin } {
		set newnodes [concat $two $newnodes]
		set surfnodes [lreplace $surfnodes $i $added]
		set begin $two
		set remain -1
	    } elseif { $two == $begin } {
		set newnodes [concat $one $newnodes]
		set surfnodes [lreplace $surfnodes $i $added]
 		set begin $one
		set remain -1
 	    } elseif { $one == $end } {
		lappend newnodes $two
		#ic_mess "$newnodes \n" green
		set surfnodes [lreplace $surfnodes $i $added]
		set end $two
		set remain -1
          
	    } elseif { $two == $end } {
		lappend newnodes $one
		set surfnodes [lreplace $surfnodes $i $added]
		set end $one
		set remain -1
	    }
	}
	set  remain [llength $surfnodes]  
      
	if {$remain == $previous} {
	    set newnodes ""
	    return
	} else {
	    set previous $remain
	}
    }
 
     return $newnodes
}


