# ===========================================================================
#  Copyright 1999 SAS IP, Inc. Proprietary Data.
#  Unauthorized use, distribution, or duplication is prohibited.
#  All Rights Reserved.
# ============================================================================
#  $Revision: 503304 $
#  $Date: 2011-09-07 10:32:34 -0400 (Wed, 07 Sep 2011) $
# ============================================================================
# File Name:     ShellSection.eui
# Description:   Define and Edit Composite Shell Section for ANSYS
# ============================================================================
package require msgcat

set imagePath [file join $env(EUIDL_DIR) gui $::euidl::euidlArray(language) images]

namespace eval ::euidl::element::shell::section {} {
      
   proc create {} {
      variable parent
      variable childsite
      variable treeParent
      variable child
      variable matid
      variable left
      variable treeMaterialParent
      variable treeModelParent
      variable emptyfolder
      variable treeChildsite
      variable dbparent
      variable replaceParent
      variable findParent

      variable numCol
      variable numRow

      variable page1
      variable page2
      variable page3

      variable tabparent
      variable mframe

      #The code goes through a check to find out
      #before it prints out a summary
      variable prepError
      variable qstatus

      #List of all global variable that are written to the Ansys database
      variable sectionid
      variable sectionname

      #Data used for storing information to input shell data to Ansys
      #tbdata is a table of size numRow and numCols-?
      #Verify if these need a default value
      variable tbdata
      variable addedMassPerUnitArea
      variable drillStiffnessFactor
      variable membraneHGFactor
      variable bendingHGFactor
      variable tss11
      variable tss22
      variable tss12
      variable compositeDensity
      variable sectionOffset
      variable uiSectionOffset

      #The material information is read from the database
      #If no materials are read the gui quits with an error
      #message(it is supposed to)
      variable listOfMaterials
      variable numberOfMaterials

      #List of all tables for the Section Function
      variable listOfTables
      variable twiceNumberOfTables
      variable listOfCSYS
      variable twiceNumberOfCSYS

      #This code is to be removed
      variable listOfUniqueLayers
      variable numberOfUniqueLayers
      variable modifiedRow
      variable newValMRow

      #The next few datas are for the search/replace mechanism
      #All variables that start with find contain values of the 
      #four parallel values of a layer that we are trying to search for
      variable findThicknessValue
      variable findMaterialIDValue
      variable findOrientationValue
      variable findNumIPValue
      
      #Similarly replace**** represents the values that replace the
      #data in search
      variable replaceThicknessValue
      variable replaceMaterialIDValue
      variable replaceOrientationValue
      variable replaceNumIPValue
      variable replaceIndex

      # if find does not contain any data these values are set to zero
      # if the replace values are not set for a particular column 
      # no data is replaced
      variable thicknessInactive
      variable materialIDInactive
      variable orientationInactive
      variable numIPInactive
      variable foundLayers
      
      variable fakeID
      variable fakeIDDefined

      #Tool Menu Variable
      variable xeroxParent
      variable numberOfCopies

      variable tablewinColor
      
      #List of colors for coloring the entities dep on Mat ID
      variable numberedEntityColors

      #Local Copy Buffer
      variable cp_r_min
      variable cp_r_max
      variable cp_c_min
      variable cp_c_max

      #A flag for tracing tbdata changes to update pics
      variable alreadyTraced

      #To turn of picture updating
      variable pictureUpdateFlag

      variable loadedImage

      set qstatus 1
      set thicknessInactive 0
      set materialIDInactive 0
      set orientationInactive 0
      set numIPInactive 0
      set fakeIDDefined 0
      set numRow 0
      set numCol 0
      set alreadyTraced 0
      set pictureUpdateFlag 1

#      ans_greygui 0 0
#      ans_greygui 1 0
#      ans_greygui 3 0
#      ans_greygui 4 0
      #Read all the images from the database
      loadImages
      prepareColorList

      if {[winfo exists .dlgCompositeShellSectionGUI]} {
            wm deiconify $parent
            raise $parent
            return
      }
     
    #  TABLE label matid
      TABLE CHAB 1

      if {[winfo exists .dlgCompositeShellSectionGUI]} {
         wm deiconify $parent
         raise $parent
         return
      }

   }
   

   proc exit {} {
       variable parent

       ans_greygui 0 1
       ans_greygui 1 1
       ans_greygui 3 1
       ans_greygui 4 1
      
       wm withdraw $parent
      
   }

   proc loadImages {} {
      variable loadedImages
      global imagePath
      set loadedImages [list]
      for { set i 0 } { $i < 36 } { incr i 1 } {
         set angle [expr $i * 5]
         catch { set myimage [image create photo -file \
            [file join $imagePath section_${angle}_128x32.png] ] }
         catch { lappend loadedImages $myimage  }
      }
   }

   proc prepareColorList {} {
     variable colorList
     set colorList [list "#000000" "#ff0080" "Magenta"  "#8000ff" "Blue" "#0080ff" \
                         "Cyan" "#00ff80" "Green" "#80ff00" "Yellow" "Orange" \
                         "Red" "DarkGrey" "LightGrey" "White" ]
   }
  
   proc turnOnImageUpdating {} {
      variable picureUpdateFlag
      variable alreadyTraced
      set pictureUpdateFlag 1
      if { $alreadyTraced == 0 } {
         trace variable ::euidl::element::shell::section::tbdata w [code updateImageByTrace]
         set alreadyTraced 1
      }
   }

   proc turnOffImageUpdating {} {
      variable picureUpdateFlag
      variable alreadyTraced
      set pictureUpdateFlag 0
      if { $alreadyTraced == 1 } {
         trace vdelete ::euidl::element::shell::section::tbdata w [code updateImageByTrace]
         set alreadyTraced 0
      }
   }
 
   proc TABLE {label matid} {
      
      variable tabparent

      # For labels CHAB & USER the maximum of CELLS = 1000  
      
      variable sectionid
      variable numCol
      variable numRow
      variable tbdata
      variable labelin
      variable tbopt
      variable tboptkcn
      variable colmax
      variable rowmax
      variable page1
      variable page2
      variable page3
      variable numberOfMaterials

      # colmax need a default
      set colmax 1000
      set rowmax 1000000 
      set labelin $label
     
      variable parent
      variable childsite
      #Handle to the table created for the shell sections
      variable shelldatatable
      variable mat
      variable treeChildsite
      variable confirm
      variable mframe

      variable alreadyTraced
      variable pictureUpdateFlag

      set mat $matid
      set tbopt "None defined"
      set tboptkcn 0

      if [winfo exists .dlgCompositeShellSectionGUI] {
         # Set the display correctly
         $parent activate
         return
      }


      set parent [euidl::dialog .dlgCompositeShellSectionGUI \
                                -class EUIDL -grabwin this]

      set childsite [$parent component childsite]

      #SET WINDOW#

      wm minsize $parent 800 450
    
      wm title $parent [msgcat::mc "Create and Modify Shell Sections"]

      $parent configure \
            -okcommand [code saveAndExit] \
            -cancelcommand [code cancelShellSectionGUI] \
            -helpcommand [code help]


      #wm minsize $parent [winfo reqwidth $parent] \
      #                    [expr [winfo reqheight $parent] + 50]

      #Construct a frame for the main menus
      set mframe [frame $childsite.mframe -class EUIDL]
      pack $mframe -side top -anchor w

      menubars
      getMaterialList
      readNumberedEntityColors

      #Construct a tab notebook and two pages
      set tabparent [::euidl::tabnotebook $childsite.tnb]
      pack $tabparent -padx 3 -pady 3 -fill both -expand true

      set page [$tabparent add]
      $tabparent pageconfigure 0 -label [msgcat::mc "Layup"]
      $tabparent pageconfigure 0 -command [code toggleMenuBars 1]
      set page1 [frame $page.hold -class EUIDL]
      pack $page1 -padx 10 -pady 10 -fill both -expand true

      set page [$tabparent add]
      $tabparent pageconfigure 1 -label [msgcat::mc "Section Controls"]
      $tabparent pageconfigure 1 -command [code toggleMenuBars 0]
      set page2 [frame $page.hold -class EUIDL]
      pack $page2 -padx 10 -pady 10 -fill both -expand true

      set page [$tabparent add]
      $tabparent pageconfigure 2 -label [msgcat::mc "Summary"] \
                                 -command [code processSummaryPage]
      set page3 [frame $page.hold -class EUIDL]
      pack $page3 -padx 10 -pady 10 -fill both -expand true


      if { $numberOfMaterials != 0 } {
         page1
         page2
         page3
         addrow 1

         $tabparent select 0

         #Obtain the list of Material IDs
         #Put information in global data 

         update
         # Get the correct width of the widget
         set ndWidth [winfo reqwidth [$tabparent component tabset]]
         set ndWpage1 [winfo reqwidth $page1]
         if {$ndWidth < $ndWpage1} {set ndWidth $ndWpage1}
         set ndWpage2 [winfo reqwidth $page2]
         if {$ndWidth < $ndWpage2} {set ndWidth $ndWpage2}
         set ndWpage3 [winfo reqwidth $page3]
         if {$ndWidth < $ndWpage3} {set ndWidth $ndWpage3}

         # Get the correct height of the widget
         set ndHeight [winfo reqheight [$tabparent component tabset]]
         set ndHpage1 [winfo reqheight $page1]
         if {$ndHeight < $ndHpage1} {set ndHeight $ndHpage1}
         set ndHpage2 [winfo reqheight $page2]
         if {$ndHeight < $ndHpage2} {set ndHeight $ndHpage2}
         set ndHpage3 [winfo reqheight $page3]
         if {$ndHeight < $ndHpage3} {set ndHeight $ndHpage3}

         $tabparent configure \
               -width [expr $ndWidth + 25] \
               -height [expr $ndHeight + 50]

         $parent activate

         set pictureUpdateFlag 1
         if { $alreadyTraced == 0 } {
            trace variable ::euidl::element::shell::section::tbdata w [code updateImageByTrace]
            set alreadyTraced 1
         }
         updateImages

         set sectionid 1
         set listOfSections [ ans_getlist sect ]
         set twiceNumberOfSections [ llength $listOfSections ]


         if { $twiceNumberOfSections > 0 } {
            set temp [lindex $listOfSections 0]
            if { $temp != "None defined" } {
               #Look for the first valid section id and load it
               for { set iIndex 1 } { $iIndex < $twiceNumberOfSections } { incr iIndex 2 } {
                  set sectionid [lindex $listOfSections $iIndex]

                  #check if the section is a shell section
                  if { [info exists sectionid] != 0 } {
                     if { $sectionid != "None defined" } {
                        if { ! [catch { set sectionid [ ans_evalexpr $sectionid ] }] } {
                           if { $sectionid > 0 } {
                              if  { ! [catch { set sectiontype [ans_getvalue shell,$sectionid,type] }] } {
                                 if { $sectiontype == "SHEL    " } {
                                    filltable
                                    if {[winfo exists .dlgCompositeShellSectionGUI]} {
                                          wm deiconify $parent
                                          raise $parent
                                          return
                                    }
                                 }
                              }
                           }
                        }
                     }
                  }
               }
               #End of loop looking for valid section
               #Now set it to the smallest available number
               set sectionid [expr $sectionid + 1]
            }
         }
      
         after 125 [list focus -force $shelldatatable]

      } else {
         ans_senderror 2 "Shell Section GUI will not startup without any valid materials"
         cancelShellSectionGUI
      }


   }

