# 
proc oncreateLCSDEZLoad {} {
    global current_lcs_to_load lcs_data
	if ![ic_geo_is_loaded] ic_empty_tetin
	if ![array exists lcs_data] aie_load_lcs
	if [info exists current_lcs_to_load(edit)] {
		set current_lcs_to_load(name) $current_lcs_to_load(edit)
		unset current_lcs_to_load(edit)
	}


    foreach {n v} {
	name "" number 0 type Rectangular definedBy 0
	x1 0.0 y1 0.0 z1 0.0 x2 0.0 y2 0.0 z2 1.0 x3 1.0 y3 0.0 z3 0.0
	ref 0 scale 1.0
    } {
	if [info exists current_lcs_to_load($n)] {
	    set $n $current_lcs_to_load($n)
	} else {
	    set $n $v
	}
    }

    set ref [aie_get_lcs_name $ref]
    if {$name == ""} {
	foreach i [array names lcs_data] {
	    set used($i) 1
	    set used([lindex $lcs_data($i) 0]) 1
	}
	for {set i 1} {[info exists used(LCS$i)] || [info exists used($i)]} {incr i} { }
	set name LCS$i
	set number $i
    }
    set LCSTypeList [list Rectangular Cylindrical Spherical] ;# not Toroidal
    set LCSList [lsort [array names lcs_data]]
    if {$ref != ""} {
	createLCSRef setvalue @[lsearch $LCSList $ref]
    }
	set pickList [list "$x1 $y1 $z1" "$x2 $y2 $z2" "$x3 $y3 $z3"]
	set pickList1 {0 0 0}
    ::AIEnv::GUIManagement::ToggleGrey createLCSName [info exists current_lcs_to_load(name)]

    set AllowActiveReload 1
}

proc oncreateLCS1PWdgtFinish {} {
	if {$pickList1 != "" && $auto_pick_mode} {
		createLCSDEZ apply
		createLCS1PWdgt pick
	} 
}

proc oncreateLCS3PWdgtFinish {} {
	if {([llength $pickList] == 3) && $auto_pick_mode} {
		createLCSDEZ apply
		createLCS3PWdgt pick
	}
}

proc oncreateLCSDEZUnload {} {
	if [info exists ::current_lcs_to_load(name)] {
		unset ::current_lcs_to_load(name)
	}
}

proc aie_set_normal_to_screen_lcs {p0} {
	global tdv_default
#  
#   Not define coordinate system inside local: too confusing
#	aie_set_lcs_current lcs Global
#
#
	if ![va_is_triplet $p0] {
		ic_mess "Define origin location: $p0\n"
		return ""
	}
	set x0 [lindex $p0 0]
	set y0 [lindex $p0 1]
	set z0 [lindex $p0 2]
	set scr  [$tdv_default world2screen $x0 $y0 $z0]
	set scrx [lindex $scr 0]
	set scry [lindex $scr 1]
	set scrx [expr $scrx+1000.0]
	set p1z  [$tdv_default screen2world $scrx $scry] 
	set zdir [ic_vcalc nrm [lindex $p1z 1]]
	set p1   [lindex $p1z 0]
	set xdir [ic_vcalc dir $p0 $p1]
	set ydir [ic_vcalc product $xdir $zdir]
	set ydir [ic_vcalc nrm [ic_vcalc product $zdir $xdir]]
	set xdir [ic_vcalc nrm [ic_vcalc product $ydir $zdir]] 
# Create 3 points: 
	set p_on_x [ic_vcalc sum $p0 $xdir]
	set p_on_z [ic_vcalc sum $p0 $zdir]
	return [list $p0 $p_on_z $p_on_x]
}

