# ===========================================================================
#  Copyright 1999 SAS IP, Inc. Proprietary Data.
#  Unauthorized use, distribution, or duplication is prohibited.
#  All Rights Reserved.
# ============================================================================
#  $Revision: 145151 $
#  $Date: 2009-11-20 15:35:13 -0500 (Fri, 20 Nov 2009) $
# ============================================================================
# File Name:     DiscreteReinfSection.eui
# Description:   Define and Edit Discrete Reinforcement Section for ANSYS
# ============================================================================
package require msgcat

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

namespace eval ::euidl::element::discreinf::section {} {
      
   proc create {secIN} {
      variable parent
      variable childsite
      variable treeParent
      variable child
      variable left
      variable emptyfolder
      variable treeChildsite
      variable dbparent
      variable replaceParent
      variable findParent

      variable numCol
      variable numRow

      variable page1

      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
      variable sectionsubtype

      #Data used for storing information to input reinf data to Ansys
      #tbdata is a table of size numRow and numCols-?
      #Verify if these need a default value
      variable tbdata
      variable compositeDensity

      #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

      #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 findMaterialIDValue
      variable findAreaValue
      variable findPatternValue
      variable findV1Value
      variable findV2Value
      variable findV3Value
      variable findV4Value
      variable findV5Value
      variable findV6Value
      
      #Similarly replace**** represents the values that replace the
      #data in search
      variable replaceMaterialIDValue
      variable replaceAreaValue
      variable replacePatternValue
      variable replaceV1Value
      variable replaceV2Value
      variable replaceV3Value
      variable replaceV4Value
      variable replaceV5Value
      variable replaceV6Value
      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 materialIDInactive
      variable areaInactive
      variable patternInactive
      variable v1Inactive
      variable v2Inactive
      variable v3Inactive
      variable v4Inactive
      variable v5Inactive
      variable v6Inactive
      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
      
      #This is used to keep track of switching subtypes
      variable jumpingOut

      set qstatus 1
      set materialIDInactive 0
      set areaInactive 0
      set patternInactive 0
      set v1Inactive 0
      set v2Inactive 0
      set v3Inactive 0
      set v4Inactive 0
      set v5Inactive 0
      set v6Inactive 0
      set fakeIDDefined 0
      set numRow 0
      set numCol 0
      set alreadyTraced 0
      set jumpingOut 0

#      ans_greygui 0 0
#      ans_greygui 1 0
#      ans_greygui 3 0
#      ans_greygui 4 0

      if {[winfo exists .dlgDiscreteReinfSectionGUI]} {
            wm deiconify $parent
            raise $parent
            return
      }
     
    #  TABLE label secIN
      TABLE $secIN

      if {[winfo exists .dlgDiscreteReinfSectionGUI]} {
         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 TABLE {secIN} {
      
      variable sectionid
      variable numCol
      variable numRow
      variable tbdata
      variable tbopt
      variable colmax
      variable rowmax
      variable page1
      variable numberOfMaterials

      # colmax need a default
      set colmax 1000
      set rowmax 1000000 
     
      variable parent
      variable childsite
      #Handle to the table created for the reinf sections
      variable reinfdatatable
      variable mat
      variable treeChildsite
      variable confirm
      variable mframe

      variable alreadyTraced
      variable jumpingOut

      set mat $secIN
      set tbopt "None defined"

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


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

      set childsite [$parent component childsite]

      #SET WINDOW#

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

      $parent configure \
            -okcommand [code saveAndExit] \
            -cancelcommand [code cancelReinfSectionGUI] \
            -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

      set page1 [frame $childsite.hold -class EUIDL]
      pack $page1 -padx 10 -pady 10 -fill both -expand true

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

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

         update
         # Get the correct width of the widget
         set ndWidth [winfo reqwidth $page1]

         # Get the correct height of the widget
         set ndHeight [winfo reqheight $page1]

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

         $parent activate

         set sectionid $secIN
         # Check if it is a new section with no id
         if { $secIN == "NEW" } {
            newSection
            return
         }
         # Check if it is a new section with id
         if { [info exists sectionid] != 0 } {
            if { $sectionid != "None defined" } {
               if { ! [catch { set sectionid [ ans_evalexpr $sectionid ] }] } {
                  if { $sectionid > 0 } {
                     if { ! [ ans_evalexpr sectinqr($sectionid,1) ] } {
                        newSection
                        set sectionid $secIN
                        return
                     }
                  }
               }
            }
         }
                        
         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 reinf 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 reinf,$sectionid,type] }] } {
                                 if { $sectiontype == "REIN    " } {
                                    filltable
                                    if { $jumpingOut == 1 } {
                                       return
                                    }
                                    if {[winfo exists .dlgDiscreteReinfSectionGUI]} {
                                          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 $reinfdatatable]

      } else {
         ans_senderror 2 "Reinf Section GUI will not startup without any valid materials"
         cancelReinfSectionGUI
      }


   }

   proc menubars {} {

      variable parent
      variable childsite
      variable mframe
      variable sectionid
      variable findMaterialIDValue
      variable findAreaValue
      variable findPatternValue
      variable findV1Value
      variable findV2Value
      variable findV3Value
      variable findV4Value
      variable findV5Value
      variable findV6Value
      variable replaceMaterialIDValue
      variable replaceAreaValue
      variable replacePatternValue
      variable replaceV1Value
      variable replaceV2Value
      variable replaceV3Value
      variable replaceV4Value
      variable replaceV5Value
      variable replaceV6Value

      #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::discreinf::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 writeReinforcementSectionToDB]
      
      # 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 Multiple Copies" \
                             -command [code makeNCopiesDialog]
   }

   proc help {} {
      ans_loadhelp Hlp_G_STRREINF_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 reinf section
         if { $isValidID != 0 } {
            if  { [catch { set sectiontype [ans_getvalue reinf,$sectionid,type] }] } {
               set sectiontype "UNKNOWN"
            }
         } else {
            set sectiontype "UNKNOWN"
         }

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

   proc traceSectionID { myVar arrayIndex values } {
      greyOutPullDowns
   }

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

      #Varaible for the Section Function data
      variable listOfSections
      variable numberOfSections

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


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


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

      euidl::label $child.lblTop -height 3 \
           -anchor w \
           -text [msgcat::mc "      "]

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

      #Section Subtype
      #Label
      euidl::label $child.sectionsubtypelabel -height 3 \
           -text [msgcat::mc "Reinforcement Subtype"]
      grid $child.sectionsubtypelabel -column 3 -row 1 -sticky e
      #The Entry
      euidl::combobox  $child.cmbboxsectionsubtype \
                      -variable [scope sectionsubtype ] \
                      -style combobox
      set subtypelist [list Smeared SMEA Discrete DISC]
      $child.cmbboxsectionsubtype insert list end $subtypelist

      #Grid the section id entry
      grid $child.cmbboxsectionsubtype -column 4 -row 1 -sticky w
      $child.cmbboxsectionsubtype configure -command [code switchSubType]
      bind $child.cmbboxsectionsubtype <Return> { break }
      bind $child.cmbboxsectionsubtype <Leave> { break }

      #Name of the Section\
      #Label
      euidl::label $child.sectionnamelabel -height 3 \
           -text [msgcat::mc "Name"]
      grid $child.sectionnamelabel -column 5 -row 1 -sticky e
      #The Entry
      euidl::entry  $child.sectionnameentry -variable [scope sectionname ]
      #Grid the section id entry
      grid $child.sectionnameentry -column 6 -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 7 -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 8 -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 Reinforcement"] \
            -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 Reinforcement"] \
            -command [code rowselect ]
      grid $child.delrow -column 2 -row 3

      #Construct the Table
      set numCol 9
      set numRow 0

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

      $reinfdatatable config -rowmax 1000000

      set rowmax 1000000


      # FILL THE TABLE WITH EXISTING DATA IF TABLE EXISTS

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

      grid $reinfdatatable -sticky news -column 0 -row 2 -columnspan 9
      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 1
      grid columnconfigure $child 5 -weight 1
      grid columnconfigure $child 6 -weight 1
      grid columnconfigure $child 7 -weight 1
      grid columnconfigure $child 8 -weight 1

      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

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

      set tablewinColor [ $child.sectionnameentry cget -background ]

   }

   proc initable {} {

       variable tbdata
       variable reinfdatatable
       variable numCol
       variable numRow
       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) "Material ID"
       set tbdata(-1,1) "Area"
       set tbdata(-1,2) "Pattern"
       set tbdata(-1,3) "V1"
       set tbdata(-1,4) "V2"
       set tbdata(-1,5) "V3"
       set tbdata(-1,6) "V4"
       set tbdata(-1,7) "V5"
       set tbdata(-1,8) "V6"

       $reinfdatatable configure \
            -colwidth 11 -rows [expr $numRow+1] -cols  [expr $numCol +1]
       $reinfdatatable width -1 4

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

   }

   proc clearSection {} {
      variable numRow
      variable sectionname
      variable sectionsubtype
      variable tbopt

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

      set sectionname ""
      set sectionsubtype "DISC"

      #Set all the page 2 values
      set tbopt "None defined"
   }

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

   proc reload {} {
      variable reinfdatatable
      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 reinfdatatable
      variable numCol
      variable numRow
      variable tbopt
      variable page1
      variable numberOfMaterials
      variable listOfMaterials
      variable sectionid
      variable sectionname
      variable sectionsubtype
      variable alreadyTraced
      variable jumpingOut
      variable currow

      #check if the section is a reinf 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 reinf,$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 == "REIN    " } {

            catch { set sectionsubtype [ans_getvalue reinf,$sectionid,subtype] }
            switchSubType
            if { $jumpingOut == 1 } {
               return
            }

            #clean up
            clearSection

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

            set temp [ catch { set sectionname [ans_getvalue reinf,$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 $i - 1]
                set tbdata($otheri,0) [ans_getvalue reinf,$sectionid,tabl,$i,1]
                set tbdata($otheri,1) [ans_getvalue reinf,$sectionid,tabl,$i,2]
                set patternValue [ans_getvalue reinf,$sectionid,tabl,$i,3]
                if {$patternValue == 2} {
                   set tbdata($otheri,2) "EDGo"
                } elseif {$patternValue == 3} {
                   set tbdata($otheri,2) "LAYn"
                } elseif {$patternValue == 4} {
                   set tbdata($otheri,2) "BEAM"
                } elseif {$patternValue == 5} {
                   set tbdata($otheri,5) "GEN "
                } elseif {$patternValue == 6} {
                   set tbdata($otheri,2) "ARRA"
                } else {
                   set tbdata($otheri,2) "????"
                }
                set tbdata($otheri,3) [ans_getvalue reinf,$sectionid,tabl,$i,4]
                set tbdata($otheri,4) [ans_getvalue reinf,$sectionid,tabl,$i,5]
                set tbdata($otheri,5) [ans_getvalue reinf,$sectionid,tabl,$i,6]
                set tbdata($otheri,6) [ans_getvalue reinf,$sectionid,tabl,$i,7]
                set tbdata($otheri,7) [ans_getvalue reinf,$sectionid,tabl,$i,8]
                set tbdata($otheri,8) [ans_getvalue reinf,$sectionid,tabl,$i,9]
            }

            arrayPatternToggle
            #One more factor to be added

            update idletasks

            update
#            focus $reinfdatatable

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

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

         } else {
            ans_senderror 2 "This is not a Reinforcement Section."
         }
      }
      filterSubType

      # 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 reinfdatatable
      variable tbdata
      variable labelin
      variable numRow
      variable numCol
      variable tbopt
      variable alreadyTraced
      variable treeChildsite
      variable listOfMaterials
      variable numberOfMaterials
      
      set child [$page1.frm1 component childsite]

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

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

      if {$numRow > 0} {
         if {$tbdata(0,2) == "ARRA"} {
            tk_messageBox -icon warning \
                  -message [msgcat::mc "Cannot add any more rows.  Only 1 row is allowed with the ARRAY pattern."]\
                  -parent $treeChildsite
            return
         }
      }
      #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
         $reinfdatatable insert row -keeptitles -- [expr $numRow - 1] 1

         #Move the view to see added row
         $reinfdatatable 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]      

         $reinfdatatable selection set [expr $currow +1],0
         $reinfdatatable activate [expr $currow +1],0
         $reinfdatatable 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 -variable [scope tbdata($lastrow,0)]
         $child.matcb$lastrow insert list end $listOfMaterials
         $reinfdatatable window configure $lastrow,0 -window $child.matcb$lastrow
         bind $child.matcb$lastrow <Button-1>  [code unhighlightAll]

         #Add the comboboxes to the last row only for the Pattern
         euidl::combobox  $child.pattcb$lastrow
         $child.pattcb$lastrow configure -variable [scope tbdata($lastrow,2)]
         set patternList [list "Elem Edge" EDGo Layer LAYn "Beam Loc" BEAM]
         $child.pattcb$lastrow insert list end $patternList
         $reinfdatatable window configure $lastrow,2 -window $child.pattcb$lastrow
         if {$numRow < 2} {
            $child.pattcb$lastrow configure -command [code arrayPatternToggle]
            euidl::combobox  $child.v1table -variable [scope tbdata(0,3)] \
                                            -style combobox
            $reinfdatatable window configure 0,3 -window $child.v1table
            bind $child.v1table <Return> { break }
            euidl::combobox  $child.v1csys -variable [scope tbdata(0,4)] \
                                            -style combobox
            $reinfdatatable window configure 0,4 -window $child.v1csys
            bind $child.v1csys <Return> { break }
         }
         bind $child.pattcb$lastrow <Button-1>  [code unhighlightAll]

      }

      #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 < 9} {incr j 1} {
               catch { set tbdata($i,$j) $tbdata([expr $i - $numNewRows],$j) }
            }
         }
      }
      
      #Now that the rows have been added. Renumber the -1 column.
      for {set i 0} {$i < $numRow} {incr i 1} {
        set tempIndex [expr $i + 1]
        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) [lindex $listOfMaterials 1]  }
         catch { set tbdata($crow,1) 0.0 }
         catch { set tbdata($crow,2) EDGo }
         catch { set tbdata($crow,3) "" }
         catch { set tbdata($crow,4) "" }
         catch { set tbdata($crow,5) "" }
         catch { set tbdata($crow,6) "" }
         catch { set tbdata($crow,7) "" }
         catch { set tbdata($crow,8) "" }
      }

      update
      focus $reinfdatatable

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

      # Add delete buttons
      adddeleteButtonStateToggle      

  }

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

   proc rowselect {} {

      variable reinfdatatable
      variable numRow

      #create a list of sorted selected cells format {0,0 0,1 ....}
      set listcell [$reinfdatatable 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 {$reinfdatatable 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
      }

   }


   proc colselect {} {

      variable reinfdatatable

       #create a list of sorted selected cells format {0,0 0,1 ....}
       set listcell [$reinfdatatable 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 {$reinfdatatable 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 reinfdatatable
      variable labelin
      variable thiscol
      variable tbdata
      variable numRow
      variable numCol
      variable treeChildsite
      variable page1
        
      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 < $numCol} {incr j 1} {
                  catch {set tbdata($i,$j) $tbdata([expr $i + 1],$j)}
                }
             }
         }
         # Delete the current row
         $reinfdatatable 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 $i + 1]
      }
        
      #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
      }
      if { $numRow < 2 } {
         # remove the ARRAY choice from the first row
         set patternList [list "Elem Edge" EDGo Layer LAYn "Beam Loc" BEAM "Array" ARRA]
         catch { $child.pattcb0 delete list 0 end }
         catch { $child.pattcb0 insert list end $patternList }

      } else {
         # remove the ARRAY choice from the first row
         set patternList [list "Elem Edge" EDGo Layer LAYn "Beam Loc" BEAM]
         catch { $child.pattcb0 delete list 0 end }
         catch { $child.pattcb0 insert list end $patternList }
      }
   }

   proc arrayPatternToggle {} {

      variable reinfdatatable
      variable page1
      variable tbdata

      set child [$page1.frm1 component childsite]

      if {$tbdata(0,2) == "ARRA"} {
       #  return

         #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]
            }
         }
         catch { $child.v1table delete list 0 end }
         catch { $child.v1table insert list end $listOfTables }

         #Get the List of all Available ESYS
         set listOfCSYStemp [ ans_getlist csys ]
         set listOfCSYS [list]
         set twiceNumberOfCSYS [ llength $listOfCSYStemp ]
         for { set i 0 } { $i < $twiceNumberOfCSYS } { incr i 1 } {
            set thisword [lindex $listOfCSYStemp $i]
            set thisword [string trim $thisword]
            lappend listOfCSYS $thisword
         }
         catch { $child.v1csys delete list 0 end }
         catch { $child.v1csys insert list end $listOfCSYS }
      } else {
         catch { $child.v1table delete list 0 end }

      }

   }

   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 reinfdatatable
      variable cp_r_min
      variable cp_r_max
      variable cp_c_min
      variable cp_c_max

      set copiedtableindices [$reinfdatatable 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 $reinfdatatable]] \
            $reinfdatatable]} {
         $mframe.sectionebutton.editmenu entryconfigure 1 -state normal
         $mframe.sectionebutton.editmenu entryconfigure 2 -state normal
      }
   }

   proc b1EditButton {} {
      lowerEditButton
      toggleInsertPasteMenuItems
   }

   proc cancelReinfSectionGUI {} {
      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 sectionsubtype
      variable tbdata
      variable compositeDensity
      variable listOfMaterials
      variable numberOfMaterials

      ans_sendcommand ) /go
      trace vdelete ::euidl::element::discreinf::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 sectionsubtype         }
      catch { unset tbdata                 }
      catch { unset compositeDensity       }
      catch { unset listOfMaterials        }
      catch { unset numberOfMaterials      }

   }

   proc writeReinforcementSectionToDB {} {
   
      variable parent
      variable labelin
      variable numCol
      variable numRow
      variable tbdata
      variable tbopt
      variable treeChildsite
      variable reinfdatatable 
      variable sectionid
      variable sectionname
      variable sectionsubtype
      variable fakeID
      variable fakeIDDefined

      #optional data
      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,#,reinf,,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 < $numCol } { 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 0} { $i < $numRow } { incr i 1 } {
            set ErrorArea 0
            catch { set ErrorArea [ ans_evalexpr $tbdata($i,1) ] }
            if { $ErrorArea < 0 } {
               set erow [expr $i + 1]
               ans_senderror 2 "Invalid Area in table row=$erow ."
               set qstatus 1
               return
            }
      }

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

      #loop through all reinforcements
      for { set i 0} { $i < $numRow } { incr i 1 } {
         #loop through data within each layer
         if {$tbdata($i,2) == "ARRA"} {
            catch { set temp [ans_sendcommand "$nolog" secdata, \
                   $tbdata($i,0),$tbdata($i,1),$tbdata($i,2), \
                   %$tbdata($i,3)%,$tbdata($i,4)]  }
         } else {
            catch { set temp [ans_sendcommand "$nolog" secdata, \
                   $tbdata($i,0),$tbdata($i,1),$tbdata($i,2),$tbdata($i,3), \
                   $tbdata($i,4),$tbdata($i,5),$tbdata($i,6),$tbdata($i,7)]  }
         }
      }


      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 sectionsubtype
      variable tbdata                 
      variable compositeDensity       
      variable listOfMaterials        
      variable numberOfMaterials      
      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         
      }

      writeReinforcementSectionToDB

      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::discreinf::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 sectionsubtype         }
         catch { unset tbdata                 }
         catch { unset compositeDensity       }
         catch { unset listOfMaterials        }
         catch { unset numberOfMaterials      }
         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 reinfdatatable
     variable tbdata
     variable numRow
     variable numCol

     if {[catch {$reinfdatatable 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 reinfdatatable

      variable materialIDInactive
      variable areaInactive
      variable patternInactive
      variable v1Inactive
      variable v2Inactive
      variable v3Inactive
      variable v4Inactive
      variable v5Inactive
      variable v6Inactive

      variable findMaterialIDValue
      variable findAreaValue
      variable findPatternValue
      variable findV1Value
      variable findV2Value
      variable findV3Value
      variable findV4Value
      variable findV5Value
      variable findV6Value
      variable page1

      $reinfdatatable 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 area matches
         # if  !string match $area
         # info exists sC($cmd,$i,in)
         set isThere [catch {set area $findAreaValue}]
         if { $findAreaValue != "" } {
            if {  $area == $tbdata($i,1) && $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 pattern $findPatternValue}]
         if { $findPatternValue != "" } {
            if {  $pattern == $tbdata($i,2) && $matching == 1 } {
               set matching 1
            } else {
               set matching 0
            }
         }
         unset isThere

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

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

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

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

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

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

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

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

      $reinfdatatable selection clear all
      unhighlightComboBoxes
   }

   proc unhighlightComboBoxes {} {
      variable numRow
      variable reinfdatatable
      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.pattcb$i configure -entrybackground $tablewinColor
         $child.pattcb$i configure -entryforeground black
      }
   }

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

         if { [ $reinfdatatable 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 { [ $reinfdatatable selection includes $i,3 ] == 1 } {
            $child.pattcb$i configure -entrybackground black
            $child.pattcb$i configure -entryforeground $tablewinColor
         } else {
            $child.pattcb$i configure -entrybackground $tablewinColor
            $child.pattcb$i configure -entryforeground black
         }
      }
   }

   proc highlightTableRow { i } {
      variable reinfdatatable
      variable numCol

      #Put information in the array that this row has been selected
      for { set j 0 } { $j < $numCol } { incr j 1 } {
         $reinfdatatable selection set $i,$j
      }
   }

   proc unhighlightTableRow { i } {
      variable reinfdatatable
      variable numCol

      #Put information in the array that this row has been selected
      for { set j 0 } { $j < $numCol } { incr j 1 } {
         $reinfdatatable selection clear $i,$j
      }
   }

   proc replaceRow { row } {
      variable replaceMaterialIDValue
      variable replaceAreaValue
      variable replacePatternValue
      variable replaceV1Value
      variable replaceV2Value
      variable replaceV3Value
      variable replaceV4Value
      variable replaceV5Value
      variable replaceV6Value
      variable foundLayers
      variable tbdata
      variable reinfdatatable
      variable numRow

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

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

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

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

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

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

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

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

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

   proc moveToNext {} {
      variable replaceIndex
      variable numRow
      variable reinfdatatable
      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 { [$reinfdatatable 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_STRREINF_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  "Material ID"]
      grid $child.findC1            -column 2 -row 1 -columnspan 1

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

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

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

      euidl::label $child.findC5 -text [msgcat::mc  "V2"]
      grid $child.findC5            -column 6 -row 1 -columnspan 1

      euidl::label $child.findC6 -text [msgcat::mc  "V3"]
      grid $child.findC6            -column 7 -row 1 -columnspan 1

      euidl::label $child.findC6 -text [msgcat::mc  "V4"]
      grid $child.findC7            -column 8 -row 1 -columnspan 1

      euidl::label $child.findC6 -text [msgcat::mc  "V5"]
      grid $child.findC8            -column 9 -row 1 -columnspan 1

      euidl::label $child.findC7 -text [msgcat::mc  "V6"]
      grid $child.findC9            -column 10 -row 1 -columnspan 1

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

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

      euidl::entry $child.findAreaEntry \
                  -width 10 \
                  -variable [scope findAreaValue]
      grid $child.findAreaEntry   -column 3 -row 2 -columnspan 1

      euidl::entry $child.findPatternEntry \
                  -width 10 \
                  -variable [scope findPatternValue]
      grid $child.findPatternEntry  -column 4 -row 2 -columnspan 1

      euidl::entry $child.findV1Entry \
                  -width 10 \
                  -variable [scope findV1Value]
      grid $child.findV1Entry       -column 5 -row 2 -columnspan 1

      euidl::entry $child.findV2Entry \
                  -width 10 \
                  -variable [scope findV2Value]
      grid $child.findV2Entry       -column 6 -row 2 -columnspan 1

      euidl::entry $child.findV3Entry \
                  -width 10 \
                  -variable [scope findV3Value]
      grid $child.findV3Entry       -column 7 -row 2 -columnspan 1

      euidl::entry $child.findV4Entry \
                  -width 10 \
                  -variable [scope findV4Value]
      grid $child.findV4Entry       -column 8 -row 2 -columnspan 1

      euidl::entry $child.findV5Entry \
                  -width 10 \
                  -variable [scope findV5Value]
      grid $child.findV5Entry       -column 9 -row 2 -columnspan 1

      euidl::entry $child.findV6Entry \
                  -width 10 \
                  -variable [scope findV6Value]
      grid $child.findV6Entry       -column 10 -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_STRREINF_4]

      set child [$replaceParent component childsite]

      #SET WINDOW#

      wm minsize $replaceParent 500 100
    
      wm title $replaceParent [msgcat::mc "Find Replace Reinf 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  "Material ID"]
      grid $child.replaceC1            -column 2 -row 1 -columnspan 1

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

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

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

      euidl::label $child.replaceC5 -text [msgcat::mc  "V2"]
      grid $child.replaceC5            -column 6 -row 1 -columnspan 1

      euidl::label $child.replaceC6 -text [msgcat::mc  "V3"]
      grid $child.replaceC6            -column 7 -row 1 -columnspan 1

      euidl::label $child.replaceC7 -text [msgcat::mc  "V4"]
      grid $child.replaceC7            -column 8 -row 1 -columnspan 1

      euidl::label $child.replaceC8 -text [msgcat::mc  "V5"]
      grid $child.replaceC8            -column 9 -row 1 -columnspan 1

      euidl::label $child.replaceC9 -text [msgcat::mc  "V6"]
      grid $child.replaceC9            -column 10 -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::combobox $child.replaceMaterialIDEntry \
                  -width 10 \
                  -variable [scope replaceMaterialIDValue]
      grid $child.replaceMaterialIDEntry -column 2 -row 2 -columnspan 1
      $child.replaceMaterialIDEntry insert list end $listOfMaterials

      euidl::entry $child.replaceAreaEntry \
                  -width 10 \
                  -variable [scope replaceAreaValue]
      grid $child.replaceAreaEntry -column 3 -row 2 -columnspan 1

      euidl::combobox $child.replacePatternEntry \
                  -width 10 \
                  -variable [scope replacePatternValue]
      grid $child.replacePatternEntry -column 4 -row 2 -columnspan 1
      set patternList [list "Elem Edge" EDGo Layer LAYn "Beam Loc" BEAM]
      $child.replacePatternEntry insert list end $patternList

      euidl::entry $child.replaceV1Entry \
                  -width 10 \
                  -variable [scope replaceV1Value]
      grid $child.replaceV1Entry -column 5 -row 2 -columnspan 1

      euidl::entry $child.replaceV2Entry \
                  -width 10 \
                  -variable [scope replaceV2Value]
      grid $child.replaceV2Entry -column 6 -row 2 -columnspan 1

      euidl::entry $child.replaceV3Entry \
                  -width 10 \
                  -variable [scope replaceV3Value]
      grid $child.replaceV3Entry -column 7 -row 2 -columnspan 1

      euidl::entry $child.replaceV4Entry \
                  -width 10 \
                  -variable [scope replaceV4Value]
      grid $child.replaceV4Entry -column 8 -row 2 -columnspan 1

      euidl::entry $child.replaceV5Entry \
                  -width 10 \
                  -variable [scope replaceV5Value]
      grid $child.replaceV5Entry -column 9 -row 2 -columnspan 1

      euidl::entry $child.replaceV6Entry \
                  -width 10 \
                  -variable [scope replaceV6Value]
      grid $child.replaceV6Entry -column 10 -row 2 -columnspan 1

      #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
   }

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

   proc applyMakeNCopies {} {

      variable numberOfCopies
      variable numRow
      variable numCol
      variable tbdata
      variable reinfdatatable
      variable xeroxParent

      $reinfdatatable activate 0,0 
      $reinfdatatable selection anchor 0,0
      $reinfdatatable 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 <  $numCol } { 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

         $reinfdatatable activate 0,0 
         $reinfdatatable selection anchor 0,0
         $reinfdatatable 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_STRREINF_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 reinfdatatable
      variable cp_r_min
      variable cp_r_max
      variable cp_c_min
      variable cp_c_max
      set copiedtableindices [$reinfdatatable 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 $reinfdatatable
   }

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

      set copiedtableindices [$reinfdatatable 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
         $reinfdatatable selection set $final_r_min,$final_c_min
         $reinfdatatable selection anchor $final_r_min,$final_c_min
         $reinfdatatable 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 $reinfdatatable
         update
         euidl::EuidlTable::tk_tablePaste $reinfdatatable
         rehighlightComboBoxes
      }
   }

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

   #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 switchSubType {} {
      variable sectionsubtype
      variable sectionid
      variable jumpingOut

      if { $sectionsubtype == "SMEA    " } {
         set sectionsubtype "SMEA"
      }
      if { $sectionsubtype == "SMEA" } {
         set jumpingOut 1
         if { $sectionid == "" } {
            set sectionid "NEW"
         }
         ::euidl::element::reinf::section::create $sectionid
         ::euidl::element::discreinf::section::cancelReinfSectionGUI
         return
      }
   }

   proc filterSubType {} {
      variable sectionid
      variable page1

      set child [$page1.frm1 component childsite]
      $child.cmbboxsectionsubtype configure -state normal

      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 reinf,$sectionid,type] }] } {
                     # If a section exists in the database, you may not change the Subtype.
                     # Period
                     $child.cmbboxsectionsubtype configure -state disabled
                  }
               }
            }
         }
      }
   }
}