   proc menubars {} {

      variable parent
      variable childsite
      variable mframe
      variable sectionid
      variable findThicknessValue
      variable findMaterialIDValue
      variable findOrientationValue
      variable findNumIPValue
      variable replaceThicknessValue
      variable replaceMaterialIDValue
      variable replaceOrientationValue
      variable replaceNumIPValue

      #Construct Menu Bars
      # Section Menu Bar
      menubutton $mframe.sectionmbutton -text Section \
                  -menu $mframe.sectionmbutton.sectionmenu
      grid $mframe.sectionmbutton -row 0 -column 3 -sticky w
      bind $mframe.sectionmbutton <Enter> [code raiseSectionButton]
      bind $mframe.sectionmbutton <Leave> [code lowerSectionButton]
      bind $mframe.sectionmbutton <FocusOut> [code lowerSectionButton]
      bind $mframe.sectionmbutton <Button-1> [code lowerSectionButton]
      trace variable ::euidl::element::shell::section::sectionid w [code traceSectionID]
      set sectionmenu [menu $mframe.sectionmbutton.sectionmenu -tearoff 0]
      $sectionmenu add command -label New -command [code newSection]
      $sectionmenu add command -label Reload -command [code reload]
      $sectionmenu add command -label Save -command [code writeCompositeShellSectionToDB]
      
      # Tools Menu Bar
      menubutton $mframe.sectionebutton -text Edit \
                  -menu $mframe.sectionebutton.editmenu
      grid $mframe.sectionebutton -row 0 -column 4 -sticky w
      bind $mframe.sectionebutton <Enter> [code raiseEditButton]
      bind $mframe.sectionebutton <Leave> [code lowerEditButton]
      bind $mframe.sectionebutton <Button-1> [code b1EditButton]
      bind $mframe.sectionebutton <FocusOut> [code lowerEditButton]

      set editmenu [menu $mframe.sectionebutton.editmenu -tearoff 0]

      $editmenu add command -label "Copy" \
                            -command [code copy_local]

      $editmenu add command -label "Paste" \
                            -command [code paste_local]

      $editmenu add command -label "Insert" \
                            -command [code insert_local]
      # Tools Menu Bar
      menubutton $mframe.sectiontbutton -text Tools \
                  -menu $mframe.sectiontbutton.toolsmenu
      grid $mframe.sectiontbutton -row 0 -column 5 -sticky w
      bind $mframe.sectiontbutton <Enter> [code raiseToolsButton]
      bind $mframe.sectiontbutton <Leave> [code lowerToolsButton]
      bind $mframe.sectiontbutton <FocusOut> [code lowerToolsButton]
      bind $mframe.sectiontbutton <Button-1> [code lowerToolsButton]

      set toolsmenu [menu $mframe.sectiontbutton.toolsmenu -tearoff 0]

      $toolsmenu add command -label "Find Menu" \
                             -command [code findDialog]
      $toolsmenu add command -label "Replace Menu" \
                             -command [code replaceDialog]
      $toolsmenu add command -label "Add Symmetry" \
                             -command [code applySymmetry]
      $toolsmenu add command -label "Add AntiSymmetry" \
                             -command [code applyAntiSymmetry]
      $toolsmenu add command -label "Add Multiple Copies" \
                             -command [code makeNCopiesDialog]
   }

   proc help {} {
      variable tabparent
      switch -- [$tabparent index select] {
         0 {
            ans_loadhelp Hlp_G_STRSHELL_4
         }
         1 {
            ans_loadhelp Hlp_C_SECCONTROL
         }
         2 {
            ans_loadhelp Hlp_G_STRSHELL_4
         }
      }
   }

   proc greyOutPullDowns {} {

      variable sectionid
      variable mframe

      #Variable to check if sectionid is a parameter
      set isParam -1

      $mframe.sectionmbutton.sectionmenu entryconfigure 1 -state disabled
      $mframe.sectionmbutton.sectionmenu entryconfigure 2 -state disabled

      if { [info exists sectionid] != 0 } {
         #If it is not an integer it might be a APDL Param
         if { ![string is integer $sectionid] } {
            set parlist [ans_getlist PAR]
            if { [llength  $parlist] != 0 } {
               set isParam [lsearch $parlist $sectionid]
            }
            #If it is an APDL parameter make save normal
            if { $isParam != -1 } {
               #Grey out Save and Reload
               $mframe.sectionmbutton.sectionmenu entryconfigure 2 -state normal
            }
         } else {
         #if it is an integer make reload normals
               $mframe.sectionmbutton.sectionmenu entryconfigure 2 -state normal
         }

         #tcl check to get an integer in case there are spaces
         catch { set sectionid [expr 1 * $sectionid] }
         set isValidID 0
         
         #If it is a valid parameter or an integer do the sectinqr
         if { $isParam != -1 } {
            catch { set isValidID [ ans_evalexpr sectinqr($sectionid,1) ] }
         } else {
            if { [string is integer $sectionid] } {
               catch { set isValidID [ ans_evalexpr sectinqr($sectionid,1) ] }
            }
         }

         #if it is a valid section check if it is a shell section
         if { $isValidID != 0 } {
            if  { [catch { set sectiontype [ans_getvalue shell,$sectionid,type] }] } {
               set sectiontype "UNKNOWN"
            }
         } else {
            set sectiontype "UNKNOWN"
         }

         set sectiontype [string trim $sectiontype]
         #If it is a valid shell section make reload normal
         if { $sectiontype == "SHEL" } {
            $mframe.sectionmbutton.sectionmenu entryconfigure 1 -state normal
         }
      }
   }

   proc traceSectionID { myVar arrayIndex values } {
      greyOutPullDowns
   }

   proc page1 {} {
      variable childsite
      variable tabparent
      variable page1
      variable treeChildsite
      variable shelldatatable
      variable tbdata
      variable numCol
      variable numRow
      variable colmax
      variable rowmax
      variable sectionid
      variable tablewinColor
      variable tbdata

      #Varaible for the Section Function data
      variable listOfTables
      variable twiceNumberOfTables
      variable listOfCSYS
      variable twiceNumberOfCSYS
      variable tbopt
      variable tboptkcn

      #Varaible for the Section Function data
      variable listOfSections
      variable numberOfSections
      variable uiSectionOffset
      variable sectionOffset

      euidl::labeledframe $page1.frm1 -text [msgcat::mc "Layup"]
      set child [$page1.frm1 component childsite]
      grid $page1.frm1 -column 0 -row 0 -sticky new
      pack $page1.frm1 -fill both -expand true


      set shelldatatable [euidl::table $child.tbl1 \
            -variable [scope tbdata] \
            -rowseparator \n \
            -colseparator \t \
            -validate focusout \
            -colstretchmode fill \
         ]


      bind $shelldatatable <B1-Motion> [code rehighlightComboBoxes]
      bind $shelldatatable <Button-1>  [code rehighlightComboBoxes]
      bind $shelldatatable <ButtonRelease-1>  [code rehighlightComboBoxes]
      bind $shelldatatable <Control-c>  [code copy_local]
      bind $shelldatatable <Control-i>  [code insert_local]

      euidl::label $child.lblTop -height 3 \
           -anchor w \
           -text [msgcat::mc "Create and Modify Shell Sections"]

      grid $child.lblTop -sticky w -column 0 -row 1 \
            -columnspan 3

      #Name of the Section\
      #Label
      euidl::label $child.sectionnamelabel -height 3 \
           -text [msgcat::mc "Name"]
      grid $child.sectionnamelabel -column 4 -row 1 -sticky e
      #The Entry
      euidl::entry  $child.sectionnameentry -variable [scope sectionname ]
      #Grid the section id entry
      grid $child.sectionnameentry -column 5 -row 1 -sticky w
      bind $child.sectionnameentry <Return> { break }

      #Section ID
      #Label
      euidl::label $child.sectionidlabel -height 3 \
           -text [msgcat::mc "ID"]
      grid $child.sectionidlabel -column 6 -row 1 -sticky e
      #The Entry
      euidl::combobox  $child.cmbboxsectionid -variable [scope sectionid ] \
                      -style combobox
      #Get the List of all Available Sections
      set listOfSections [ ans_getlist sect ]
      set numberOfSections [ llength $listOfSections ]
      set twiceNumberOfSections [ llength $listOfSections ]
      if { $twiceNumberOfSections > 0 } {
         set first [lindex $listOfSections 0]
         if { $first == "None defined" } {
            set listOfSections [list "None defined" 0]
         }
      }
      $child.cmbboxsectionid insert list end $listOfSections
      

      #Grid the section id entry
      grid $child.cmbboxsectionid -column 7 -row 1 -sticky w
      $child.cmbboxsectionid configure -command [code filltable]
      bind $child.cmbboxsectionid <Button-1> [code sectionIdUpdate]
      bind $child.cmbboxsectionid <Return> { break }
      bind $child.cmbboxsectionid <Leave> { break }

      #Add a new row to define a layer
      #Button to add new layer
      euidl::button $child.addaftr -text [msgcat::mc "Add Layer"] \
            -command [code addrow 1]
      grid $child.addaftr -column 1 -row 3

      #Delete a row to define a layer
      #Button to delete layer
      euidl::button $child.delrow -text [msgcat::mc "Delete Layer"] \
            -command [code rowselect ]
      grid $child.delrow -column 2 -row 3


      #Section Offset
      #SHELL SECTION OFFSETS(from pr7section.F)
      #-----------------------------------------
      #  position = 1 --> Mid-Plane (default)
      #  position = 2 --> Top-Plane 
      #  position = 3 --> Bottom-Plane
      #  position = 0 --> User Input location
      #------------------------------------------
      #**** Add a mechanism to set user input location
      euidl::label $child.p2SOFFL -height 2 -anchor w \
           -text [msgcat::mc  "Section Offset"]
      grid $child.p2SOFFL -sticky w -column 1 -row 5
      euidl::combobox  $child.p2SOFFCMB -variable [scope sectionOffset ] \
                                        -command [code toggleUISecOffsetState]
      $child.p2SOFFCMB insert list end \
          [list {  Mid-Plane}         1 \
                {  Top-Plane}         2 \
                {  Bottom-Plane}      3 \
                {  User-Input-Location} 0
          ]
      set sectionOffset 1
      grid $child.p2SOFFCMB -sticky w -column 2 -row 5
      bind $child.p2SOFFCMB <Return> { break }

      #Entry box for Section Offset value
      #This is activated only if section offset is set to UserInputLocation
      euidl::label $child.p1SOffsetUInputLabel -height 2 -anchor w \
           -text [msgcat::mc  "User Defined Value"]
      $child.p1SOffsetUInputLabel configure -state disabled
      grid $child.p1SOffsetUInputLabel -sticky e -column 4 -row 5

      euidl::entry $child.p1SOffsetUInput -variable [scope uiSectionOffset]
      $child.p1SOffsetUInput configure -state disabled
      grid $child.p1SOffsetUInput -sticky w -column 5 -row 5
      bind $child.p1SOffsetUInput <Return> { break }

      #Section Function
      #Get the list of available function and link them in here.
      euidl::label $child.p1SFL -height 2 -anchor w \
           -text [msgcat::mc  "Section Function"]
      grid $child.p1SFL -sticky e -column 1 -row 6 \
            -columnspan 1
      euidl::label $child.p1SFkcnL -height 2 -anchor w \
           -text [msgcat::mc  "KCN or Node"]
      grid $child.p1SFkcnL -sticky e -column 4 -row 6 \
            -columnspan 1

      #Get the List of all Available Tables
      set listOfTables [ ans_getlist par ]
      set twiceNumberOfTables [ llength $listOfTables ]
      if { $twiceNumberOfTables > 0 } {
         set first [lindex $listOfTables 0]
         if { $first != "None defined" } {
            set listOfTables [concat {"None" "None defined"} $listOfTables]
            set twiceNumberOfTables [expr $twiceNumberOfTables + 2]
         }
      }

      euidl::combobox  $child.p1SFCMB -variable [scope tbopt]
      $child.p1SFCMB insert list end $listOfTables
      grid $child.p1SFCMB -sticky e -column 2 -row 6 -columnspan 1
      bind $child.p1SFCMB <Return> { break }

      #Get the List of all Available ESYS
      set listOfCSYS [ ans_getlist csys ]
      set listOfCSYS [concat $listOfCSYS {"Node table" -99}]
      set listOfCSYS [concat $listOfCSYS {"2D Node table" -98}]
      set twiceNumberOfCSYS [ llength $listOfCSYS ]

      euidl::combobox  $child.p1SFkcnCMB -variable [scope tboptkcn]
      $child.p1SFkcnCMB insert list end $listOfCSYS
      grid $child.p1SFkcnCMB -sticky e -column 5 -row 6 -columnspan 1
      bind $child.p1SFkcnCMB <Return> { break }

      #Construct the Table
      set numCol 5
      set numRow 0

      #Layer Number
      set tbdata(1,-1) "1"

      $shelldatatable config -rowmax 1000000

      set rowmax 1000000


      # FILL THE TABLE WITH EXISTING DATA IF TABLE EXISTS

      # we will want to see if the shell section exists here
      set sh 0
      if {$sh == 1} {
         #if table does not exist, set the default
      } else {         
          initable 
      }

      grid $shelldatatable -sticky news -column 0 -row 2 -columnspan 8
      grid rowconfigure $child 2 -weight 1

      # Set the max view height for the table
      grid rowconfigure $child 2 -minsize 50
      grid columnconfigure $child 2 -minsize 3
      grid columnconfigure $child 5 -minsize 3
      grid columnconfigure $child 0 -weight 1
      grid columnconfigure $child 1 -weight 1
      grid columnconfigure $child 2 -weight 1
      grid columnconfigure $child 3 -weight 1
      grid columnconfigure $child 4 -weight 0
      grid columnconfigure $child 5 -weight 0
      grid columnconfigure $child 6 -weight 0

      update idletasks

      grid propagate $child 0

      euidl::combobox  $child.newcb$numRow -style combobox
      $child.newcb$numRow insert list end \
          [list {-999} -999 \
            {  Mat0}      1 \
            {  Mat1}      2 \
            {  Mat2}      3 \
          ]

      set treeChildsite $child

      $shelldatatable selection set 1,0
      $shelldatatable activate 1,0 
      $shelldatatable selection anchor 1,0
      $shelldatatable see active

      set tablewinColor [ $child.sectionnameentry cget -background ]

   }