proc oncreateLCSDEZApply {} {

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

    # Input "pickList" may be in current LCS. 
    # 
    set wasLCS [ic_csystem_get_current]
    if {$definedBy == 1} {
       set xyz [ic_coords_into_global $pickList1]
       if {$xyz == ""} {
          status_message "Cannot create LCS. Set/Select X Y Z" red
          return
       }	
       foreach "p0 p1 p2" [aie_set_normal_to_screen_lcs $xyz] ""
    } else {
       set p0 [ic_coords_into_global [lindex $pickList 0]]
       set p1 [ic_coords_into_global [lindex $pickList 1]]			
       set p2 [ic_coords_into_global [lindex $pickList 2]]			
       if {$p0 == "" || $p1 == "" || $p2 == ""} {
          status_message "Cannot create LCS. Check data" red
          return
       }
    }			
    if ![info exists ::current_lcs_to_load(name)] {
       set name [aie_new_lcs_name $name]
    }
#   Not define coordinate system inside local: too confusing
#	aie_set_lcs_current lcs Global
#
    set dby $definedBy
    set refnum [aie_get_lcs_num $ref]
    set data "$number $name $type $dby $p0 $p1 $p2 $refnum $scale"
    aie_set_lcs_data $name $data
    aie_save_lcs
    if {[info exists lcs_name_list] && [lsearch $lcs_name_list $name] < 0} {
       lappend lcs_name_list $name
    }
# geometry:
	set new [aie_create_csystem_from_nastran $name $type $p0 $p1 $p2]
	if {$new == ""} return
    ::AIEnv::GUIManagement::Tree::ShowLCS 2 lcs-$name 
	#if [info exists ::current_lcs_to_load(name)] {unset ::current_lcs_to_load(name)}
}

proc aie_delete_lcs {type name} {
    global lcs_data
    global lcs_name_list
	if [info exists lcs_data($name)] {
		unset lcs_data($name)
	}

	if {[ic_csystem_get_current] == $name} {
		ic_csystem_display all 0
		aie_set_lcs_current type global
	}
	catch "ic_csystem_delete $name" 
	set pos [lsearch $lcs_name_list $name]
	if { $pos >= 0} {
	   set lcs_name_list [lreplace $lcs_name_list $pos $pos]
	}
	aie_save_lcs
	::AIEnv::GUIManagement::Tree::DeleteLCS $name
}

proc aie_create_csystem_from_nastran {name type p0 p1 p2} {
	set zdir [ic_vcalc dir $p0 $p1]
	set xdir [ic_vcalc dir $p0 $p2]
	if ![ic_vcalc len $xdir] {return ""}
	set ydir [ic_vcalc nrm [ic_vcalc product $zdir $xdir]]
	set xdir [ic_vcalc nrm [ic_vcalc product $ydir $zdir]]

 	switch $type {
	    Cartesian   - R - Rectangular { set t2 cartesian }
	    Cylindrical - C               { set t2 cylindrical }
	    Spherical   - S               { set t2 spherical}
	}
	ic_csystem_create $name $t2 $p0 $xdir $ydir $zdir
	return $name
}

proc aie_set_lcs_current {type name} {
    global coord_system_label tdv_height tdv_default mess_lcs_current

    if {$name == "Global"} {
        set name global
    }
    set cc [ic_csystem_get $name]
    if {$cc == ""} {
        ic_mess "No such coordinate system $name\n"
        return
    }
    ic_csystem_set_current $name
    if {![info exist mess_lcs_current] || ([info exist mess_lcs_current] && $mess_lcs_current != "$name")} {
        ic_mess "Current Coordinate system is $name\n"
        set mess_lcs_current $name
    }
    after 5000 { catch { unset mess_lcs_current } }
    if [info exists coord_system_label] {
        $coord_system_label delete
        unset coord_system_label
    }
    if {($name != "") && ($name != "global")} {
        set str "Coord system = $name"
        set x 10
        set y [expr {$tdv_height($tdv_default) - 15}]
        set coord_system_label [tdv_text_im -point "$x $y 0" -transform 0 -text $str -color white]
        $tdv_default add_image $coord_system_label
    }
}