   proc page2 {} {
      variable childsite
      variable tabparent
      variable page2
      variable treeChildsite
      variable shelldatatable
      variable numCol
      variable numRow
      variable colmax
      variable rowmax

      variable addedMassPerUnitArea
      variable drillStiffnessFactor
      variable membraneHGFactor
      variable bendingHGFactor
      variable tss11
      variable tss22
      variable tss12

      euidl::labeledframe $page2.frm1 -text [msgcat::mc "Section Controls"]
      set child [$page2.frm1 component childsite]
      pack $page2.frm1 -fill both -expand true -anchor w

      #Other Element Attributes include
      #1) Transverse Shear Stiffness (E11, E22, E12)
      #2) Added Mass Per Unit Area
      #3) Membrane HG Factor
      #4) Bending  HG Factor
      #5) Drill Stiffness Factor

      #Transverse Shear Stiffness
      #It has three component 11,22,12
      euidl::label $child.p2TSSL -height 2 -anchor w \
           -text [msgcat::mc  "Trans Shear Stiffness (E11,E22,E12)"]
      grid $child.p2TSSL -sticky w -column 0 -row 0 \
            -columnspan 3

      euidl::entry  $child.p2TSS11E -variable [scope tss11 ]
      grid $child.p2TSS11E -sticky w -column 3 -row 0 -columnspan 1
      bind $child.p2TSS11E <Return> { break }

      euidl::entry  $child.p2TSS22E -variable [scope tss22 ]
      grid $child.p2TSS22E -sticky w -column 4 -row 0 -columnspan 1
      bind $child.p2TSS22E <Return> { break }

      euidl::entry  $child.p2TSS12E -variable [scope tss12 ]
      grid $child.p2TSS12E -sticky w -column 5 -row 0 -columnspan 1
      bind $child.p2TSS12E <Return> { break }

      #Added Mass/Unit Area
      euidl::label $child.p2AMPUAL -height 2 -anchor w \
           -text [msgcat::mc  "Added Mass/Unit Area"]
      grid $child.p2AMPUAL -sticky w -column 0 -row 1 \
            -columnspan 3
      euidl::entry  $child.p2AMPUAE -variable [scope addedMassPerUnitArea ]
      grid $child.p2AMPUAE -sticky w -column 3 -row 1 -columnspan 1
      bind $child.p2AMPUAE <Return> { break }

      #Membrane Hourglass
      euidl::label $child.p2MHGL -height 2 -anchor w \
           -text [msgcat::mc  "Membrane Hourglass Factor"]
      grid $child.p2MHGL -sticky w -column 0 -row 2 \
           -columnspan 3
      euidl::entry  $child.p2MHGE -variable [scope membraneHGFactor ]
      grid $child.p2MHGE -sticky w -column 3 -row 2 -columnspan 1
      bind $child.p2MHGE <Return> { break }

      #Bending Hourglass
      euidl::label $child.p2BHGL -height 2 -anchor w \
           -text [msgcat::mc  "Bending Hourglass Factor"]
      grid $child.p2BHGL -sticky w -column 0 -row 3 \
           -columnspan 3
      euidl::entry  $child.p2BHGE -variable [scope bendingHGFactor ]
      grid $child.p2BHGE -sticky w -column 3 -row 3 -columnspan 1
      bind $child.p2BHGE <Return> { break }

      #Drill Stiffness Factor
      euidl::label $child.p2DSFL -height 2 -anchor w \
           -text [msgcat::mc  "Drill Stiffness Factor"]
      grid $child.p2DSFL -sticky w -column 0 -row 4 \
            -columnspan 3
      euidl::entry  $child.p2DSFE -variable [scope drillStiffnessFactor ]
      grid $child.p2DSFE -sticky w -column 3 -row 4 -columnspan 1
      bind $child.p2DSFE <Return> { break }

      update idletasks
         
      set treeChildsite $child
   }

   proc page3 {} {
      variable childsite
      variable tabparent
      variable page3
      variable treeChildsite
      variable shelldatatable
      variable numCol
      variable numRow
      variable colmax
      variable rowmax

      #Summary of the whole section
      euidl::labeledframe $page3.frm1 -text [msgcat::mc "Summary"]
      set child [$page3.frm1 component childsite]
      pack $page3.frm1 -fill both -expand true -anchor w

      #ID of the Shell
      euidl::label $child.lNIDL -height 2 -anchor w \
           -text [msgcat::mc  "Shell ID                    =  "]
      grid $child.lNIDL  -column 0 -row 0
      euidl::label $child.lNIDLV -height 2 -anchor w \
           -text [msgcat::mc  "-"]
      grid $child.lNIDLV  -column 1 -row 0

      #Name of the Shell
      euidl::label $child.lNAME -height 2 -anchor w \
           -text [msgcat::mc  "Shell Name                  =  "]
      grid $child.lNAME  -column 0 -row 1
      euidl::label $child.lNAMEV -height 2 -anchor w \
           -text [msgcat::mc  "-"]
      grid $child.lNAMEV  -column 1 -row 1

      #Total Thickness
      euidl::label $child.lTTHK -height 2 -anchor w \
           -text [msgcat::mc  "Total Thickness             =  "]
      grid $child.lTTHK -column 0 -row 2
      euidl::label $child.lTTHKV -height 2 -anchor w \
           -text [msgcat::mc  "-"]
      grid $child.lTTHKV -column 1 -row 2

      #Number of Layers
      euidl::label $child.lNLAY -height 2 -anchor w \
           -text [msgcat::mc  "Number of Layers            =  "]
      grid $child.lNLAY  -column 0 -row 3
      euidl::label $child.lNLAYV -height 2 -anchor w \
           -text [msgcat::mc  "-"]
      grid $child.lNLAYV  -column 1 -row 3

      #Number of Section Pts
      euidl::label $child.lNSP -height 2 -anchor w \
           -text [msgcat::mc  "Number of Section Pts       =  "]
      grid $child.lNSP -column 0 -row 4
      euidl::label $child.lNSPV -height 2 -anchor w \
           -text [msgcat::mc  "-"]
      grid $child.lNSPV -column 1 -row 4

      #Offset State
      euidl::label $child.lYOFF -height 2 -anchor w \
           -text [msgcat::mc  "Section Offset Information  =  "]
      grid $child.lYOFF -column 0 -row 5
      euidl::label $child.lYOFFV -height 2 -anchor w \
           -text [msgcat::mc  "-"]
      grid $child.lYOFFV -column 1 -row 5

      #Laminate Density
      euidl::label $child.lLDEN -height 2 -anchor w \
           -text [msgcat::mc  "Laminate Density            =  "]
      grid $child.lLDEN -column 0 -row 6
      euidl::label $child.lLDENV -height 2 -anchor w \
           -text [msgcat::mc  "-"]
      grid $child.lLDENV -column 1 -row 6

     update idletasks
         
      set treeChildsite $child
   }

   proc initable {} {

       variable tbdata
       variable shelldatatable
       variable numCol
       variable numRow
       variable pictureUpdateTable
       variable alreadyTraced

       set $numRow 0
       set $numCol 0
       set tbdata(0,-1) "0"
       #set all Columns Labels that you are going to create
       set tbdata(-1,0) "Thickness"
       set tbdata(-1,1) "Material ID"
       set tbdata(-1,2) "Orientation" 
       set tbdata(-1,3) "Integration Pts"
       set tbdata(-1,4) "Pictorial View"

       $shelldatatable configure -rows [expr $numRow+1] -cols  [expr $numCol +1]
       $shelldatatable width -1 4

       $shelldatatable tag cell disabledtitle 0,-1
#       $shelldatatable tag cell disabled 0,0

   }

   proc clearSection {} {
      variable numRow
      variable sectionname
      variable addedMassPerUnitArea
      variable drillStiffnessFactor
      variable membraneHGFactor
      variable bendingHGFactor
      variable tss11
      variable tss22
      variable tss12
      variable tbopt
      variable tboptkcn
      variable sectionOffset

      #clean up
      set oldNumRows $numRow
      for {set i 1} {$i<=$oldNumRows} {incr i 1} {
        delrow 0
      }

      set sectionname ""

      #Set all the page 2 values
      set addedMassPerUnitArea ""
      set drillStiffnessFactor ""
      set membraneHGFactor ""
      set bendingHGFactor ""
      set tss11 ""
      set tss22 ""
      set tss12 ""
      set tbopt "None defined"
      set tboptkcn 0
      set sectionOffset 1
   }

   proc newSection {} {
      variable sectionid
      clearSection
      set sectionid ""
      addrow 1
   }

   proc reload {} {
      variable shelldatatable
      variable page1

      # These were here for 5.7 bug combobox changes seem to have fixed
#      set child [$page1.frm1 component childsite]
#      update
#      focus -force $child.cmbboxsectionid
#      update
      filltable
   }

   proc filltable {} {
      variable parent
      variable labelin
      variable mat
      variable tbdata
      variable shelldatatable
      variable numCol
      variable numRow
      variable tbopt
      variable tboptkcn
      variable page1
      variable numberOfMaterials
      variable listOfMaterials
      variable sectionid
      variable sectionname
      variable sectionOffset
      variable uiSectionOffset
      variable addedMassPerUnitArea
      variable drillStiffnessFactor
      variable membraneHGFactor
      variable bendingHGFactor
      variable tss11
      variable tss22
      variable tss12
      variable pictureUpdateFlag
      variable alreadyTraced
      variable listOfTables
      variable twiceNumberOfTables
      variable listOfCSYS
      variable twiceNumberOfCSYS
      variable currow

      #check if the section is a shell section
      if { [info exists sectionid] != 0 } {

         if { $sectionid == "None defined" } {
            ans_senderror 2 "This is an invalid Section ID."
            return
         }

         if { [catch { set sid [ ans_evalexpr $sectionid ] }] } {
            ans_senderror 2 "This is an invalid Section ID."
            return
         }
 
         if { $sid <= 0 } {
            ans_senderror 2 "This is an invalid Section ID."
            return
         }

         if  { [catch { set sectiontype [ans_getvalue shell,$sectionid,type] }] } {
            set sectiontype "UNKNOWN"
            ans_senderror 2 "This is an invalid Section ID."
            return
         }

         # Must activate buttons at end - of before a return
         $parent configure \
            -okstate disabled \
            -cancelstate disabled

         if { $sectiontype == "SHEL    " } {
            #Flag to set picture update to false
            set pictureUpdateFlag 0
            #Switch off tracing to speed up loading of data
            if { $alreadyTraced == 1 } {
               trace vdelete ::euidl::element::shell::section::tbdata w [code updateImageByTrace]
               set alreadyTraced 0
            }

            #clean up
            clearSection

            set temp [ catch { set STTHK [ans_getvalue shell,$sectionid,prop,tthk]  }]
            if { $temp > 0 } {
               set STTHK 0.0
            }

            #Get the number of layers
            set temp [ catch { set numLayers [ans_getvalue shell,$sectionid,prop,nlay]  }]
            if { $temp > 0 } {
               set numLayers 0
            }

            set temp [ catch { set sectionname [ans_getvalue shell,$sectionid,name]  }]
            if { $temp > 0 } {
               set sectionname ""
            }

            set child [$page1.frm1 component childsite]

            # Loop through data
            set currow 0
            addrow $numLayers

            #index + 1 used used to avoid + operation to calculate index + 1
            for {set i 1} {$i <= $numLayers} {incr i 1} {
                set otheri [expr $numLayers - $i]
                set tbdata($otheri,0) [ans_getvalue shell,$sectionid,tabl,$i,1]
                set tbdata($otheri,1) [ans_getvalue shell,$sectionid,tabl,$i,2]
                set tbdata($otheri,2) [ans_getvalue shell,$sectionid,tabl,$i,3]
                set tbdata($otheri,3) [ans_getvalue shell,$sectionid,tabl,$i,4]
            }

            #Get the Section Offset Information
            set sectionOffset [ans_getvalue shell,$sectionid,prop,pos]
            if { $sectionOffset == 0 } {
               toggleUISecOffsetState
               set uiSectionOffset [ans_getvalue shell,$sectionid,prop,offz]
            }

            #Set the Section Function info
            #If the Section does not a Section Function this command return a "" I think
            set temp [ catch { set tbopt [ans_getvalue shell,$sectionid,prop,func] }]
            if { $temp != 0 } {
               set tbopt "None defined"
            }
            set tbopt [string trim $tbopt]

            set matching 0
            for { set i 1 } { $i < $twiceNumberOfTables } { incr i 2 } {
               set currentT [lindex $listOfTables $i]
               if { $currentT == $tbopt } {
                  set matching 1
               }
            }

            if { $matching == 0 } {
               set tbopt "None defined"
            }
            set tbopt [string trim $tbopt]

            set tboptkcn [ans_getvalue shell,$sectionid,prop,fkcn]
            for { set i 1 } { $i < $twiceNumberOfCSYS } { incr i 2 } {
               set currentT [lindex $listOfCSYS $i]
               if { [string is integer $currentT] } {
                  if { $currentT == $tboptkcn } {
                     set tboptkcn $currentT
                  }
              }
            }

            #User Define Parameters
            set addedMassPerUnitArea [ans_getvalue shell,$sectionid,prop,amas]
            set drillStiffnessFactor [ans_getvalue shell,$sectionid,prop,dstf]
            set membraneHGFactor     [ans_getvalue shell,$sectionid,prop,mscf]
            set bendingHGFactor      [ans_getvalue shell,$sectionid,prop,bscf]
            set tss11                [ans_getvalue shell,$sectionid,prop,ut11]
            set tss22                [ans_getvalue shell,$sectionid,prop,ut22]
            set tss12                [ans_getvalue shell,$sectionid,prop,ut12]
            #One more factor to be added

            set pictureUpdateFlag 1
            if { $alreadyTraced == 0 } {
               trace variable ::euidl::element::shell::section::tbdata w [code updateImageByTrace]
               set alreadyTraced 1
            }
            updateImages

            update idletasks

            update
#            focus $shelldatatable

            $shelldatatable selection clear all
            $shelldatatable selection set $currow,0
            $shelldatatable activate $currow,0
            $shelldatatable selection anchor $currow,0
            $shelldatatable see active

            after 125 [list focus -force $shelldatatable;update]

         } else {
            ans_senderror 2 "This is not a Shell Section."
         }
      }
      # Must activate buttons at end - of before a return
      $parent configure \
         -okstate normal \
         -cancelstate normal
   }
  
   #ADD A ROW IN THE TABLE#
   # Here we add a row at the bottom of the table and move the data
   # down appropriately
   proc addrow { numNewRows } {

      variable page1
      variable shelldatatable
      variable tbdata
      variable labelin
      variable numRow
      variable numCol
      variable tbopt
      variable tboptkcn
      variable alreadyTraced
      variable treeChildsite
      variable listOfMaterials
      variable numberOfMaterials
      variable pictureUpdateFlag
      
      set child [$page1.frm1 component childsite]

      #Insert a row after the currently selected one
      if {[catch {$shelldatatable index active row} currow]} {
        set currow 0
      }

      if { $currow == -1 } {
         set currow 0
      }

      #Add the necessary rows and comboboxes at the bottom
      for { set i 0 } { $i < $numNewRows } { incr i 1 } {
         incr numRow

         #add a row at the bottom of the table
         $shelldatatable insert row -keeptitles -- [expr $numRow - 1] 1

         #Move the view to see added row
         $shelldatatable yview scroll 1 unit

         #Label this new row
         #since we are adding labels going "up" we will want to move all of
         #the labels down - and label row 1 equal to numRow

         set tbdata($numRow,-1) "$numRow"
         set lastrow [expr $numRow - 1]      

         $shelldatatable selection set [expr $currow +1],0
         $shelldatatable activate [expr $currow +1],0
         $shelldatatable selection anchor [expr $currow +1],0

         #Add the comboboxes to the last row only for the Material Type
         euidl::combobox  $child.matcb$lastrow
         $child.matcb$lastrow configure -command [code updateImageInRow $lastrow]
         $child.matcb$lastrow configure -variable [scope tbdata($lastrow,1)]
         $child.matcb$lastrow insert list end $listOfMaterials
         $shelldatatable window configure $lastrow,1 -window $child.matcb$lastrow
         bind $child.matcb$lastrow <Button-1>  [code unhighlightAll]

         #Add the comboboxes to the last row only for the Number of Integration Points
         euidl::combobox  $child.nipcb$lastrow
         $child.nipcb$lastrow configure -variable [scope tbdata($lastrow,3)]
         set numberOfIPList [list 1 1 3 3 5 5 7 7 9 9]
         $child.nipcb$lastrow insert list end $numberOfIPList
         $shelldatatable window configure $lastrow,3 -window $child.nipcb$lastrow
         bind $child.nipcb$lastrow <Button-1>  [code unhighlightAll]

         #Add a label for the preview picture
         euidl::button $child.prvbtn$lastrow -relief sunken
         $shelldatatable window configure $lastrow,4 -window $child.prvbtn$lastrow -sticky ew
         $shelldatatable window bind $child.matcb$lastrow $child.nipcb$lastrow \
               $child.prvbtn$lastrow
      }

      #Move the data down
      if {$numRow > 1} {
         #Move the data down
         for {set i $lastrow} { $i > $currow && $i != 0 } {set i [expr $i - 1]} {
            for {set j 0} {$j < 4} {incr j 1} {
               catch { set tbdata($i,$j) $tbdata([expr $i - $numNewRows],$j) }
            }
         }
      }
      
      #Now that the rows have been added. Renumber the -1 column to make it look
      #like everything is inverted
      for {set i 0} {$i < $numRow} {incr i 1} {
        set tempIndex [expr $numRow - $i]
        set tbdata($i,-1) "$tempIndex"
      }
      
      #Unset the newly added rows
      for {set i 0} {$i < $numNewRows } {incr i 1} {
         set crow [expr $i + $currow]
         catch { set tbdata($crow,0) 0.0 }
         catch { set tbdata($crow,1) [lindex $listOfMaterials 1]  }
         catch { set tbdata($crow,2) 0.0 }
         catch { set tbdata($crow,3) 3  }
      }

      update
      focus $shelldatatable

      $shelldatatable selection clear all
      $shelldatatable selection set $currow,0
      $shelldatatable activate $currow,0
      $shelldatatable selection anchor $currow,0
      $shelldatatable see active

      # Add delete buttons
      adddeleteButtonStateToggle      

  }

    #Returns the rows and columns selected#
    #default to the last one created#

   proc rowselect {} {

      variable shelldatatable
      variable numRow

      turnOffImageUpdating

      #create a list of sorted selected cells format {0,0 0,1 ....}
      set listcell [$shelldatatable curselection]
      set length [llength $listcell]

      #get the first cell and the last cell selected
      set first [lindex  $listcell 0]
      set lastind [expr $length -1]
      set last [lindex  $listcell $lastind]

      #get the first and the last row 
      set firstlis [split $first ,]
      set firstrow  [lindex  $firstlis 0]


      set lastlis [split $last ,]
      set lastrow  [lindex  $lastlis 0]


      if {$length == 0} {
         if {[catch {$shelldatatable index active row} firstrow]} {
            set firstrow 2
         }
         set lastrow $firstrow
      }

      #Delete all the rows selected
      for {set i $firstrow} { $i <= $lastrow && $numRow > 1 } {incr i 1} {
         delrow $firstrow
      }

      turnOnImageUpdating

      #Update Images in all the rows selected
      for {set i $firstrow} {$i < $numRow} {incr i 1} {
         updateImageInRow $i
      }
   }


   proc colselect {} {

      variable shelldatatable

       #create a list of sorted selected cells format {0,0 0,1 ....}
       set listcell [$shelldatatable curselection]
       set length [llength $listcell]

       #get the first cell and the last cell selected
       set first [lindex  $listcell 0]
       set lastind [expr $length -1]
       set last [lindex  $listcell $lastind]

       #get the first and the last row 
       set firstlis [split $first ,]
       set firstcol [lindex  $firstlis 1]

       set lastlis [split $last ,]
       set lastcol  [lindex  $lastlis 1]

       if {$length == 0} {
          if {[catch {$shelldatatable index active col} firstcol]} {
             set firstcol 2
          }
          set lastcol $firstcol
       }

       #Delete all the rows selected
       for {set i $firstcol} {$i <= $lastcol} {incr i 1} {
          delcolumn $firstcol
       }
        
   }