proc aie_set_lcs_data {name vals} {
    global lcs_data

    set lcs_data($name) $vals
    ::AIEnv::GUIManagement::Tree::PutLCS [list $name] 0
    aie_copy_lcs_to_bocos
}

proc aie_copy_lcs_to_bocos {} {
    global lcs_data lcs_name_list

    if ![info exists lcs_name_list] {set lcs_name_list ""}
    ic_boco_nastran_csystem reset
    
    foreach n [array names lcs_data] {
	if {$n == "Global"} continue
	
	foreach i {number name type dby x1 y1 z1 x2 y2 z2 x3 y3 z3 ref scale} v $lcs_data($n) {
	    set $i $v
	}
	foreach i {x1 y1 z1 x2 y2 z2 x3 y3 z3} {
	    set $i [expr [set $i] * $scale]
	}
	if {$ref == ""} { set ref 0 }
	
	switch $type {
	    Cartesian   - R - Rectangular { set t2 r }
	    Cylindrical - C               { set t2 c }
	    Spherical   - S               { set t2 s }
	}
	ic_boco_nastran_csystem set $number $ref $t2 [list $x1 $y1 $z1] \
	    [list $x2 $y2 $z2] [list $x3 $y3 $z3]

	if {[info exists lcs_name_list] && [lsearch $lcs_name_list $n] < 0} {
	   lappend lcs_name_list $n
	}
    }
}

proc aie_edit_lcs {name} {
    global current_lcs_to_load
    global lcs_data

    set current_lcs_to_load(edit) $name
    foreach {p n} {
	number 0 name 1 type 2 definedBy 3
	x1 4 y1 5 z1 6 x2 7 y2 8 z2 9 x3 10 y3 11 z3 12
	ref 13 scale 14
    } {
	set current_lcs_to_load($p) [lindex $lcs_data($name) $n]
    }
    createLCSDEZ show
}

# Pull in the LCS's from the params.

# Note that the scale is currently unused

# lcs_data(Reference_Coordinate_System) is always the number