   #DELETE A ROW IN THE TABLE#

   proc delrow { currow } {

      variable shelldatatable
      variable labelin
      variable thiscol
      variable tbdata
      variable numRow
      variable numCol
      variable treeChildsite
        
      if {$numRow > 0} {
         #move all information up and delete row
         if {$numRow > 1} {
            #Move the data down
            for {set i $currow} {$i < [expr $numRow - 1]} {incr i 1} {
               for {set j 0} {$j < 4} {incr j 1} {
                  catch {set tbdata($i,$j) $tbdata([expr $i + 1],$j)}
                }
             }
         }

         # Delete the current row
         $shelldatatable delete rows -keeptitles -- [expr $numRow - 1] 1

         set numRow [expr $numRow - 1]
      } else {
         tk_messageBox -icon warning \
               -message [msgcat::mc "Cannot remove any more rows"]\
               -parent $treeChildsite
      }

      #renumber all the 0th cols
      for { set i 0} { $i < $numRow } { incr i 1} {
         set tbdata($i,-1) [expr $numRow - $i]
      }
        
      #disable or enable the add and delete buttons
      adddeleteButtonStateToggle
   }

   proc adddeleteButtonStateToggle {} {
      variable numRow
      variable page1

      set child [$page1.frm1 component childsite]
      if { $numRow < 2 } {
         $child.delrow configure -state disabled
      } else {
         $child.delrow configure -state normal
      }
   }

   proc updateImages {} {
      variable shelldatable
      variable page1
      variable numRow
      variable tbdata
      variable numberedEntityColors

      #Read the colors information
      readNumberedEntityColors

      set child [$page1.frm1 component childsite]

      for { set i 0 } { $i < $numRow } { incr i 1 } {
         updateImageInRow $i
      }
   }

   proc updateImageInRow { rowIndex } {
      variable shelldatable
      variable page1
      variable numRow
      variable tbdata
      variable numberedEntityColors
      variable loadedImages
      variable colorList
      
      if { $rowIndex > -1 && $rowIndex < $numRow } {

         set child [$page1.frm1 component childsite]

         #Calculate Angle/File Name
         if { [info exists tbdata($rowIndex,2)] == 1 } {
            set angle $tbdata($rowIndex,2)
            ::apdl::noerr 1
            if { [catch { set angle [ ans_evalexpr $angle ] }] } {
               set angle 0.0
            }
            ::apdl::noerr 0
         } else {
            set angle 0
         }

         if { $angle > 0 } {
            set angle [expr $angle + .5]
         } elseif { $angle < 0 } {
            set angle [expr $angle - .5]
         }

         set angle [expr int($angle)]

         set temp [catch { set angle [ expr $angle % 180 ] } ]
         if { $temp } {
            set angle 0
         }

         if { $angle < 0 } {
            set angle [expr $angle + 180 ]
         }

         set angle [expr ( $angle + 2.5 ) / 5 ]
         set angle [expr int($angle)]
         set angle [expr $angle * 5]

         if { [info exists tbdata($rowIndex,1)] == 1 } {
            set matid $tbdata($rowIndex,1)
         } else {
            set matid 0
         }

         set eid 1
         set temp [catch { set eid [expr $matid % 11 ] } ]
         if { $temp } {
            set eid 0
         } else {
            set eid [expr $eid - 1 ]
            if { $eid == -1 } {
               set eid 10
            }
         }

         set curColor [lindex $numberedEntityColors $eid]
         set curColorIndex [expr int($curColor)]
         set color [lindex $colorList $curColorIndex]

         set iIndex [expr $angle / 5 ]
         set iIndex [expr $iIndex % 36]
         catch { set myimage [lindex $loadedImages $iIndex] }
         catch { $child.prvbtn$rowIndex configure -image $myimage }
         $child.prvbtn$rowIndex configure -background $color
         $child.prvbtn$rowIndex configure -foreground $color
      }
   }

   proc updateImageByTrace { myVar arrayIndex values } {
      variable pictureUpdateFlag

      #Read the colors information
      readNumberedEntityColors

      if { $arrayIndex != "active" && $pictureUpdateFlag == 1 } {
         scan $arrayIndex "%d,%d" xid yid
         if { $yid == 2 || $yid == 1 || $yid == 2 } {
            if { $xid > -1 } {
               updateImageInRow $xid
            }
         }
      }
   }
   
   #Verify if all the data is defined
   proc preprocessSummary {} {
      variable prepError
      variable tbdata
      variable sectionid
      variable sectionOffset
      variable sectionname
      variable numRow

     set prepError 0

      #checks in page1
      #Magic Number 4 for Max j comes from num of input cols
      for { set i 0} { $i < $numRow} {incr i 1} {
         for { set j 0} { $j < 4} {incr j 1} {
            set temp [info exists tbdata($i,$j)]
            if { $temp == 0 } {
               set prepError 1
            } else {
               if { $tbdata($i,$j) == "" } {
                  set prepError 1
               }
            }
         }
      }

      set temp [info exists sectionid]
      if { $temp == 0 } {
         set prepError 1
      }
      
      set temp [info exists sectionname]
      if { $temp == 0 } {
         set prepError 1
      }

      set temp [info exists sectionOffset]
      if { $temp == 0 } {
         ans_senderror 2 "Unable to prepare summary, \
                          No section offset data given"
      }

      if { $prepError == 1 } {
         ans_senderror 2 "Unable to prepare summary, Incomplete Data Set"
      }
   }

   proc toggleMenuBars { flag } {
      variable mframe

      $mframe.sectionebutton configure -state normal
      $mframe.sectiontbutton configure -state normal

      if { [ info exists flag ]} {
         if { $flag == 0 } {
            #enable edit and tools menu bar
            $mframe.sectionebutton configure -state disabled
            $mframe.sectiontbutton configure -state disabled
         }
      }
   }

   proc toggleInsertPasteMenuItems {} {
      #Disable Edit and Paste Menu Items
      variable mframe
      variable shelldatatable
      variable cp_r_min
      variable cp_r_max
      variable cp_c_min
      variable cp_c_max

      set copiedtableindices [$shelldatatable curselection]
      set firsttwo [lindex $copiedtableindices 0]
      set lasttwo [lindex $copiedtableindices end]
      scan $firsttwo "%d,%d" in_r_min in_c_min

      $mframe.sectionebutton.editmenu entryconfigure 1 -state disabled
      $mframe.sectionebutton.editmenu entryconfigure 2 -state disabled
      if [ catch {selection get} sel] {
         if [catch {selection get -selection CLIPBOARD} sel] {
            return
         }
      }

      if {[string match [mwinfo hull [focus -displayof $shelldatatable]] \
            $shelldatatable]} {
         $mframe.sectionebutton.editmenu entryconfigure 1 -state normal
         $mframe.sectionebutton.editmenu entryconfigure 2 -state normal
      }
   }

   proc b1EditButton {} {
      lowerEditButton
      toggleInsertPasteMenuItems
   }