proc aie_load_lcs {} {
    global lcs_data env lcs_name_list mess_lcs_current

    if {[array exists lcs_data] && [ic_csystem_list] == "" && [ic_csystem_get_current] == "global" } {
        if {![info exist mess_lcs_current] || ([info exist mess_lcs_current] && $mess_lcs_current != "global")} {
            ic_mess "Current Coordinate system is global\n"
        }
        set mess_lcs_current global
        return
    }
    after 5000 { catch { unset mess_lcs_current } }
    set cur_lcs [ic_csystem_get_current]
    catch { unset lcs_data }
    if ![info exists lcs_name_list] { set lcs_name_list "" }
    
    set lcs_data(Global) [list 0 Global Rectangular 0 0 0 0  0 0 0  0 0 0  0 1.0 1.0]
    
    # First see if we have any LCS's in the tetin data that need to get copied to the param data
    foreach lcname [ic_csystem_list] {
	    if [ic_param_node_exists :Local_Coordinates/$lcname] continue
	    foreach i {type p1 p2 p3} v [ic_csystem_get $lcname] {
	        set $i $v
	    }
        # NASTRAN LCS
		set Z_direction [ic_vcalc product $p2 $p3]
		set Pnt_on_Z [ic_vcalc sum $p1 $Z_direction]
		set Pnt_on_X [ic_vcalc sum $p1 $p2]
	    switch -glob $type {
	        car* { set ntype Rectangular }
	        cyl* { set ntype Cylindrical }
	        sph* { set ntype Spherical }
	        default { error "unknown coord system type $type" }
	    }
	    ic_param_add_node :Local_Coordinates $lcname [list Type $ntype \
							  Pt1_1 [lindex $p1 0] \
							  Pt1_2 [lindex $p1 1] \
							  Pt1_3 [lindex $p1 2] \
							  Pt2_1 [lindex $Pnt_on_Z 0] \
							  Pt2_2 [lindex $Pnt_on_Z 1] \
							  Pt2_3 [lindex $Pnt_on_Z 2] \
							  Pt3_1 [lindex $Pnt_on_X 0] \
							  Pt3_2 [lindex $Pnt_on_X 1] \
							  Pt3_3 [lindex $Pnt_on_X 2]]
    }
    
    set data ""
    foreach ch [ic_param_list_children :Local_Coordinates] {
	    array set vals { Type Rectangular Coordinate_System_ID 1 Pt1_1 0.0
	        Pt1_2 0.0 Pt1_3 0.0 Pt2_1 0.0 Pt2_2 0.0 Pt2_3 1.0
	        Pt3_1 1.0 Pt3_2 0.0 Pt3_3 0.0 Reference_Coordinate_System 0
	        Scale 1.0 }
	    array set vals [ic_param_get_values $ch]
	    if {$vals(Type) == "Cartesian"} { set vals(Type) Rectangular }
	    set name [lindex [split $ch /] end]
	    set lcs_data($name) [list $vals(Coordinate_System_ID) $name \
				 $vals(Type) 0 \
				 $vals(Pt1_1) $vals(Pt1_2) $vals(Pt1_3) \
				 $vals(Pt2_1) $vals(Pt2_2) $vals(Pt2_3) \
				 $vals(Pt3_1) $vals(Pt3_2) $vals(Pt3_3) \
				 $vals(Reference_Coordinate_System) \
				 $vals(Scale) 1.0]
	    lappend data [concat $name $lcs_data($name)]
	    aie_create_csystem_from_nastran $name $vals(Type) \
		    "$vals(Pt1_1) $vals(Pt1_2) $vals(Pt1_3)" \
		    "$vals(Pt2_1) $vals(Pt2_2) $vals(Pt2_3)" \
		    "$vals(Pt3_1) $vals(Pt3_2) $vals(Pt3_3)"

	    if {[info exists lcs_name_list] && [lsearch $lcs_name_list $name] < 0} {
	        lappend lcs_name_list $name
         }
    }

    ::AIEnv::GUIManagement::Tree::PutLCS $data 1
    aie_copy_lcs_to_bocos
    if {$cur_lcs != "" && [string toupper $cur_lcs] != "GLOBAL"} {
        ::AIEnv::GUIManagement::Tree::ShowLCS 2 lcs-$cur_lcs
    }
}

proc aie_save_lcs {} {
    global lcs_data
    foreach ch [ic_param_list_children :Local_Coordinates] {
	ic_param_delete_node $ch
    }
    
    foreach n [array names lcs_data] {
	if {$n == "Global"} continue
	
	set ref [lindex $lcs_data($n) 13]
	if {$ref == ""} { set ref 0 }
	
	set vals [list Create 1 Reference_Coordinate_System $ref]
	foreach t {Coordinate_System_ID Type 
	    Pt1_1 Pt1_2 Pt1_3 Pt2_1 Pt2_2 Pt2_3 Pt3_1 Pt3_2 Pt3_3 
	    Scale} i \
	    {0 2 4 5 6 7 8 9 10 11 12 14} {
		lappend vals $t [lindex $lcs_data($n) $i]
	    }
	ic_param_set_values :Local_Coordinates/$n $vals
    }
}

proc aie_get_lcs_name {num} {
    global lcs_data
    foreach n [array names lcs_data] {
	if {[lindex $lcs_data($n) 0] == $num} {
	    return $n
	}
    }
    return ""
}

proc aie_get_lcs_num {name} {
    global lcs_data
    if {($name == "") || ($name == "0")} { set name Global }
	if ![array exists lcs_data] aie_load_lcs
    if ![info exists lcs_data($name)] {
	user_error "No LCS exists with name \"$name\""
	return 0
    }
    return [lindex $lcs_data($name) 0]
}