   proc processSummaryPage {} {
      variable numRow
      variable page3
      variable sectionid
      variable fakeID
      variable fakeIDDefined
      variable numRow
      variable prepError

      toggleMenuBars 0

      set child [$page3.frm1 component childsite]

      set fakeIDDefined 0
      set maxSectionID 1

      set SNAME " "
      set STTHK 0.0
      set SNUML 0
      set SNSP 0
      set SECO 0.0
      set STS22 0.0
      set STS12 0.0
      set SLDEN 0.0

      #A catch is used here if sectionid's value is blank
      if { [catch { set formatlabel [format "%d" $sectionid] } ] } {
         set formatlabel ""
      }
      $child.lNIDLV configure -text [msgcat::mc "%s" $formatlabel]

      set formatlabel [format "%s" $SNAME]
      $child.lNAMEV configure -text [msgcat::mc "%s" $formatlabel]

      set formatlabel [format "%f" $STTHK]
      $child.lTTHKV configure -text [msgcat::mc "%s" $formatlabel]

      set formatlabel [format "%3d" $SNUML]
      $child.lNLAYV configure -text [msgcat::mc "%s" $formatlabel]

      set formatlabel [format "%3d" $SNSP]
      $child.lNSPV configure -text [msgcat::mc "%s" $formatlabel]

      if { $SECO == 0 } {
         set formatlabel [format "%f" $SECO]
      } elseif { $SECO == 1 } {
         set formatlabel "Mid-Plane"
      } elseif { $SECO == 2 } {
         set formatlabel "Top-Plane"
      } elseif { $SECO == 3 } {
         set formatlabel "Bottom-Plane"
      } else {
         set formatlabel "Error in Input"
      }
      $child.lYOFFV configure -text [msgcat::mc "%s" $formatlabel]

      set formatlabel [format "%f" $SLDEN]
      $child.lLDENV configure -text [msgcat::mc "%s" $formatlabel]

      #Write the information to the database and perform the
      #necessary queries. Always write the section data to a
      #fake section id and read the summary information This
      #is done to protect shell sections currently defined
      #from being edited. They are to be edited only when someone
      #hits the ok button
      set maxSectionID [ ans_evalexpr sectinqr(0,14) ]

      #Preprocess for Summary
      preprocessSummary      

      if { $numRow > 0 && $prepError == 0 } {
         #Add one to this make this the fake ID
         #ADD CODE HERE TO INCREMENT FAKE ID ONLY
         #IF NO DATA IN STORED IN THAT SPOT
         
         #check if the fake id is already used
         if { [info exists fakeID] != 1 } {
            set fakeID 1
         }

         #keep increasing the section id till u find one not used
         #hopefully there are no cases where some one creates
         #section 1 to 1 million, if that is the case we will use
         #max id
         for { set isIDUsed 1 } { $isIDUsed == 1 } {} {
            set isIDUsed [ ans_evalexpr sectinqr($fakeID,1) ]
            if { $isIDUsed != 0 } {
               set fakeID [expr $fakeID + 1]
            }
         }

         #write to DB
         set fakeIDDefined 1
         writeCompositeShellSectionToDB
         
         set sectionDefined [ans_evalexpr sectinqr($fakeID,1) ]
         #If such a section ID does not exist just put 0.0 in all
         #and send an error message.
         
         #defaults
         set SNAME " "
         set STTHK 0.0
         set SNUML 0
         set SNSP 0
         set SECO 0.0
         set STS22 0.0
         set STS12 0.0
         set SLDEN 0.0

         #Update all Summmary infomation
         #= zero implied it is undefined
         if { $sectionDefined != 0 && $numRow > 0 } {
            catch { set SNAME [ans_getvalue shell,$fakeID,name]  }
            catch { set STTHK [ans_getvalue shell,$fakeID,prop,tthk]  }
            catch { set SNUML [ans_getvalue shell,$fakeID,prop,nlay]  }
            catch { set SNSP  [ans_getvalue shell,$fakeID,prop,nsp]   }
            catch { set SECO [ans_getvalue shell,$fakeID,prop,pos]   }
            if { $STTHK > 0 } {
               catch { set SLDEN [ans_getvalue shell,$fakeID,prop,lden]  }
            }
         }

         #A catch is used here if sectionid's value is blank
         if { [catch { set formatlabel [format "%d" $sectionid] } ] } {
            set formatlabel ""
         }
         $child.lNIDLV configure -text [msgcat::mc "%s" $formatlabel]

         set formatlabel [format "%s" $SNAME]
         $child.lNAMEV configure -text [msgcat::mc "%s" $formatlabel]

         set formatlabel [format "%f" $STTHK]
         $child.lTTHKV configure -text [msgcat::mc "%s" $formatlabel]

         set formatlabel [format "%3d" $SNUML]
         $child.lNLAYV configure -text [msgcat::mc "%s" $formatlabel]

         set formatlabel [format "%3d" $SNSP]
         $child.lNSPV configure -text [msgcat::mc "%s" $formatlabel]

         if { $SECO == 0 } {
            catch { set SECO [ans_getvalue shell,$fakeID,prop,offz]   }
            set formatlabel [format "%f" $SECO]
         } elseif { $SECO == 1 } {
            set formatlabel "Mid-Plane"
         } elseif { $SECO == 2 } {
            set formatlabel "Top-Plane"
         } elseif { $SECO == 3 } {
            set formatlabel "Bottom-Plane"
         } else {
            set formatlabel "Error in Input"
         }
         $child.lYOFFV configure -text [msgcat::mc "%s" $formatlabel]

         set formatlabel [format "%f" $SLDEN]
         $child.lLDENV configure -text [msgcat::mc "%s" $formatlabel]

         #Now remove the data from the database
         if { $fakeIDDefined == 1 } {
            set fakeIDDefined 0
            catch { ans_sendcommand )sdelete,$fakeID,$fakeID,0 }
         }

      } else {
         set sectionDefined 0
      }

   }

   proc cancelShellSectionGUI {} {
      variable parent
      variable numRow
      variable tbdata
      variable cp_r_min
      variable cp_r_max
      variable cp_c_min
      variable cp_c_max
      variable sectionid
      variable sectionname
      variable tbdata
      variable addedMassPerUnitArea
      variable drillStiffnessFactor
      variable membraneHGFactor
      variable bendingHGFactor
      variable tss11
      variable tss22
      variable tss12
      variable compositeDensity
      variable sectionOffset
      variable uiSectionOffset
      variable listOfMaterials
      variable numberOfMaterials
      variable listOfTables
      variable twiceNumberOfTables
      variable listOfCSYS
      variable twiceNumberOfCSYS

      ans_sendcommand ) /go
      trace vdelete ::euidl::element::shell::section::sectionid w [code traceSectionID]
      catch { destroy $parent }

      catch { unset numRow                 }
      catch { unset tbdata                 }
      catch { unset parent                 }
      catch { unset cp_r_min               }
      catch { unset cp_r_max               }
      catch { unset cp_c_min               }
      catch { unset cp_c_max               }
      catch { unset parent                 }
      catch { unset numRow                 }
      catch { unset tbdata                 }
      catch { unset cp_r_min               }
      catch { unset cp_r_max               }
      catch { unset cp_c_min               }
      catch { unset cp_c_max               }
      catch { unset sectionid              }
      catch { unset sectionname            }
      catch { unset tbdata                 }
      catch { unset addedMassPerUnitArea   }
      catch { unset drillStiffnessFactor   }
      catch { unset membraneHGFactor       }
      catch { unset bendingHGFactor        }
      catch { unset tss11                  }
      catch { unset tss22                  }
      catch { unset tss12                  }
      catch { unset compositeDensity       }
      catch { unset sectionOffset          }
      catch { unset uiSectionOffset        }
      catch { unset listOfMaterials        }
      catch { unset numberOfMaterials      }
      catch { unset listOfTables           }
      catch { unset twiceNumberOfTables    }
      catch { unset listOfCSYS             }
      catch { unset twiceNumberOfCSYS      }

   }

   proc writeCompositeShellSectionToDB {} {
   
      variable parent
      variable labelin
      variable numCol
      variable numRow
      variable tbdata
      variable tbopt
      variable tboptkcn
      variable treeChildsite
      variable shelldatatable 
      variable sectionid
      variable sectionname
      variable sectionOffset
      variable uiSectionOffset
      variable fakeID
      variable fakeIDDefined

      #Varaible for the Section Function data
      variable listOfTables
      variable twiceNumberOfTables
      variable listOfCSYS
      variable twiceNumberOfCSYS
      
      #optional data
      variable addedMassPerUnitArea
      variable drillStiffnessFactor
      variable membraneHGFactor
      variable bendingHGFactor
      variable tss11
      variable tss22
      variable tss12
      variable qstatus

      focus -force $parent
      update

      set qstatus 1

      if { $fakeIDDefined == 0 } {
         set nolog ""
      } else {
         set nolog ")"
         ans_sendcommand )/nopr
      }

      #The undocumented secdata command is being used to input the
      #data. The syntax goes like this
      #-------------------------      
      # sect,#,shell,,name
      # secblock,#layers
      # t1, m1, o1, p1
      # t2, m2, o2, p2
      # t3, m3, o3, p3 ...
      #-------------------------      

      if { [info exists sectionid] != 0 } {
         if { [ catch { ans_evalexpr $sectionid } ] } {
            ans_senderror 2 "This is not a valid Section ID."
            return
         }
      } else {
            ans_senderror 2 "This is not a valid Section ID."
            return         
      }

      for { set i [expr $numRow - 1]} { $i >= 0 } { incr i -1 } {
         for { set j 0 } { $j < 4 } { incr j 1} {
            if {[catch { ans_evalexpr $tbdata($i,$j) } ]} {
               set erow [expr $numRow - $i]
               set ecol [expr $j + 1]
               ans_senderror 2 "Invalid Data in table row=$erow col=$ecol."
               set qstatus 1
               return
            }
         }
      }

      for { set i [expr $numRow - 1]} { $i >= 0 } { incr i -1 } {
            set ErrorThickness 0
            catch { set ErrorThickness [ ans_evalexpr $tbdata($i,0) ] }
            if { $ErrorThickness < 0 } {
               set erow [expr $numRow - $i]
               ans_senderror 2 "Invalid Thickness in table row=$erow ."
               set qstatus 1
               return
            }
      }

      if {[catch { ans_evalexpr $sectionOffset } ]} {
         ans_senderror 2 "Invalid Data for Section Offset."
         set qstatus 1
         return
      }

      if { $fakeIDDefined == 0 } {
         catch { set temp [ ans_sendcommand "$nolog" sect,$sectionid,shell,,$sectionname] }
      } else {
         catch { set temp [ ans_sendcommand "$nolog" sect,$fakeID,shell,,$sectionname] }
      }

      #loop through all layers
      for { set i [expr $numRow - 1]} { $i >= 0 } { incr i -1 } {
         #loop through data within each layer
         catch { set temp [ans_sendcommand "$nolog" secdata, \
                   $tbdata($i,0),$tbdata($i,1),$tbdata($i,2),$tbdata($i,3)]  }
      }

      #Section offset information
      #To be added user defined offset
      if { [info exists sectionOffset] == 0 } {
         #defaults
         set sectionOffset 1
      }

      set tempOffset "MID"
      if { $sectionOffset == 1 } {
         set tempOffset "MID"
      } 
      if { $sectionOffset == 2 } {
         set tempOffset "TOP"
      }
      if { $sectionOffset == 3 } {
         set tempOffset "BOT"
      } 
      if { $sectionOffset == 0 } {
         set tempOffset "USER"
         catch { set temp [ ans_sendcommand "$nolog" secoffset,$tempOffset,$uiSectionOffset] }
      } else {
         catch { set temp [ ans_sendcommand "$nolog" secoffset,$tempOffset] }
      }


      #Section Function
      if { $tbopt != "undefined" && $tbopt != "" && \
           $tbopt != "        " &&  $tbopt != "None defined" } {
         catch { set temp [ ans_sendcommand "$nolog" secf,%$tbopt%,$tboptkcn] }
      }
      
      catch { ans_sendcommand "$nolog" seccontrol,$tss11,$tss22,$tss12,\
                                 $addedMassPerUnitArea, \
                                 $membraneHGFactor, \
                                 $bendingHGFactor, \
                                 $drillStiffnessFactor }
      set qstatus 0
        
   }

   proc saveAndExit {} {
      variable sectionid
      variable fakeIDDefined
      variable numCol
      variable numRow
      variable tbdata
      variable parent                 
      variable cp_r_min               
      variable cp_r_max               
      variable cp_c_min               
      variable cp_c_max               
      variable parent                 
      variable numRow                 
      variable tbdata                 
      variable cp_r_min               
      variable cp_r_max               
      variable cp_c_min               
      variable cp_c_max               
      variable sectionid              
      variable sectionname            
      variable tbdata                 
      variable addedMassPerUnitArea   
      variable drillStiffnessFactor   
      variable membraneHGFactor       
      variable bendingHGFactor        
      variable tss11                  
      variable tss22                  
      variable tss12                  
      variable compositeDensity       
      variable sectionOffset          
      variable uiSectionOffset        
      variable listOfMaterials        
      variable numberOfMaterials      
      variable listOfTables           
      variable twiceNumberOfTables    
      variable listOfCSYS           
      variable twiceNumberOfCSYS    
      variable parent 
      variable qstatus

      #Save and Exit
      if { [info exists sectionid] != 0 } {
         if { [catch { ans_evalexpr $sectionid } ] } {
            ans_senderror 2 "This is not a valid Section ID."
            return
         }
      } else {
            ans_senderror 2 "This is not a valid Section ID."
            return         
      }

      writeCompositeShellSectionToDB

      if { $qstatus != 0 } {
         set qstatus 0
         return
      }


      #FINISH ONLY IF
      if { $fakeIDDefined != 1 } {
         ans_sendcommand ) /go
         #BEFORE YOU START WINDING UP.
         #DO A CHECK ON WHETHER THE INFORMATION WRITTEN IS VALID OR NOT
         trace vdelete ::euidl::element::shell::section::sectionid w [code traceSectionID]

         catch { destroy $parent              }
         catch { unset numRow                 }
         catch { unset numCol                 }
         catch { unset tbdata                 }
         catch { unset parent                 }
         catch { unset cp_r_min               }
         catch { unset cp_r_max               }
         catch { unset cp_c_min               }
         catch { unset cp_c_max               }
         catch { unset parent                 }
         catch { unset numRow                 }
         catch { unset tbdata                 }
         catch { unset cp_r_min               }
         catch { unset cp_r_max               }
         catch { unset cp_c_min               }
         catch { unset cp_c_max               }
         catch { unset sectionid              }
         catch { unset sectionname            }
         catch { unset tbdata                 }
         catch { unset addedMassPerUnitArea   }
         catch { unset drillStiffnessFactor   }
         catch { unset membraneHGFactor       }
         catch { unset bendingHGFactor        }
         catch { unset tss11                  }
         catch { unset tss22                  }
         catch { unset tss12                  }
         catch { unset compositeDensity       }
         catch { unset sectionOffset          }
         catch { unset uiSectionOffset        }
         catch { unset listOfMaterials        }
         catch { unset numberOfMaterials      }
         catch { unset listOfTables           }
         catch { unset twiceNumberOfTables    }
         catch { unset listOfCSYS             }
         catch { unset twiceNumberOfCSYS      }
         catch { unset parent }
      }
   }

   #function to read the numbered colors
   proc readNumberedEntityColors {} {
      variable numberedEntityColors
      variable numNumberedEntityColors

      set numNumberedEntityColors 11

      #Loop through the data structures to find out if they are defined.
      #Whatever this means
      set numberedEntityColors [list]
      set idefined 0
      for { set i 1 } { $i <= $numNumberedEntityColors } { incr i 1} {
             set id [expr 25 + $i]
             lappend numberedEntityColors [ans_getvalue common,,d2com,,int,$id]
      }
   }

   #function to get list of materials
   proc getMaterialList {} {

      variable listOfMaterials
      variable numberOfMaterials

     #set numberOfMaterials [ans_evalexpr mpinqr(0,0,12)]
     #set listOfMaterials [ans_getlist mat]
     #set maxMaterials [ans_evalexpr mpinqr(0,0,14)]

      #Get the number of materials      
      set maxMaterials [ans_evalexpr mpinqr(0,0,14)]
      set numberOfMaterials 0
      #Loop through the data structures to find out if they are defined.
      #Whatever this means
      set idefined 0
      for { set i 1 } { $i <= $maxMaterials } { incr i 1} {
         set defined [ ans_evalexpr mpinqr($i,0,1)]
         if { $defined == 1 } {
             set idefined [expr $idefined + 1]
            if { $idefined == 1 } {
               set listOfMaterials [list $i $i]
            } else {
                lappend listOfMaterials $i $i
            }
             set numberOfMaterials [expr $numberOfMaterials + 1]
          }
      }
   }

   proc reassignRow {} {
     variable shelldatatable
     variable tbdata
     variable numRow
     variable numCol

     if {[catch {$shelldatatable index active row} currow]} {
        set currow 1
     }

     set modifiedRow $currow
     set newValMRow $tbdata($currow,5)

      #check in the modifiedRow and the newValMRow are valid rows 
     if { $modifiedRow < $numRow && $modifiedRow >=0 \
          && $newValMRow < $numRow && $newValMRow >= 0 } {
         if { $newValMRow != $modifiedRow } {
            #Copy all newValMRow data to current row
            for { set i 0 } { $i < 5} { incr i 1} {
               set temp [catch [set tbdata($modifiedRow,$i) \
                                   $tbdata([expr $numRow - $newValMRow],$i)]]
            }
         }
     }
   }

   proc findRows {} {
      variable numRow
      variable tbdata
      variable shelldatatable

      variable thicknessInactive
      variable materialIDInactive
      variable orientationInactive
      variable numIPInactive

      variable findThicknessValue
      variable findMaterialIDValue
      variable findOrientationValue
      variable findNumIPValue
      variable page1

      $shelldatatable selection clear all
      set child [$page1.frm1 component childsite]

      #To be added
      #the parameter option can be NEXT or ALL
      
      #Go throuch each row and find out which layers match
      for { set i 0 } { $i < $numRow } { incr i 1 } {
         set matching 1

         # check if the thickness matches
         # if  !string match $thickness
         # info exists sC($cmd,$i,in)
         set isThere [catch {set thickness $findThicknessValue}]
         if { $findThicknessValue != "" } {
            if {  $thickness == $tbdata($i,0) && $matching == 1 } {
               set matching 1
            } else {
               set matching 0
            }
         }
         unset isThere

         set isThere [catch {set material $findMaterialIDValue}]
         if { $findMaterialIDValue != "" } {
            if {  $material == $tbdata($i,1) && $matching == 1 } {
               set matching 1
            } else {
               set matching 0
            }
         }
         unset isThere

         set isThere [catch {set orientation $findOrientationValue}]
         if { $findOrientationValue != "" } {
            if {  $orientation == $tbdata($i,2) && $matching == 1 } {
               set matching 1
            } else {
               set matching 0
            }
         }
         unset isThere

         set isThere [catch {set numIP $findNumIPValue}]
         if { $findNumIPValue != "" } {
            if {  $numIP == $tbdata($i,3) && $matching == 1 } {
               set matching 1
            } else {
               set matching 0
            }
         }
         unset isThere

         if { $matching == 1 } {
            highlightTableRow $i
         }
      }
      rehighlightComboBoxes
   }

   proc unhighlightAll {} {
      variable numRow
      variable shelldatatable
      variable page1
      variable tablewinColor
      set child [$page1.frm1 component childsite]

      $shelldatatable selection clear all
      unhighlightComboBoxes
   }

   proc unhighlightComboBoxes {} {
      variable numRow
      variable shelldatatable
      variable page1
      variable tablewinColor
      set child [$page1.frm1 component childsite]

      for { set i 0 } { $i < $numRow } { incr i 1 } {
         $child.matcb$i configure -entrybackground $tablewinColor
         $child.matcb$i configure -entryforeground black
         $child.nipcb$i configure -entrybackground $tablewinColor
         $child.nipcb$i configure -entryforeground black
      }
   }

   proc rehighlightComboBoxes {} {
      variable numRow
      variable shelldatatable
      variable page1
      variable tablewinColor
      set child [$page1.frm1 component childsite]
      
      for { set i 0 } { $i < $numRow } { incr i 1 } {

         if { [ $shelldatatable selection includes $i,1 ] == 1 } {
            $child.matcb$i configure -entrybackground black
            $child.matcb$i configure -entryforeground $tablewinColor
         } else {
            $child.matcb$i configure -entrybackground $tablewinColor
            $child.matcb$i configure -entryforeground black
         }

         if { [ $shelldatatable selection includes $i,3 ] == 1 } {
            $child.nipcb$i configure -entrybackground black
            $child.nipcb$i configure -entryforeground $tablewinColor
         } else {
            $child.nipcb$i configure -entrybackground $tablewinColor
            $child.nipcb$i configure -entryforeground black
         }
      }
   }

   proc highlightTableRow { i } {
      variable shelldatatable

      #Put information in the array that this row has been selected
      $shelldatatable selection set $i,0
      $shelldatatable selection set $i,1
      $shelldatatable selection set $i,2
      $shelldatatable selection set $i,3
   }

   proc unhighlightTableRow { i } {
      variable shelldatatable

      #Put information in the array that this row has been selected
      $shelldatatable selection clear $i,0
      $shelldatatable selection clear $i,1
      $shelldatatable selection clear $i,2
      $shelldatatable selection clear $i,3
   }

   proc replaceRow { row } {
      variable replaceThicknessValue
      variable replaceMaterialIDValue
      variable replaceOrientationValue
      variable replaceNumIPValue
      variable foundLayers
      variable tbdata
      variable shelldatatable
      variable numRow

      #Replace if highligted
      if { [$shelldatatable selection includes $row,0 ] == 1 } {
         if { [info exists replaceThicknessValue] } {
            if { $replaceThicknessValue != "" } {
               set tbdata($row,0) $replaceThicknessValue
            }
            $shelldatatable selection clear $row,0
         }
      }

      if { [$shelldatatable selection includes $row,1 ] == 1 } {
         if { [info exists replaceMaterialIDValue] } {
            if { $replaceMaterialIDValue != "" } {
              set tbdata($row,1) $replaceMaterialIDValue
            }
            $shelldatatable selection clear $row,1
         }
      }

      if { [$shelldatatable selection includes $row,2 ] == 1 } {
         if { [info exists replaceOrientationValue] } {
            if { $replaceOrientationValue != "" } {
              set tbdata($row,2) $replaceOrientationValue
            }
            $shelldatatable selection clear $row,2
         }
      }

      if { [$shelldatatable selection includes $row,3 ] == 1 } {
         if { [info exists replaceNumIPValue ] } {
            if { $replaceNumIPValue != "" } {
              set tbdata($row,3) $replaceNumIPValue
            }
            $shelldatatable selection clear $row,3
         }
      }
   }

   proc moveToNext {} {
      variable replaceIndex
      variable numRow
      variable shelldatatable
      variable foundLayers
      variable replaceIndex
      variable numRow

      set numMatchingLayers [llength $foundLayers]

      set foundNext 0
      for { set index $replaceIndex } \
          { $foundNext == 0 && $replaceIndex < $numRow } \
          { incr replaceIndex 1 } {
         if { [$shelldatatable selection includes $replaceIndex,0] == 1 } {
            set foundNext 1
         }
      }
   }

   proc replaceAll {} {
      variable numRow

      for { set i 0 } { $i < $numRow } { incr i 1 } {
         replaceRow $i
      }
      rehighlightComboBoxes
   }

   proc findDialog {} {
      
      variable findParent

      if [winfo exists .dialogssmfind] {
         # Set the display correctly
         $findParent activate
         return
      }

      set findParent [euidl::dialog .dialogssmfind -class EUIDL -grabwin this]

      $findParent configure \
                        -okcommand [code findOk] \
                        -cancelcommand [code findFinish] \
                        -helpcommand [list ans_loadhelp Hlp_G_STRSHELL_4]

      set child [$findParent component childsite]

      #SET WINDOW#

      wm minsize $findParent 500 100
    
      wm title $findParent [msgcat::mc "Find & Highlight"]

      #Construct a frame for the main menus
      set mframe [frame $child.mframe -class EUIDL]
      grid $mframe

      #Construct the entry boxes/comboboxes for the search and replace stuff.
      #There are four boxes/ 2 sets one for search and one for replace.
      euidl::label $child.findC1 -text [msgcat::mc  "Thickness"]
      grid $child.findC1            -column 2 -row 1 -columnspan 1

      euidl::label $child.findC2 -text [msgcat::mc  "Material ID"]
      grid $child.findC2            -column 3 -row 1 -columnspan 1

      euidl::label $child.findC3 -text [msgcat::mc  "Orientation"]
      grid $child.findC3            -column 4 -row 1 -columnspan 1

      euidl::label $child.findC4 -text [msgcat::mc  "Num Intgr Pts"]
      grid $child.findC4            -column 5 -row 1 -columnspan 1

      euidl::label $child.findLabel -text [msgcat::mc  "Find"]
      grid $child.findLabel            -column 1 -row 2 -columnspan 1

      euidl::entry $child.findThicknessEntry \
                   -variable [scope findThicknessValue]
      grid $child.findThicknessEntry   -column 2 -row 2 -columnspan 1

      euidl::entry $child.findMaterialIDEntry \
                   -variable [scope findMaterialIDValue]
      grid $child.findMaterialIDEntry  -column 3 -row 2 -columnspan 1

      euidl::entry $child.findOrientationEntry \
                  -variable [scope findOrientationValue]
      grid $child.findOrientationEntry -column 4 -row 2  -columnspan 1

      euidl::entry $child.findNumIPEntry \
                  -variable [scope findNumIPValue]
      grid $child.findNumIPEntry       -column 5 -row 2 -columnspan 1

      #Create Button for Find
      euidl::button $child.findbutton \
                  -text [msgcat::mc "Replace"] \
                  -command [ code closeFindOpenReplace]
      grid $child.findbutton -column 1 -row 3 -columnspan 1

      #Activate it for the first time
      $findParent activate
   }
   
   proc findFinish {} {
      variable findParent
      $findParent deactivate
   }

   proc findOk {} {
      variable findParent
      findRows
      $findParent deactivate
   }

   proc closeFindOpenReplace {} {
      findRows
      findFinish
      replaceDialog            
   }

   proc replaceDialog {} {
      
      variable replaceParent
      variable listOfMaterials

      if [winfo exists .dialogssmreplace] {
         # Set the display correctly
         $replaceParent activate
         return
      }

      set replaceParent [euidl::dialog .dialogssmreplace \
                         -class EUIDL -grabwin this]

      $replaceParent configure \
                        -okcommand [code replaceFinish] \
                        -cancelcommand [code replaceFinish] \
                        -helpcommand [list ans_loadhelp Hlp_G_STRSHELL_4]

      set child [$replaceParent component childsite]

      #SET WINDOW#

      wm minsize $replaceParent 500 100
    
      wm title $replaceParent [msgcat::mc "Find Replace Shell Table"]

      #wm minsize $replaceParent [winfo reqwidth $replaceParent] \
      #                    [expr [winfo reqheight $replaceParent] + 50]

      #Construct a frame for the main menus
      set mframe [frame $child.mframe -class EUIDL]
      grid $mframe

      euidl::label $child.replaceC1 -text [msgcat::mc  "Thickness"]
      grid $child.replaceC1            -column 2 -row 1 -columnspan 1

      euidl::label $child.replaceC2 -text [msgcat::mc  "Material ID"]
      grid $child.replaceC2            -column 3 -row 1 -columnspan 1

      euidl::label $child.replaceC3 -text [msgcat::mc  "Orientation"]
      grid $child.replaceC3            -column 4 -row 1 -columnspan 1

      euidl::label $child.replaceC4 -text [msgcat::mc  "Num Integr Pts"]
      grid $child.replaceC4            -column 5 -row 1 -columnspan 1

      #Construct the entry boxes/comboboxes for the search and replace stuff.
      #There are four boxes/ 2 sets one for search and one for replace.
      euidl::label $child.replaceLabel -text [msgcat::mc  "Replace"]
      grid $child.replaceLabel         -column 1 -row 2 -columnspan 1

      euidl::entry $child.replaceThicknessEntry \
                  -variable [scope replaceThicknessValue]
      grid $child.replaceThicknessEntry -column 2 -row 2 -columnspan 1

      euidl::combobox $child.replaceMaterialIDEntry \
                  -variable [scope replaceMaterialIDValue]
      grid $child.replaceMaterialIDEntry -column 3 -row 2 -columnspan 1
      $child.replaceMaterialIDEntry insert list end $listOfMaterials

      euidl::entry $child.replaceOrientationEntry \
                  -variable [scope replaceOrientationValue]
      grid $child.replaceOrientationEntry -column 4 -row 2 -columnspan 1

      euidl::combobox $child.replaceNumIPEntry \
                  -variable [scope replaceNumIPValue]
      grid $child.replaceNumIPEntry -column 5 -row 2 -columnspan 1
      set numberOfIPList [list 1 1 3 3 5 5 7 7 9 9]
      $child.replaceNumIPEntry insert list end $numberOfIPList

      #Create Button for Replace All
      euidl::button $child.replaceallbutton \
                     -text [msgcat::mc "Replace All"] \
                     -command [ code replaceAll]
      grid $child.replaceallbutton -column 1 -row 3 -columnspan 1

      #Activate it for the first time
      $replaceParent activate
   }


   proc replaceFinish {} {
      variable replaceParent
      $replaceParent deactivate
   }

   #Procedure to apply symmetry on existing layer information
   proc applySymmetry {} {
      variable numRow
      variable shelldatatable
      variable tbdata

     $shelldatatable activate 0,0 
     $shelldatatable selection anchor 0,0
     $shelldatatable see active

     #Apply symmetry on 
     set oldNumRow $numRow

     $shelldatatable activate 0,0 
     $shelldatatable selection anchor 0,0
     $shelldatatable see active
     addrow $oldNumRow

     for { set i 0} { $i < $oldNumRow } { incr i 1 } {
        set old [expr $numRow - $i -1]
        copyDataRowToRow $old $i
     }
   }
   
   #Procedure to apply symmetry on existing layer information
   proc applyAntiSymmetry {} {
      variable numRow
      variable tbdata
      variable shelldatatable

      $shelldatatable activate 0,0 
      $shelldatatable selection anchor 0,0
      $shelldatatable see active

      #Apply symmetry on 
      set oldNumRow $numRow

         $shelldatatable activate 0,0 
         $shelldatatable selection anchor 0,0
         $shelldatatable see active
         addrow $oldNumRow

      for { set i 0} { $i < $oldNumRow } { incr i 1 } {
         set old [expr $numRow - $i -1]
         copyDataRowToRow $old $i
         catch { set tbdata($i,2) [expr -1 * [ans_evalexpr $tbdata($old,2)]] }
      }
   }

   proc copyDataRowToRow { old new } {
      variable tbdata
      for { set i 0 } { $i < 4 } { incr i 1 } {
         catch { set tbdata($new,$i) $tbdata($old,$i) }
      }
   }

   proc applyMakeNCopies {} {

      variable numberOfCopies
      variable numRow
      variable tbdata
      variable shelldatatable
      variable xeroxParent

      $shelldatatable activate 0,0 
      $shelldatatable selection anchor 0,0
      $shelldatatable see active

      #Before you do anything verify if any of the data are empty
      #if so do nothing
      set allOk 1
      for { set i 0 } { $i <  $numRow } { incr i 1} {
         for { set j 0 } { $j <  4 } { incr j 1 } {
            set temp [info exists tbdata($i,$j)]
            if { $temp != 1 } {
               set allOk 0
               puts "Error in code. Report to Ansys Support \n"
            }
         }
      }

      if { $allOk == 1 } {

         #Apply symmetry on 
         set oldNumRow $numRow

         $shelldatatable activate 0,0 
         $shelldatatable selection anchor 0,0
         $shelldatatable see active
         addrow [expr $oldNumRow * $numberOfCopies]

         for { set i 0} { $i < $oldNumRow } { incr i 1 } {
            set old [expr $numRow - $i - 1]
            for { set j 1} { $j <= $numberOfCopies } { incr j 1 } {
               set index [expr $i + ( $j * $oldNumRow ) ]
               set new [expr $numRow - $index - 1]
               copyDataRowToRow $old $new
            }
         }
      }
      
      #Done
      $xeroxParent deactivate
   }

   #Make N Copies of the Table
   #and paste it upwards
   proc makeNCopiesDialog {} {
      
      variable xeroxParent
      variable numberOfCopies

      if [winfo exists .ssxerox] {
         # Set the display correctly
         $xeroxParent activate
         return
      }

      set xeroxParent [euidl::dialog .ssxerox -class EUIDL -grabwin this]

      $xeroxParent configure \
                   -okcommand [code applyMakeNCopies] \
                   -cancelcommand [code cancelMakeNCopies] \
                   -helpcommand [list ans_loadhelp Hlp_G_STRSHELL_4]

      set child [$xeroxParent component childsite]

      #SET WINDOW#

      wm minsize $xeroxParent 100 100
    
      wm title $xeroxParent [msgcat::mc "Number of Copies"]

      #wm minsize $findParent [winfo reqwidth $replaceParent] \
      #                    [expr [winfo reqheight $replaceParent] + 50]

      #Construct a frame for the main menus
      set mframe [frame $child.mframe -class EUIDL]
      grid $mframe

      #Construct the entry boxes/comboboxes for the search and replace stuff.
      #There are four boxes/ 2 sets one for search and one for replace.
      euidl::label $child.ncopiesLabel -text [msgcat::mc  "Number of Copies"]
      grid $child.ncopiesLabel -column 1 -row 1 -columnspan 1

      euidl::entry $child.ncopiesEntry -variable [scope numberOfCopies]
      grid $child.ncopiesEntry   -column 2 -row 1 -columnspan 1

      #Activate it for the first time
      $xeroxParent activate
   }

   proc cancelMakeNCopies {} {
      variable xeroxParent
      $xeroxParent deactivate
   }

   proc copy_local {} {
      variable shelldatatable
      variable cp_r_min
      variable cp_r_max
      variable cp_c_min
      variable cp_c_max
      set copiedtableindices [$shelldatatable curselection]
      set firsttwo [lindex $copiedtableindices 0]
      set lasttwo [lindex $copiedtableindices end]
      scan $firsttwo "%d,%d" cp_r_min cp_c_min
      scan $lasttwo "%d,%d" cp_r_max cp_c_max
      euidl::EuidlTable::tk_tableCopy $shelldatatable
   }

   proc insert_local {} {
      variable shelldatatable
      variable cp_r_min
      variable cp_r_max
      variable cp_c_min
      variable cp_c_max
      variable currow

      set copiedtableindices [$shelldatatable curselection]
      set firsttwo [lindex $copiedtableindices 0]
      set lasttwo [lindex $copiedtableindices end]
      scan $firsttwo "%d,%d" in_r_min in_c_min
      scan $firsttwo "%d,%d" in_r_max in_c_max


      if { [info exists in_r_min] && [info exists in_c_min] && \
           [info exists in_r_max] && [info exists in_c_max] && \
           [info exists cp_r_max] && [info exists cp_r_min] } {

         #find the final mins
         if { $in_r_min < $in_r_max } {
            set final_r_min $in_r_min
         } else {
            set final_r_min $in_r_max
         }

         if { $in_c_min < $in_c_max } {
            set final_c_min $in_c_min
         } else {
            set final_c_min $in_c_max
         }

         set currow $final_r_min
         $shelldatatable selection set $final_r_min,$final_c_min
         $shelldatatable selection anchor $final_r_min,$final_c_min
         $shelldatatable activate $final_r_min,$final_c_min
         rehighlightComboBoxes

         #Number of rows to be added
         set tobeadded [ expr $cp_r_max - $cp_r_min + 1 ]
         addrow $tobeadded

         unhighlightAll

         focus $shelldatatable
         update
         euidl::EuidlTable::tk_tablePaste $shelldatatable
         rehighlightComboBoxes
      }
   }

   proc paste_local {} {
      variable shelldatatable
      focus $shelldatatable
      update
      euidl::EuidlTable::tk_tablePaste $shelldatatable
   }

   #Raise and Lower buttons on the pull down menu
   proc raiseSectionButton {} {
      variable mframe
      $mframe.sectionmbutton configure -relief raised
   }

   proc lowerSectionButton {} {
      variable mframe
      $mframe.sectionmbutton configure -relief flat
   }
   proc raiseEditButton {} {
      variable mframe
      $mframe.sectionebutton configure -relief raised
   }

   proc lowerEditButton {} {
      variable mframe
      $mframe.sectionebutton configure -relief flat
   }

   proc raiseToolsButton {} {
      variable mframe
      $mframe.sectiontbutton configure -relief raised
   }

   proc lowerToolsButton {} {
      variable mframe
      $mframe.sectiontbutton configure -relief flat
   }

   proc sectionIdUpdate {} {
      variable page1
      variable numberOfSections

      set child [$page1.frm1 component childsite]
      set listOfSections [ans_getlist sect]
      set twiceNumberOfSections [ llength $listOfSections ]
      if { $twiceNumberOfSections > 0 } {
         set first [lindex $listOfSections 0]
         if { $first == "None defined" } {
            set listOfSections [list "None defined" 0]
         }
      }

      catch { $child.cmbboxsectionid delete list 0 end }
      catch { $child.cmbboxsectionid insert list end $listOfSections }
   }

   proc toggleUISecOffsetState {} {
      variable page1
      variable sectionOffset
      variable uiSectionOffset
      set child [$page1.frm1 component childsite]
      #Section offset information
      #To be added user defined offset
      if { [info exists sectionOffset] == 1 } {
         if { $sectionOffset == 0 } {
            $child.p1SOffsetUInput configure -state normal
            $child.p1SOffsetUInputLabel configure -state normal
         } else {
            $child.p1SOffsetUInput configure -state disabled
            $child.p1SOffsetUInputLabel configure -state disabled
            set uiSectionOffset 0.0
         }
      } else {
         $child.p1SOffsetUInput configure -state disabled
         $child.p1SOffsetUInputLabel configure -state disabled
         set uiSectionOffset 0.0
      }
   }
}