proc aie_rename_lcs {name} {
    global lcs_data
    global lcs_name_list
    
    set newname [question_box .newname "New name" "New name for $name" $name]
    if {$newname == ""} return
    if [info exists lcs_data($newname)] {
    tk_dialog .newname Rename "Cannot rename:\nLocal Coordinate System \"$newname\" already exists\n" "" -1 OK
	return
	}

    #if ![aie_valid_name $newname 1] {return}
    #set newname [string toupper $newname]
    set newname [aie_get_valid_name $newname]
    
    if {[ic_csystem_get_current] == $name} {
       ic_csystem_display all 0
       aie_set_lcs_current type global
    }

    if [info exists lcs_data($name)] {
        set lcs_data($newname) $lcs_data($name)
        set lcs_data($newname) [lreplace  $lcs_data($newname) 1 1 $newname]
        unset lcs_data($name)
    }
    catch "ic_csystem_delete $name"
    set pos [lsearch $lcs_name_list $name]
    if { $pos >= 0} {
       set lcs_name_list [lreplace $lcs_name_list $pos $pos]
    }
    if {[info exists lcs_name_list] && [lsearch $lcs_name_list $newname] < 0} {
       lappend lcs_name_list $newname
    }
    ::AIEnv::GUIManagement::Tree::RenameLCS $name $newname

    set name $newname
    set type [lindex $lcs_data($name) 2]
    set p0 [lindex $lcs_data($name) 4]
    append p0 " "
    append p0 [lindex $lcs_data($name) 5] 
    append p0 " "
    append p0 [lindex $lcs_data($name) 6]
    set p1 [lindex $lcs_data($name) 7]
    append p1 " "
    append p1 [lindex $lcs_data($name) 8] 
    append p1 " "
    append p1 [lindex $lcs_data($name) 9]
    set p2 [lindex $lcs_data($name) 10]
    append p2 " "
    append p2 [lindex $lcs_data($name) 11] 
    append p2 " "
    append p2 [lindex $lcs_data($name) 12]
    aie_save_lcs
    set new [aie_create_csystem_from_nastran $name $type $p0 $p1 $p2]
    if {$new == ""} return
    ::AIEnv::GUIManagement::Tree::ShowLCS 1 lcs-$name 
#    set ::va_set(name) $name
#    va_auto_name csystem
#    set name $::va_set(name)
 
}

proc aie_flip_axes_lcs {name} {
	global lcs_data
	set data [ic_csystem_get $name]
	if ![llength $data] return
	foreach {type p0 p1 p2 p3} $data ""
	ic_csystem_create $name $type $p0 $p2 $p3 $p1
	#
	#NASTRAN LCS data for project
	foreach i {type p1 p2 p3} v [ic_csystem_get $name] {
	    set $i $v
	}

	set Z_direction [ic_vcalc product $p2 $p3]
	set Pnt_on_Z [ic_vcalc sum $p1 $Z_direction]
	set Pnt_on_X [ic_vcalc sum $p1 $p2]
	set newdata $lcs_data($name)
	set i 7
	foreach c "$Pnt_on_Z $Pnt_on_X" {
		set newdata [lreplace $newdata $i $i $c]
		incr i
	}
	aie_set_lcs_data $name $newdata
	#
	if {[ic_csystem_get_current] == $name} {
		ic_csystem_display $name 1
	} else {
		aie_set_lcs_current $type $name
		::AIEnv::GUIManagement::Tree::ShowLCS 1 lcs-$name 
	}
}

proc aie_new_lcs_name {{name ""}} {
# delete spaces if any 
	while 1 {
		set k [string first " " $name]
		if {$k < 0} break
		set name [string replace $name $k $k]
	}
	if ![llength $name] {
		set name LCS1
	}
	set list [ic_csystem_list]
	if {[lsearch $list $name] < 0} {
		return $name
	}
	set last [string index $name end]
    if ![regexp {[0-9]} $last] {
		append name 0
	} else {
		set name [string replace $name end end][incr last]
	}
	return [aie_new_lcs_name $name]
}




