#===========================================================================
#  Copyright 1999 SAS IP, Inc. Proprietary Data.
#  Unauthorized use, distribution, or duplication is prohibited.
#  All Rights Reserved.
# ============================================================================
#  $Revision: 662436 $
#  $Date: 2013-07-24 10:31:25 -0400 (Wed, 24 Jul 2013) $
# ============================================================================
# File Name:     MaterialCurveFit.eui
# Description:   Define Material Curve Fitting for ANSYS
# Authors:       jlo/rjayasee
# ============================================================================
#!/bin/sh


package require msgcat

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

image create photo mtlclose -file [file join $imagePath mtlclose16x16.png]
image create photo mtlopen  -file [file join $imagePath mtlopen16x16.png]
image create photo mtlicon  -file [file join $imagePath mtlicon16x16.png]

namespace eval ::euidl::material::CurveFit {} {

   variable matModelArr
   variable ::euidl::material::CurveFit::matModelArr

   option add *MatOpts*padX 5 startupFile
   option add *MatOpts*padY 3 startupFile
   option add *MatOpts*EuidlEntry*width 12 startupFile

   ::euidl::setImageDir [file join $env(EUIDL_DIR) gui \
         $::euidl::euidlArray(language) images]
   
   proc create {} {
      variable parent
      variable childsite
      variable treeParent
      variable child
      variable matid
      variable left
      variable treeMaterialParent
      variable treeFunctionParent
      variable modControlMenu
      variable emptyfolder
      variable treeChildsite
      variable matModelArr
      variable currentWorkDir
      variable ansysWorkDir
      variable exitFromCFITGUIFLAG
      variable funcDefnParams

      variable wizardStep
      variable wizardChoice
      variable summarystep
      variable combinationFunction
      variable optionalCaseName
      variable validAttribList
      variable DeleteCommandForLHSTree
      variable DeleteParamsForLHSTree
      
      variable fromMaterialGUI

      for { set index 0 } { $index < 50 } { incr index 1 } {
          variable xAxisLogToggleValue$index
          variable yAxisLogToggleValue$index
      }

      for { set index 1 } { $index < 50 } { incr index 1 } {
          variable expdata$index
          variable expattribdata$index
      }


      #Variable for defining additional tables
      variable coefftable
      variable numExpDataTables
      variable expFile
      variable pickedFileName
      variable currentExpIndex
      variable scrolledParent
      variable partialSolveParam
      variable partialSolveParamTable
      variable referenceTemperature
      variable browseparent
      variable experimentTempList
      variable graphParent
      variable detailedExpName
      variable detailedFuncName
      variable detailedGraphName
      variable graphArray
      variable InFunction
      variable CoeffSeed
      variable InWizardControlFunction
      variable CFTProgressDlg


      set InWizardControlFunction 0
      set InFunction 0
      set CoeffSeed(numcoeff) 1      

      set currentExpIndex 1
 #     ans_greygui 0 0
 #     ans_greygui 1 0
 #     ans_greygui 3 0
 #     ans_greygui 4 0
 
      set fromMaterialGUI 1

      CreateCombinationFunctionDatabase
      
      #Set the current dir
      set currentWorkDir [pwd]
      set ansysWorkDir [pwd]
      set partialSolveParam pvhe
      set partialSolveParamTable(0,0) 1
      set partialSolveParamTable(1,0) 1
      set partialSolveParamTable(2,0) 1
      
       if {[winfo exists .curvefittinggui]} {
             refresh
             wm deiconify $parent
             raise $parent
             ::uidl::registerWindow $parent 
             return
       }
      #BINDINGS#
     
      # The use of /NOPR and /GO should not be used the usage in this
      # file is very convoluted and so just get the value coming in
      # and set it back when exiting
      set matModelArr(printStatus) [ans_getvalue active,,prkey]


      #bind all <Alt-KeyPress-d> [code delete]
      #bind all <Alt-KeyPress-c> [code ans_sendcommand Fnc_CopyMatModel]
      #bind all <Alt-KeyPress-n> [code New]
  
      set emptyfolder [ list ]

 #     set parent [euidl::dialog .curvefittinggui -class EUIDL \
 #            -master NULL -width 800 -height 400 \
 #            -okbutton 0 -helpbutton 0 -cancelbutton 0 ]

      set parent [euidl::wizard .curvefittinggui -width 800 -height 500 ]
      $parent configure \
               -canceltext [msgcat::mc "Close"] \
               -finishbutton 0

      wizardstate "disabled"

     ::uidl::registerWindow $parent 
      set matModelArr(parent) $parent

      set childsite [$parent component childsite]
      wm title $parent [msgcat::mc "Define Material Model Behavior"]

      # Create the menubar
      set modControlMenu [menu $childsite.menubar]
      foreach m {Function Edit} {
           set $m [menu $modControlMenu.m$m -tearoff 0]
           $modControlMenu add cascade -label [msgcat::mc $m] \
             -menu $modControlMenu.m$m
      }
      $Function add command -label [msgcat::mc "New Model ..."] -command  [code New]
      $Function add command -label [msgcat::mc "Exit"] -command  [code exit]
      $Edit add command -label [msgcat::mc "Copy ..."] \
            -command  [ code  copy]
      $Edit add command -label [msgcat::mc "Delete"] \
            -command  [ code delete]
      $modControlMenu add command -label [msgcat::mc "Help"] \
            -command  [list ans_loadhelp Hlp_mcf]

      if {0} {
#        (only if wizard running outside material model)
         $parent config -menu $modControlMenu -cancelcommand [code exit]
      } else {
         $parent config -cancelcommand [code exit]
      }



        update idletasks
        wm minsize $parent [winfo reqwidth $parent] \
                          [winfo reqheight $parent]

     #   catch {$parent activate}
     #   $parent activate

   }
   
# --------------------------------------------------------------
#  Function Name: CancelFileBrowseWindow
#  Purpose:       Construct the Dialog to Browse for Files
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
proc CancelFileBrowseWindow {} {
   variable browseparent
   variable parent
   catch { lower $browseparent }
   catch { wm withdraw $browseparent }
   catch {   wm deiconify $parent  }
   catch {   raise $parent  }
   return
}

# --------------------------------------------------------------
#  Function Name: StatusBarControl
#  Purpose:       Construct Working Button
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
proc StatusBarControl { iState } {
   variable CFTProgressDlg
   variable parent
   
   if { $iState == 1 } {
       catch { destroy $CFTProgressDlg }
       set CFTProgressDlg [euidl::dialog .cftprogresswindow -class EUIDL -okbutton false -cancelbutton false -helpbutton false ]
       set child [$CFTProgressDlg component childsite]
       euidl::button $child.hourglass -text "Working ..."
       pack $child.hourglass -fill both -expand 1

       wm minsize $CFTProgressDlg [winfo reqwidth $CFTProgressDlg] \
                                  20
       wm title $CFTProgressDlg [msgcat::mc "Status Bar"]
       ::uidl::registerWindow $CFTProgressDlg
       set matModelArr(parent) $CFTProgressDlg

       lower $parent
       wm iconify $parent

       $CFTProgressDlg activate
       wm deiconify $CFTProgressDlg
       raise $CFTProgressDlg
       
       update
       #grab -global $CFTProgressDlg
   } elseif { $iState == 2 } {
        StatusBarControl 1
        set child [$CFTProgressDlg component childsite]
        $child.hourglass configure -text "Solution In Progress"
   } elseif { $iState == 3 } {
        set child [$CFTProgressDlg component childsite]
        $child.hourglass configure -text "Solution Completed"
        StatusBarControl 0
   } elseif { $iState == 4 } {
        set child [$CFTProgressDlg component childsite]
        $child.hourglass configure -text "Error in Solution"
        catch { destroy $CFTProgressDlg }
   } elseif { $iState == 5 } {
       catch { destroy $CFTProgressDlg }
       set CFTProgressDlg [euidl::dialog .cftprogresswindow -class EUIDL -okbutton false -cancelbutton false -helpbutton false ]
       set child [$CFTProgressDlg component childsite]
       ::uidl::registerWindow $CFTProgressDlg
       set matModelArr(parent) $CFTProgressDlg
       euidl::button $child.hourglass -text "Working ..."
       pack $child.hourglass -fill both -expand 1

       wm minsize $CFTProgressDlg [winfo reqwidth $CFTProgressDlg] \
                                  20
       wm title $CFTProgressDlg [msgcat::mc "Status Bar"]
       ::uidl::registerWindow $CFTProgressDlg
       set matModelArr(parent) $CFTProgressDlg

       $CFTProgressDlg activate
       wm deiconify $CFTProgressDlg
       raise $CFTProgressDlg
       
       update
       #grab -global $CFTProgressDlg
   } elseif { $iState == 6 } {
        catch { destroy $CFTProgressDlg }
        update
   } else {
       catch { destroy $CFTProgressDlg }
       wm deiconify $parent
       raise $parent
       update
   }
}

# --------------------------------------------------------------
#  Function Name: ToggleParentState
#  Purpose:       Construct Working Button
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
proc ToggleParentState { iState } {
   variable parent
   variable junklabel
   
   set child [$parent component childsite]
   set leftchild [$child.left component childsite]
   
   if { $iState == 1 } {
      $leftchild.curveFit configure -state disabled
      #grab set $parent.buttonBox
   } else {
      $leftchild.curveFit configure -state normal
      #catch { destroy $child.junk }
      #grab release $parent.buttonBox
   }
}

# --------------------------------------------------------------
#  Function Name: OpenCloseFileBrowseWindow
#  Purpose:       Construct the Dialog to Browse for Files
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
proc OpenCloseFileBrowseWindow { expType } {
   variable parent
   variable pickedFileName
   variable currentWorkDir
   
   set pickedFileName ""
   
   set types {
           {{All Files}    {*}}
   }
   set pickedFileName [::euidl::getOpenFile -parent $parent -filetypes $types -initialdir $currentWorkDir]
   
   if {![string match {} $pickedFileName]} {
      UpdateExperimentFileName $expType
   } else {
      CancelFileBrowseWindow
   }
}

# --------------------------------------------------------------
#  Function Name: OpenFileBrowseWindow
#  Purpose:       Construct the Dialog to Browse for Files
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
proc OpenFileBrowseWindow { expType } {

   variable browseparent
   variable pickedFileName
   variable currentWorkDir   
   if {[winfo exists .cftFileBrowseWindow]} {
       refresh
       wm deiconify .cftFileBrowseWindow
       raise .cftFileBrowseWindow
       ::uidl::registerWindow $browseparent 
       return
   }   

   set browseparent [euidl::dialog .cftFileBrowseWindow -class EUIDL \
      -master NULL -title [::msgcat::mc "Read Experiment From File"] ]
   $browseparent configure -okcommand [code UpdateExperimentFileName $expType ] \
                         -cancelcommand [ code CancelFileBrowseWindow ]   
   set childsite [ $browseparent component childsite ]
   
   set types {
           {{All Files}    {*}}
   }

   #Create the browse button
   euidl::fileinline $childsite.browseitem \
         -buttontext [::msgcat::mc "Browse ..."] \
         -filetypes $types \
         -oper "open" \
         -variable [scope pickedFileName ] \
         -type ansys   
   $childsite.browseitem configure -initialdir [scope currentWorkDir]
         
   # This is supposed to keep wizard on top after hitting browse
   if {[ans_getvalue common,,mccom,,int,16]} {
      set custwin .cftFileBrowseWindow
   } else {
      set custwin .cftFileBrowseWindow
      wm transient $custwin $AnsysGUI::ansGUIArray(parent)
      set geom [split [wm geometry $AnsysGUI::ansGUIArray(parent)] +-]
      set x [expr [lindex $geom 1] + 40]
      set y [expr [lindex $geom 2] + 100]
      if {$x > 0} { set x "+$x"}
      if {$y > 0} { set y "+$y"}
      #wm geometry $custwin "$x$y"
   }

   grid $childsite.browseitem -column 0 -row 0 -sticky nsew

   ::uidl::registerWindow $browseparent 

   refresh
   wm deiconify $browseparent
   raise $browseparent
   return
}

# --------------------------------------------------------------
#  Function Name: UpdateExperimentFileName
#  Purpose:       Updates and Loads the experiment file name
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
proc UpdateExperimentFileName { expType } {
   variable currentExpIndex
   variable pickedFileName
   variable scrolledParent
   variable browseparent
   variable parent
   variable expFile

   if { [info exists pickedFileName] } {
      if { [info exists currentExpIndex] } {
         set expFile($currentExpIndex) $pickedFileName
         set childsitescrolled [$scrolledParent childsite]
         LoadFileToTable $currentExpIndex $childsitescrolled $expType
      }
   }

   catch { lower $browseparent }
   catch { wm withdraw $browseparent }
   catch {   wm deiconify $parent  }
   catch {   raise $parent  }
}


# --------------------------------------------------------------
#  Function Name: createwithid
#  Purpose:       Set ID then call create procedure
#  Arguments:     current material id
#  Notes:         Called from material model gui
# 
# --------------------------------------------------------------
    proc createwithid {matin category} {
         
      variable parent
      variable wizardStep
      variable wizardChoice
      variable matidnew
      variable fromMaterialGUI
      variable matStates

      set fromMaterialGUI 1
      set matidnew $matin
      set wizardStep 0

      create

      set matStates(Hyper) 0
      set matStates(Visco) 0
      set matStates(Creep) 0
      set matStates(Plast) 0

      set matStates($category) 1

      BuildChoiceArray

      set wizardStep 1
      set procedure  [lindex $wizardChoice($wizardStep) 0]
      catch {set arguments  [lindex $wizardChoice($wizardStep) 1]}

      if [string match $arguments ""] {
         $procedure
      } else {
         $procedure $arguments
      }

      $parent configure \
         -prevcommand [code WizardControl -1] \
         -nextcommand [code WizardControl 1]

      $parent configure \
         -prevstate disabled
      update idletasks
      catch {$parent activate}
      refreshL
   }

# --------------------------------------------------------------
#  Function Name: createwithcurveid
#  Purpose:       Set ID then call create procedure
#  Arguments:     current material id
#  Notes:         Called from material model gui LHS experiment
#
# --------------------------------------------------------------
    proc createwithcurveid {matin expnum} {

      variable parent
      variable wizardStep
      variable wizardChoice
      variable matidnew
      variable fromMaterialGUI
      variable matStates

      set fromMaterialGUI 1
      set matidnew $matin
      set wizardStep 0

      create

      set matStates(Hyper) 0
      set matStates(Visco) 0
      set matStates(Creep) 0
      set matStates(Plast) 0

      set etype [ans_getvalue tbft,$matin,expe,$expnum,type]
      set etype [string trim $etype]

      if { [string equal -nocase UNIA $etype] } {
         set matStates(Hyper) 1
         set matStates(Plast) 1
         set bakWizardStep 1
         $parent configure -prevstate disabled
      } elseif { [string equal -nocase BIAX $etype] } {
         set matStates(Hyper) 1
         set bakWizardStep 3
      } elseif { [string equal -nocase SHEA $etype] } {
         set matStates(Hyper) 1
         set bakWizardStep 5
      } elseif { [string equal -nocase SSHE $etype] } {
         set matStates(Hyper) 1
         set bakWizardStep 7
      } elseif { [string equal -nocase VOLU $etype] } {
         set matStates(Hyper) 1
         set bakWizardStep 9
      } elseif { [string equal -nocase SDEC $etype] } {
         set matStates(Visco) 1
         set bakWizardStep 1
         $parent configure -prevstate disabled
      } elseif { [string equal -nocase BDEC $etype] } {
         set matStates(Visco) 1
         set bakWizardStep 3
      } elseif { [string equal -nocase CREEP $etype] } {
         set matStates(Creep) 1
         set bakWizardStep 1
      } else {
         set matStates(Hyper) 1
         set bakWizardStep 1
         $parent configure \
            -prevstate disabled
      }

      #Rebuild choice array
      set wizardStep 0
      BuildChoiceArray
      set wizardStep $bakWizardStep

      set procedure  [lindex $wizardChoice($wizardStep) 0]
      catch {set arguments  [lindex $wizardChoice($wizardStep) 1]}

      if [string match $arguments ""] {
         $procedure
      } else {
         $procedure $arguments
      }

      $parent configure \
         -prevcommand [code WizardControl -1] \
         -nextcommand [code WizardControl 1]

      update idletasks
      catch {$parent activate}
      refreshL
   }

# --------------------------------------------------------------
#  Function Name: createwithfunctionid
#  Purpose:       Set ID then call create procedure
#  Arguments:     current material id
#  Notes:         Called from material model gui LHS function
#
# --------------------------------------------------------------
    proc createwithfunctionid {matin funcnum} {

      variable parent
      variable wizardStep
      variable wizardChoice
      variable matidnew
      variable fromMaterialGUI
      variable matStates
      variable optionalCaseName
      variable summarystep

      variable cF
      variable editFunc

      set fromMaterialGUI 1
      set matidnew $matin
      set wizardStep 0

      create

      StatusBarControl 5

      if { ! [string equal -nocase -length 4 $funcnum "none"] } {
          set matStates(Hyper) 0
          set matStates(Creep) 0

          set editFunc $funcnum
          set fname [ans_getvalue tbft,$matin,func,$funcnum,fname]
          set fname [string trim $fname]
          set cF(HyperChoice) [FuncNameToCommand $fname]

          #If function name has a case in it turn on the visco option
          set caseList [ split $cF(HyperChoice) , ]
          set isCase [lindex $caseList 0]
          if { [string equal -nocase -length 4 $isCase "case" ] } {
              set optionalCaseName [lindex $caseList 1]
              set optionalCaseName [string trim $optionalCaseName]
          } elseif { [string equal -nocase -length 4 $isCase "Creep" ] } {
              set matStates(Creep) 1
          } else {
             set matStates(Hyper) 1
          }
      }

      BuildChoiceArray

      set wizardStep $summarystep

      set procedure  [lindex $wizardChoice($wizardStep) 0]
      catch {set arguments  [lindex $wizardChoice($wizardStep) 1]}

      if [string match $arguments ""] {
         $procedure
      } else {
         $procedure $arguments
      }

      #set wizardStep [expr $wizardStep + 1]

      #set procedure  [lindex $wizardChoice($wizardStep) 0]
      #catch {set arguments  [lindex $wizardChoice($wizardStep) 1]}

      #if [string match $arguments ""] {
      #   $procedure
      #} else {
      #   $procedure $arguments
      #}

      set editFunc -999

      $parent configure \
         -prevcommand [code WizardControl -1] \
         -nextcommand [code WizardControl 1]

      update idletasks
      

      if { ! [string equal -nocase -length 4 $funcnum "none"] } {
         set fname [ans_getvalue tbft,$matin,func,$funcnum,fname]
         set fname [string trim $fname]
         set cF(HyperChoice) [FuncNameToCommand $fname]

         ReadCoeffsFromDatabase $matin $fname
         UpdateCoeffTableParameters
      }

      refreshL

      StatusBarControl -1
   }

# --------------------------------------------------------------
#  Function Name: refreshL
#  Purpose:       Supposed to create left hand tree
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
    proc refreshL {} {
         
        variable treeMaterialParent 
        variable parent
        variable matid
            

#        if { ![catch {$treeMaterialParent expanded matroot_$matid} expanded] } {
#           if { !$expanded } {
#               catch {$treeMaterialParent expand matroot_$matid}
#           }
#        }
        if { [info exists treeMaterialParent ] } {
            $treeMaterialParent clear
            $treeMaterialParent draw
        }
        
        raise $parent
    }
    
    proc refresh {} {
        
         variable treeFunctionParent

     if { [info exists treeFunctionParent ] } {
        #$treeFunctionParent clear
        #$treeFunctionParent draw
     }

    }


    proc FuncSelection { node args } {
        variable treeFunctionParent

        if { [info exists treeFunctionParent ] } {
          $treeFunctionParent selection clear
          $treeFunctionParent selection add $node
        }     
    }
  
# 
# --------------------------------------------------------------
#  Function Name: setCurrentFunction
#  Purpose:       Set the current function to the tree node value
#  Arguments:     None
#  Notes:
#
# --------------------------------------------------------------
    proc setCurrentFunction { node args } {
       variable cF
       variable parent
       variable editFunc
       variable matid
       variable matStates
       variable InFunction

       if { $InFunction == 1 } {
          return
       }

       set InFunction 1

       if {$editFunc == -999} {
          set cF(HyperChoice) $node
       } else {
          set funcnum $editFunc
          set fname [ans_getvalue tbft,$matid,func,$funcnum,fname]
          set fname [string trim $fname]
          set cF(HyperChoice) [FuncNameToCommand $fname]
       }

       # Make sure that the choice is always set to a leaf.
       if {$node == "roothyper"} {
          set cF(HyperChoice) "HYPER,MOON,2"
       } elseif {$node == "HYPER,MOON,"} {
          set cF(HyperChoice) "HYPER,MOON,2"
       } elseif {$node == "HYPER,POLY,"} {
          set cF(HyperChoice) "HYPER,POLY,1"
       } elseif {$node == "HYPER,YEOH,"} {
          set cF(HyperChoice) "HYPER,YEOH,1"
       } elseif {$node == "HYPER,OGDE,"} {
          set cF(HyperChoice) "HYPER,OGDE,1"
       } elseif {$node == "HYPER,FOAM,"} {
          set cF(HyperChoice) "HYPER,FOAM,1"
       } elseif {$node == "rootvisco"} {
          set cF(HyperChoice) "VISCO,PVHE,"
       } elseif {$node == "VISCO,PVHE,"} {
          set cF(HyperChoice) "VISCO,PVHE,"
       } elseif {$node == "VISCO,PDEC,"} {
          set cF(HyperChoice) "VISCO,PDEC,"
       } elseif {$node == "CREEP,PRIM,"} {
          set cF(HyperChoice) "CREEP,SHAR,"
       } elseif {$node == "CREEP,SECO,"} {
          set cF(HyperChoice) "CREEP,GGAR,"
       } elseif {$node == "CREEP,PRSE,"} {
          set cF(HyperChoice) "CREEP,GTHA,"
       } elseif {$node == "rootcreep"} {
          set cF(HyperChoice) "CREEP,SHAR,"
       }
      
       #If it is a fcase stuff add to definition table
       if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {
          AppendToFunctionDefnTable
       }
       
       if { $matStates(Creep) == 1 } {
          set node $cF(HyperChoice)
       }

#       if { $matStates(Plast) == 1 } {
#          set node $cF(HyperChoice)
#       }

       #refreshL
       GetNumberOfCoefficients $node
       InitializeCoefficients
       InitializeCoefficientNames
       UpdateCoeffTableParameters
       NonLinearSettings
       refresh
       set InFunction 0
    }

# --------------------------------------------------------------
#  Function Name: OnFocusOutAfterEditFunctionParam
#  Purpose:       Loads the Right Hand Side of the Function Defn
#  Arguments:     None
#  Notes:
#
# --------------------------------------------------------------
proc OnFocusOutAfterEditFunctionParam {} {
   variable cF
   setCurrentFunction $cF(HyperChoice) ""
}
# --------------------------------------------------------------
#  Function Name: loadRightHandSide
#  Purpose:       Loads the Right Hand Side of the Function Defn
#  Arguments:     None
#  Notes:
#
# --------------------------------------------------------------
proc loadRightHandSide {} {

   variable cF
   variable parent
   variable editFunc
   variable matid

   set childsite [$parent component childsite]

   #Show Solution Data
   ShowSolutionData

   # show the advanced options
   NonLinearSettings
}

# --------------------------------------------------------------
#  Function Name: delete
#  Purpose:       Supposed to delete an item from the tree
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
    proc delete {} {
       variable matid
       variable label
       variable emptyfolder
      
       if { ![info exists label] } {
          return
       }

      refreshL
      refresh
             
    }

# --------------------------------------------------------------
#  Function Name: deletebyexpid
#  Purpose:       Delete an experiment by the list id
#  Arguments:     None
#  Notes:         Used by material model gui
#
# --------------------------------------------------------------
    proc deletebyexpid {matin expnum} {

      if { $expnum != "" } {
         set etype [ans_getvalue tbft,$matin,expe,$expnum,type]
         set etype [string trim $etype]
         ans_sendcommand tbft,edel,$matin,$etype
      }

    }

# --------------------------------------------------------------
#  Function Name: deletebyfuncid
#  Purpose:       Delete an function by the list id
#  Arguments:     None
#  Notes:         Used by material model gui
#
# --------------------------------------------------------------
    proc deletebyfuncid {matin funcnum} {

      if { $funcnum != "" } {
         set ftype [ans_getvalue tbft,$matin,func,$funcnum,fname]
         set ftype [string trim $ftype]
         set fcmd [FuncNameToCommand $ftype]
         ans_sendcommand tbft,fdel,$matin,$fcmd
      }

    }



# --------------------------------------------------------------
#  Function Name: copy
#  Purpose:       Supposed to copy one material to another
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
    proc copy {} {
      variable matid
      
      ans_sendcommand )/NOPR
      catch {ans_sendcommand )*SET,_zfromat,$matid}
      ans_sendcommand )/GO
      ::uidl::callFnc Fnc_CopyMatModel [namespace code copyCB ] 1
    }

# --------------------------------------------------------------
#  Function Name: copyCB
#  Purpose:       Copy dialog call back function
#  Arguments:     uidlButton (cancel,ok,apply)
#  Notes:         
# 
# --------------------------------------------------------------
     proc copyCB { uidlButton } {
        variable treeMaterialParent
        variable parent

        raise $parent
        if {$uidlButton != 1} {
           if { [info exists treeMaterialParent] } {
              $treeMaterialParent configure \
                 -querycommand [list [namespace code getCurveFitNodes] %n] \
                 -execcommand [list [namespace code select_Materialnode] %n %s]\
                 -selectcommand [list [namespace code Selection] %n %s]
           }
        } 
        if {$uidlButton == 2} {
             copy
        }    
    }

# --------------------------------------------------------------
#  Function Name: WizardControl
#  Purpose:       Control wizard callbacks and current step
#  Arguments:     direction (previous or next)
#  Notes:         previous goes back 2 steps, skipping 1
#                 next executes the next 2 steps, 1 callback
#                 and 1 to create next dialog
# 
# --------------------------------------------------------------
    proc WizardControl { direction } {

      variable parent
      variable wizardStep
      variable wizardChoice

      variable fromMaterialGUI
      variable InWizardControlFunction
      
      if { $InWizardControlFunction == 1 } {
         return
      }
      
      set InWizardControlFunction 1

      if {$direction == -1} {
         set wizardStep [expr $wizardStep + $direction]
         set wizardStep [expr $wizardStep + $direction]

         if { [catch {set procedure  [lindex $wizardChoice($wizardStep) 0]}] } {
            $parent configure -prevstate disabled
            return
         }

         catch {set arguments  [lindex $wizardChoice($wizardStep) 1]}

         $parent configure -prevstate disabled
         $parent configure -nextstate disabled

         if [string match $arguments ""] {
            $procedure
         } else {
            $procedure $arguments
         }
         if {$wizardStep == 1} {
            #grey out the previous button
            $parent configure \
               -prevstate disabled
         }
      } else {
         set wizardStep [expr $wizardStep + $direction]

         if { [catch { set procedure  [lindex $wizardChoice($wizardStep) 0] }] } {
            $parent configure -nextstate disabled
            return
         }

         catch {set arguments  [lindex $wizardChoice($wizardStep) 1]}

         $parent configure -prevstate disabled
         $parent configure -nextstate disabled

         if [string match $arguments ""] {
            $procedure
         } else {
            $procedure $arguments
         }


         set wizardStep [expr $wizardStep + $direction]

         set procedure  [lindex $wizardChoice($wizardStep) 0]
         catch {set arguments  [lindex $wizardChoice($wizardStep) 1]}

         if [string match $arguments ""] {
            $procedure
         } else {
            $procedure $arguments
         }
      }

      if [info exists wizardChoice([expr $wizardStep+1])] {
         $parent configure \
          -nextstate normal
      }
      if [info exists wizardChoice([expr $wizardStep-1])] {
         $parent configure \
          -prevstate normal
      }
      
      if {$fromMaterialGUI == 0 && $exitFromCFITGUIFLAG == 0 } {
         raise $parent
      }

      set InWizardControlFunction 0
    }


# --------------------------------------------------------------
#  Function Name: New
#  Purpose:       Create a new Material Model curve fit
#  Arguments:     None
# 
# --------------------------------------------------------------
    proc New {} {
      variable parent
      variable childsite
      variable emptyfolder
      variable matModelArr

      variable wizardStep
      variable wizardChoice
      variable matStates

      variable matidnew
      variable matid
      
   # Entry point for curve fit creation

      set wizardStep 1
      set wizardChoice(1) [list New]
      set wizardChoice(2) [list BuildChoiceArray]

      set matStates(Hyper) 1
      set matStates(Visco) 0
      set matStates(Creep) 0

      set childsite [$parent component childsite]
      if {[info exists childsite]} {
         destroy $childsite.newframe
      }

      set childsite [$parent component childsite]
      set parent1 [::euidl::labeledframe $childsite.newframe]
      $parent1 configure \
           -text [msgcat::mc "Specify Model Number"]
      grid $parent1 -column 1 -row 1 -sticky news

      unset childsite
      set childsite [$parent1 component childsite]

      set maxmat [expr [ans_evalexpr mpinqr(0,0,14)]]
      set matd 0
      if {$maxmat > 0} {
      set matincr 0
          while {$matincr <= $maxmat} {
             set modSelec [ans_evalexpr mpinqr($matincr,0,1)]
             if {$modSelec > 0} {
                set matd $matincr
             }
           incr matincr
           }
      }
      set matmaxi $matd
      foreach vari $emptyfolder {
           if { $vari >= $matd} {
              set matmaxi $vari
           }
      }
   
      set matidnew [expr $matmaxi + 1 ]
      
      euidl::label $childsite.lbl -height 3 -text [msgcat::mc " Define Material ID"]
      euidl::entry  $childsite.cmb -width 10 \
                 -variable [scope matidnew]


       grid $childsite.lbl -row 0 -column 0
       grid $childsite.cmb -row 0 -column 1

       wizardstate "normal" 

      $parent configure \
         -prevcommand [code WizardControl -1] \
         -nextcommand [code WizardControl 1]

       update idletasks

   }

# --------------------------------------------------------------
#  Function Name: BuildChoiceArray
#  Purpose:       Build the array of wizard function calls or
#                 the Previous and Next buttons
#  Arguments:     None
#  Notes:         Called by New
#                 Odd number WizardChoice steps always create 
#                 dialogs.
#                 Even number WizardChoice steps always perform
#                 functions.
# 
# --------------------------------------------------------------
   proc BuildChoiceArray {} {

      variable wizardStep
      variable wizardChoice
      variable matStates
      
      variable matidnew
      variable matid

      variable cF

      variable summarystep
      variable editFunc

      set editFunc -999

      set matid $matidnew

      set nextStep [expr $wizardStep + 1]

      if {$matStates(Hyper) == 1} {
         set wizardChoice($nextStep) [list AddExperimentData UNIA]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand UNIA]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list AddExperimentData BIAX]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand BIAX]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list AddExperimentData SHEA]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand SHEA]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list AddExperimentData SSHE]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand SSHE]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list AddExperimentData VOLU]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand VOLU]
         set nextStep [expr $nextStep + 1]
         set summarystep $nextStep
         set wizardChoice($nextStep) [list HyperChoiceTree]
         set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list MakeHyperFunc]
         #set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list SummaryPageForOneFunc]
         #set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list SaveOneFunc]
         set nextStep [expr $nextStep + 1]
         if { ! [info exists cF(HyperChoice)] } {
            set cF(HyperChoice) HYPER,MOON,2
         }
      }

      if {$matStates(Visco) == 1} {
         set wizardChoice($nextStep) [list AddExperimentData SDEC]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand SDEC]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list AddExperimentData BDEC]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand BDEC]
         set nextStep [expr $nextStep + 1]
         set summarystep $nextStep
         set wizardChoice($nextStep) [list HyperChoiceTree]
         set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list MakeHyperFunc]
         #set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list SummaryPageForOneFunc]
         #set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list SaveOneFunc]
         set nextStep [expr $nextStep + 1]
         set cF(HyperChoice) VISCO,HYPO,
      }

      if {$matStates(Creep) == 1} {
         set wizardChoice($nextStep) [list AddExperimentData CREEP]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand CREEP]
         set nextStep [expr $nextStep + 1]
         set summarystep $nextStep
         set wizardChoice($nextStep) [list HyperChoiceTree]
         set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list MakeHyperFunc]
         #set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list SummaryPageForOneFunc]
         #set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list SaveOneFunc]
         set nextStep [expr $nextStep + 1]
         set cF(HyperChoice) CREEP,SHAR,
      }

      if {$matStates(Plast) == 1} {
         set wizardChoice($nextStep) [list AddExperimentData UNIA]
         set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list ExperimentDataCommand UNIA]
         set nextStep [expr $nextStep + 1]
         set summarystep $nextStep
         set wizardChoice($nextStep) [list HyperChoiceTree]
         set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list MakeHyperFunc]
         #set nextStep [expr $nextStep + 1]
         #set wizardChoice($nextStep) [list SummaryPageForOneFunc]
         #set nextStep [expr $nextStep + 1]
         set wizardChoice($nextStep) [list SaveOneFunc]
         set nextStep [expr $nextStep + 1]
         set cF(HyperChoice) CASE,CPLA,
      }

#      set wizardChoice($nextStep) "ResultsPage"
#      set nextStep [expr $nextStep + 1]

#      set wizardChoice($nextStep) [list dummy_func]
#      set nextStep [expr $nextStep + 1]

#      set wizardChoice($nextStep) "SummaryPage"
#      set nextStep [expr $nextStep + 1]

#      set wizardChoice($nextStep) "PlotCurves"
#      set nextStep [expr $nextStep + 1]

      set wizardChoice($nextStep) "exit"

   }

# --------------------------------------------------------------
#  Function Name: getCurveFitData
#  Purpose:       create the tree for curve fit function selection
#  Arguments:     Node
#  Notes:        
#
# --------------------------------------------------------------
  proc getCurveFitData { matidlocal returnlabel } {

     variable mylist

     set matnum 1
     set mylist(root$matidlocal) [ list ]
     set maxMatlDef [ans_getvalue tbft,,nmat]

     set mylist(root$matidlocal) [ list none ]

     # Loop through each material model with a curve fit
     if {$maxMatlDef > 0} {
        while {$matnum <= $maxMatlDef} {
          set m [ans_getvalue tbft,,matnum,$matnum]
          set a root$m
          set b "Curve $m"

          if {$m == $matidlocal} { 
             set mylist(root$m) [ list ]
             lappend mylist(root$m) exp_$m  "Experiments"
             lappend mylist(root$m) func_$m "Curve Fits"

             # Loop through and get each constitutive function
             set mylist(func_$m) [ list ]
             set funcnum 1
             set maxFunc [ans_getvalue tbft,$m,nfun]
             set maxFunc [ans_evalexpr $maxFunc]
             while {$funcnum <= $maxFunc} {
                set f [ans_getvalue tbft,$m,func,$funcnum,fname]
                set f [string trim $f]
                set fuse [FuncNameToLabel $f]
                set mylist(func_${m}_$funcnum) [list ]
                lappend mylist(func_${m}) func_${m}_$funcnum "$fuse"
                incr funcnum
             }
             set functions $mylist(func_$m)

             # Loop through and get each experiment
             set mylist(exp_$m) [ list ]
             set experiments $mylist(exp_$m)
             set expnum 1
             set maxExp [ans_getvalue tbft,$m,nexp]
             set maxExp [ans_evalexpr $maxExp]
             while {$expnum <= $maxExp} {
                set e [ans_getvalue tbft,$m,expe,$expnum,type]
                set e [string trim $e]
                set euse [ExpNameToLabelWithId $e $expnum]
                set mylist(exp_${m}_$expnum) [list ]
                lappend mylist(exp_$m) exp_${m}_$expnum "$euse"
                incr expnum
                set experiments $mylist(exp_$m)
             }
          }

          incr matnum
        }
     }

     set folders $mylist(root$matidlocal)
     if { $returnlabel == "func" } {
        return $functions 
     } elseif { $returnlabel == "expe" } {
        return $experiments
     } else {
        return $folders
     }

}

# --------------------------------------------------------------
#  Function Name: getCurveFitNodes
#  Purpose:       Tree to traverse between different pages in
#                 in the CurveFitting GUI
#
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
 proc getCurveFitNodes { node } {

    variable mylist
    variable emptyfolder 
    variable treeMaterialParent
    variable matid

    set nodename [split $node _]
    set name  [lindex $nodename 0]
#        set matnum  [lindex $nodename 1]
    set matnum 1

    if {$node == "" } {
       set node root
       set matnum 1
    }


    # Loop through each material model with a curve fit
    set treematid $matid
    set a root$treematid
    set b "Curve $treematid"

    set mylist(root) [ list ]

    set mylist(matroot_$treematid)  [ list ]
    lappend mylist(root) [ list matroot_$treematid "Curve Fitting Data $treematid" ]
##
    set experiments [ list ]
    set curvefolders [ list ]
    set functions [ list ]
    set curvefolders [getCurveFitData $treematid folders ]

    if {$curvefolders != "none"} {
       set experiments [getCurveFitData $treematid expe ]
       set functions [getCurveFitData $treematid func ]

      set mylist(matroot_$treematid) [ list ]
       foreach {tag stuff} $curvefolders {
          lappend mylist(matroot_$treematid) [list $tag $stuff ]
       }

       set mylist(exp_$treematid) [ list ]
       set maxExp [ans_getvalue tbft,$treematid,nexp]
       set maxExp [ans_evalexpr $maxExp]
       if {$maxExp > 0} {
          foreach {tag stuff} $experiments {
             lappend mylist(exp_$treematid) [list $tag $stuff]
          }
       }

       set mylist(func_$treematid) [ list ]
       set maxFunc [ans_getvalue tbft,$matid,nfun]
       set maxFunc [ans_evalexpr $maxFunc]
       if {$maxFunc > 0} {
          foreach {tag stuff} $functions {
             lappend mylist(func_$treematid) [list $tag $stuff]
          }
       }
    }

    return $mylist($node)
}

# --------------------------------------------------------------
#  Function Name: Selection
#  Purpose:       Traverse the LHS Tree
#
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc Selection { node args } {
   variable treeMaterialParent
   variable matid
   variable label
   variable DeleteCommandForLHSTree
   variable DeleteParamsForLHSTree


   if { [info exists treeMaterialParent ] } {
     $treeMaterialParent selection clear
     $treeMaterialParent selection add $node
   }

   set DeleteCommandForLHSTree "return"
   
   switch -glob -- $node {
      func* {
         set paramlist [split $node _]
         set numParams [llength $paramlist]
         if { $numParams < 3 } {
            return 
         }
         set matid [lindex $paramlist 1]
         set funcindex [lindex $paramlist 2]
         if { [info exists funcindex] } {
            set DeleteCommandForLHSTree "deletebyfuncid"             
            set DeleteParamsForLHSTree "$matid $funcindex"
         }
      }
      exp* {
         set paramlist [split $node _]
         set numParams [llength $paramlist]
         if { $numParams < 3 } {
            return 
         }
         set matid  [lindex $paramlist 1]
         set expindex  [lindex $paramlist 2]
         if { [info exists expindex] } {
            set DeleteCommandForLHSTree "deletebyexpid"
            set DeleteParamsForLHSTree "$matid $expindex"
         }
      }
   }

}

#--------------------------------------------------------------
#  Function Name: select_LHSTreenode
#  Purpose:       Set the current function to the tree node value
#  Arguments:     None
#  Notes:
#
# --------------------------------------------------------------
proc select_LHSTreenode { node args } {
    variable matid
    variable cF
    variable matStates

   switch -glob -- $node {
      func* {
         set paramlist [split $node _]
         set curveuse  [lindex $paramlist 0]
         set matidnum  [lindex $paramlist 1]
         set funcnum  [lindex $paramlist 2]

         if {$funcnum != ""} {
           set editFunc $funcnum
           set fname [ans_getvalue tbft,$matid,func,$funcnum,fname]
           set fname [string trim $fname]
           set temp [FuncNameToCommand $fname]

           set cF(HyperChoice) $temp
           #If function name has a case in it turn on the visco option
           set caseList [ split $cF(HyperChoice) , ]
           set isCase [lindex $caseList 0]
           if { [string equal -nocase -length 4 $isCase "case" ] } {
               set fName [lindex $caseList 1]
               set ctype [ans_getvalue TBFT,$matid,FUNC,$fName,type]
               if {    [string equal -nocase -length 4 $ctype "pvhe" ] } {
                   set matStates(Visco) 1
                   set matStates(Plast) 0
               } 
               if {    [string equal -nocase -length 4 $ctype "chab" ] } {
                   set matStates(Visco) 0
                   set matStates(Plast) 1
               } 
           }
           createwithfunctionid $matid $funcnum
           update idletasks
         } else {
           createwithfunctionid $matid "none"
           update idletasks            
         }
      }
      exp* {
         set paramlist [split $node _]
         set numParams [llength $paramlist]
         set curveuse  [lindex $paramlist 0]
         set matindex  [lindex $paramlist 1]
         if { $numParams > 2 &&  $curveuse != "" } {
            set expindex  [lindex $paramlist 2]
            createwithcurveid $matid $expindex
         }
      }
   }


}

# --------------------------------------------------------------
#  Function Name: LHSCurveFittingTree
#  Purpose:       Tree to traverse between different pages in
#                 in the CurveFitting GUI
#
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc LHSCurveFittingTree {} {

   variable parent
   variable treeChildsite
   variable treeMaterialParent
   
   if { [info exist parent] } {
      set childsite [$parent component childsite]      
      set allchildren [winfo children $childsite]
      set position [lsearch $allchildren "$childsite.left"]
      if { $position > -1 } {
        grid $childsite.left -row 0 -column 0 -rowspan 4 -sticky news
        return
      }
   }
 
   if { ! [info exists treeChildSite] } {
      set childsite [$parent component childsite]        
      set left [euidl::labeledframe $childsite.left \
              -text [msgcat::mc "Material Models Defined"]]
      grid $left -row 0 -column 0 -rowspan 4 -sticky news
      set left [$left component childsite]
      grid  columnconfigure $childsite 1 -weight 2
      grid  columnconfigure $childsite 0 -weight 1
      grid  rowconfigure $childsite 1 -weight 1
      
      
      #Tree for the left side
      set treeMaterialParent [euidl::hierarchy $left.curveFit \
      -querycommand [list [namespace code getCurveFitNodes] %n] \
      -selectcommand [list [namespace code Selection] %n %s ] \
      -execcommand [list [namespace code select_LHSTreenode] %n %s] \
           -alwaysquery 1 \
           -closedicon mtlclose \
           -openicon mtlopen \
           -nodeicon mtlicon \
           -width 150 \
           -style single \
           -expanded 1 \
           -vscrollmode none \
           -contextmenu 1 \
           -borderwidth 1 \
           -height 250
      ]
      
      #Set the context menu
      set index 0
      $treeMaterialParent insertContextMenu $index command \
            -label [::msgcat::mc "Delete"] \
            -underline 0 \
            -command [namespace code DeleteItemInLHSTree]
      incr index
      
      #$treeMaterialParent insertContextMenu $index command \
            -label [::msgcat::mc "Plot"] \
            -underline 0 \
            -command [namespace code PlotItemInLHSTree]
      #incr index

      #grid $treeMaterialParent -sticky news  -row 0 -column 0
      pack $treeMaterialParent -fill both -expand 1   
      set treeChildsite $childsite
   }

}

# --------------------------------------------------------------
#  Function Name: DeleteItemInLHSTree
#  Purpose:       Delete an item in the LHS Tree
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc DeleteItemInLHSTree {} {
   variable  DeleteCommandForLHSTree
   variable  DeleteParamsForLHSTree
   
   if { [string equal -nocase $DeleteCommandForLHSTree "return"] } {
      return
   }
   
   set params [split $DeleteParamsForLHSTree]
   set numParams [llength $DeleteParamsForLHSTree]
   if { $numParams != 2 } {
      return
   }

   $DeleteCommandForLHSTree [lindex $params 0] [lindex $params 1]
   
   #update tree
   refreshL
   
   return
}

# --------------------------------------------------------------
#  Function Name: select_Materialnode
#  Purpose:       Executes when u select the item in the LHS Tree
#                 for the Material GUI
#  Arguments:     Node
#  Notes:        
#
# --------------------------------------------------------------
proc select_Materialnode { node args } {
    variable matid

    set paramlist [split $node _]
    set curveuse  [lindex $paramlist 0]
    set matuse  [lindex $paramlist 1]

    switch -glob -- $node {
             func* {
                if {$curveuse != ""} {
                  createwithfunctionid $matid $matuse
                }
             }
             exp* {
                if {$curveuse != ""} {
                  createwithcurveid $matid $matuse
                }
             }
    }


}



# --------------------------------------------------------------
#  Function Name: getFunctionNodes
#  Purpose:       create the tree for curve fit function selection
#  Arguments:     Node
#  Notes:        
#
# --------------------------------------------------------------
 proc getFunctionNodes { node} {

    variable matStates

#     set nodename [split $node _]
#     set name  [lindex $nodename 0]

    if {$node == "" } {
       set node root
    }


    if {$matStates(Hyper) == 1} {
       set funclist(root) [ list ]
       lappend funclist(root) [ list roothyper "Hyperelastic" ]
    }
    if {$matStates(Visco) == 1} {
       set funclist(root) [ list ]
       lappend funclist(root) [ list rootvisco "Viscoelastic" ]
    }
    if {$matStates(Creep) == 1} {
       set funclist(root) [ list ]
       lappend funclist(root) [ list rootcreep "Creep" ]
    }
    if {$matStates(Plast) == 1} {
       set funclist(root) [ list ]
       lappend funclist(root) [ list rootplast "Plasticity" ]
    }

    # hyperelastic tree
    set funclist(rootvisco) [ list  {VISCO,HYPO, "Hypo Visco Elastic"} ]

    #set funclist(rootvisco) [ list {VISCO,PDEC, "Prony Decay Series"} \
    #                                {VISCO,HYPO, "Hypo Visco Elastic"} \
    #                                {VISCO,HYPER, "Hyper Visco Elastic"} \
    #                        ]

    set funclist(VISCO,HYPO,)  [ list {VISCO,PSHEAR,UNDEF "Shear Terms"} \
                                      {VISCO,PBULK,UNDEF "Bulk Terms"} \
                                      {VISCO,SHIFT,UNDEF "Shift Terms"} \
                               ]

    set funclist(VISCO,PSHEAR,UNDEF)  [ list \
                                        {VISCO,PSHEAR,NONE "None"} \
                                        {VISCO,PSHEAR,1 "1  Term"} \
                                        {VISCO,PSHEAR,2 "2  Term"}\
                                        {VISCO,PSHEAR,3 "3  Term"}\
                                        {VISCO,PSHEAR,4 "4  Term"}\
                                        {VISCO,PSHEAR,5 "5  Term"}\
                                        {VISCO,PSHEAR,6 "6  Term"}\
                                        {VISCO,PSHEAR,7 "7  Term"}\
                                        {VISCO,PSHEAR,8 "8  Term"}\
                                        {VISCO,PSHEAR,9 "9  Term"}\
                                        {VISCO,PSHEAR,10 "10 Term"} \
                              ]

    set funclist(VISCO,PBULK,UNDEF)  [ list  \
                                        {VISCO,PBULK,NONE "None"} \
                                        {VISCO,PBULK,1 "1 Term"} \
                                        {VISCO,PBULK,2 "2 Term"} \
                                        {VISCO,PBULK,3 "3 Term"} \
                                        {VISCO,PBULK,4 "4 Term"} \
                                        {VISCO,PBULK,5 "5 Term"} \
                                        {VISCO,PBULK,6 "6 Term"} \
                                        {VISCO,PBULK,7 "7 Term"} \
                                        {VISCO,PBULK,8 "8 Term"} \
                                        {VISCO,PBULK,9 "9 Term"} \
                                        {VISCO,PBULK,10 "10 Term"} \
                              ]

    set funclist(VISCO,SHIFT,UNDEF)  [ list  {VISCO,SHIFT,NONE "No Shift"} \
                                       {VISCO,SHIFT,TN "Tool-NarayanaSwamy"} \
                                       {VISCO,SHIFT,WLF "WLF"} \
                              ]

    #Simple Prony Series
    set funclist(VISCO,PDEC,)  [ list {VISCO,ORDER, "Number of Terms"} \
                                      {VISCO,SHIFTP, "Shift Terms"} \
                               ]

    set funclist(VISCO,ORDER,)  [ list {VISCO,ORDER,1 "1 Term"} \
                                       {VISCO,ORDER,2 "2 Term"} \
                                       {VISCO,ORDER,3 "3 Term"} \
                                       {VISCO,ORDER,4 "4 Term"} \
                                       {VISCO,ORDER,5 "5 Term"} \
                              ]

    set funclist(VISCO,SHIFTP,)  [ list  {VISCO,SHIFTP,NONE "No Shift"} \
                                       {VISCO,SHIFTP,TN "Tool-NarayanaSwamy"} \
                                       {VISCO,SHIFTP,WLF "WLF"} ]

    # hyperelastic tree
    set funclist(roothyper) [ list {HYPER,MOON, "Mooney"} \
                                   {HYPER,OGDE, "Ogden"} \
                                   {HYPER,NEO, "Neo-Hookean"} \
                                   {HYPER,POLY, "Polynomial"} \
                                   {HYPER,BOYCE, "Arruda-Boyce"} \
                                   {HYPER,GENT, "Gent"} \
                                   {HYPER,YEOH, "Yeoh"} \
                                   {HYPER,BLAT, "Blatz-Ko (Foam)"} \
                                   {HYPER,FOAM, "Hyper Foam(Ogden Foam)"} \
                                   {HYPER,ETUB, "Extended Tube Model"} \
                            ]

    set funclist(HYPER,MOON,)  [ list {HYPER,MOON,2 "2 Parameter"} \
                                     {HYPER,MOON,3 "3 Parameter"} \
                                     {HYPER,MOON,5 "5 Parameter"} \
                                     {HYPER,MOON,9 "9 Parameter"} \
                              ]

    set funclist(HYPER,POLY,)  [ list {HYPER,POLY,1 "1st Order"} \
                                     {HYPER,POLY,2 "2nd Order"} \
                                     {HYPER,POLY,3 "3rd Order"} \
                              ]

    set funclist(HYPER,YEOH,)  [ list {HYPER,YEOH,1 "1st Order"} \
                                     {HYPER,YEOH,2 "2nd Order"} \
                                     {HYPER,YEOH,3 "3rd Order"} \
                              ]

    set funclist(HYPER,OGDE,)  [ list {HYPER,OGDE,1 "1st Order"} \
                                     {HYPER,OGDE,2 "2nd Order"} \
                                     {HYPER,OGDE,3 "3rd Order"} \
                              ]

    set funclist(HYPER,FOAM,)  [ list {HYPER,FOAM,1 "1st Order"} \
                                      {HYPER,FOAM,2 "2nd Order"} \
                                      {HYPER,FOAM,3 "3rd Order"} \
                              ]



    set funclist(HYPER,FOAM,)  [ list {HYPER,FOAM,1 "1st Order"} \
                                      {HYPER,FOAM,2 "2nd Order"} \
                                      {HYPER,FOAM,3 "3rd Order"} \
                              ]

    set funclist(HYPER,FOAM,)  [ list {HYPER,FOAM,1 "1st Order"} \
                                      {HYPER,FOAM,2 "2nd Order"} \
                                      {HYPER,FOAM,3 "3rd Order"} \
                              ]

    set funclist(HYPER,FOAM,)  [ list {HYPER,FOAM,1 "1st Order"} \
                                      {HYPER,FOAM,2 "2nd Order"} \
                                      {HYPER,FOAM,3 "3rd Order"} \
                              ]

    # Creep tree
    set funclist(rootcreep)    [ list {CREEP,PRIM, "Primary"} \
                                      {CREEP,SECO, "Secondary"} \
                                      {CREEP,PRSE, "Primary+Secondary"} \
                              ]

    set funclist(CREEP,PRIM,) [ list {CREEP,SHAR, "Strain Hardening"} \
                                   {CREEP,THAR, "Time Hardening"} \
                                   {CREEP,GEXP, "Generalized Exponential"} \
                                   {CREEP,GGRA, "Generalized Graham"} \
                                   {CREEP,GBLA, "Generalized Blackburn"} \
                                   {CREEP,MSHA, "Modified Strain Hardening"} \
                                   {CREEP,MTHA, "Modified Time Hardening"} \
                                   {CREEP,GTHA, "Generalized Time Hardening"} \
                             ]
    set funclist(CREEP,SECO,) [ list {CREEP,GGAR, "Generalized Garofalo"} \
                                    {CREEP,EXPO, "Exponential Form"} \
                                    {CREEP,NORT, "Norton"} \
                             ]
    set funclist(CREEP,PRSE,) [ list {CREEP,PSTH, "Time Hardening"} \
                                    {CREEP,PSRP, "Rational Polynomial"} \
                             ]

    # Plasticity tree
    set funclist(rootplast) [ list  {CASE,CPLA, "Plasticity"} ]
    
#    set funclist(CASE,PLAS)    [ list {PLAS,CHAB, "Chaboche Plasticity"} \
#                                      {CASE,CPLA, "Combined Plasticity"} \
#                               ]
#    set funclist(PLAS,CHAB,)   [ list {PLAS,CHAB,1 "1st Order"} \
#                                     {PLAS,CHAB,2 "2nd Order"} \
#                                     {PLAS,CHAB,3 "3rd Order"} \
#                                     {PLAS,CHAB,4 "4th Order"} \
#                              ]

    set funclist(CASE,CPLA,)  [ list  {PLAS,CHAB,UNDEF "Kinematic Hardening"} \
                                      {PLAS,MISO,UNDEF "Isotropic Hardening"} \
                              ]

    set funclist(PLAS,CHAB,UNDEF)  [ list \
                                        {PLAS,CHAB,1 "1  Term Chaboche"} \
                                        {PLAS,CHAB,2 "2  Term Chaboche"}\
                                        {PLAS,CHAB,3 "3  Term Chaboche"}\
                                        {PLAS,CHAB,4 "4  Term Chaboche"}\
                                        {PLAS,CHAB,5 "5  Term Chaboche"}\
                                        {PLAS,CHAB,6 "6  Term Chaboche"}\
                                        {PLAS,CHAB,7 "7  Term Chaboche"}\
                                        {PLAS,CHAB,8 "8  Term Chaboche"}\
                                        {PLAS,CHAB,9 "9  Term Chaboche"}\
                                        {PLAS,CHAB,10 "10 Term Chaboche"} \
                              ]

    #set betaKey [ans_getvalue active,,keyw,,beta]
    set betaKey 1
    if {$betaKey == 1} {
    set funclist(PLAS,MISO,UNDEF)  [ list  \
                                        {PLAS,CISO, "None"} \
                                        {PLAS,BISO, "Bilinear Isotropic"} \
                                        {PLAS,MISO,1 "1 Term Multilinear Isotropic "} \
                                        {PLAS,MISO,2 "2 Term Multilinear Isotropic "} \
                                        {PLAS,MISO,3 "3 Term Multilinear Isotropic "} \
                                        {PLAS,MISO,4 "4 Term Multilinear Isotropic "} \
                                        {PLAS,MISO,5 "5 Term Multilinear Isotropic "} \
                                        {PLAS,VOCE, "Voce Hardening Law"} \
                                        {PLAS,POWE, "Power Law"} \
                              ]
    } else {
    set funclist(PLAS,MISO,UNDEF)  [ list  \
                                        {PLAS,CISO, "None"} \
                              ]
    }


    if {$node == "" } {
       set node root
    }
    if {[string match {} [array names funclist $node]]} {
       return ""
    }

    return $funclist($node)
}

# --------------------------------------------------------------
#  Function Name: HyperChoiceTree
#  Purpose:       Dialog box to choose Hyperelastic models
#                 (Like HyperChoice but use a tree instead of radiobutton)
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
   proc HyperChoiceTree {} {
      variable parent
      variable childsite
      variable emptyfolder
      variable matModelArr
      variable expCurve
      variable cF
      variable matid
      variable optionalCaseName
      variable treeFunctionParent
      variable NLOpts 
      variable funcDefnParams
      variable funcDefnTable
      variable matStates
      variable InFunction
      
      set InFunction 0

      StatusBarControl 5

      $parent configure -helpcommand [list ans_loadhelp Hlp_mcf]
      $parent configure -nexttext [msgcat::mc "Save&Close"]

      set childsite [$parent component childsite]
      set allchildren [winfo children $childsite]

      if {[winfo exists $childsite.plotframe]} {
          destroy $childsite.plotframe
      }   

      if { [lsearch $allchildren "$childsite.expframe"] > -1 } {
           grid remove $childsite.expframe        
      }

      if { [lsearch $allchildren "$childsite.funcparamframe"] > -1 } {
           grid remove $childsite.funcparamframe        
      }

      if { [lsearch $allchildren "$childsite.nonlinearsettings"] > -1 } {
           grid remove $childsite.nonlinearsettings        
      }

      if { [lsearch $allchildren "$childsite.funcparamframe"] > -1 } {
           grid remove $childsite.funcparamframe        
      }

      if { [lsearch $allchildren "$childsite.funcdefframe"] > -1 } {
        CreateFunctionDefinitionMenuBar $childsite
        set funcdefframe $childsite.funcdefframe
        grid $childsite.funcdefframe -column 1 -row 0 -sticky news -rowspan 4
        grid columnconfigure $childsite 0 -weight 0
        grid columnconfigure $childsite 1 -weight 0
        grid columnconfigure $childsite 2 -weight 1
        grid columnconfigure $childsite 3 -weight 0
        grid columnconfigure $childsite 4 -weight 0
        grid columnconfigure $childsite 5 -weight 0
        
        if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {
           if { [info exists optionalCaseName] } {
              set fname [string trim $optionalCaseName]
              set cF(HyperChoice) [FuncNameToCommand $fname]
           } else {
                if { $matStates(Visco) == 1  } {
                   set fname "MYFIT"
                   set optionalCaseName "MYFIT"
                   set cF(HyperChoice) VISCO,PVHE
                }
                if { $matStates(Plast) == 1  } {
                   set fname "MYFIT"
                   set optionalCaseName "MYFIT"
                   set cF(HyperChoice) PLAS,CPLA
                }
           }
        } else {
           set fname [ CommandToFuncName $cF(HyperChoice) ]
        }
        
        ReadCoeffsFromDatabase $matid $fname
        UpdateCoeffTableParameters 
        set childsite [$childsite.funcdefframe component childsite]

        $childsite.function configure -querycommand [list [namespace code getFunctionNodes] %n] \
          -selectcommand [list [namespace code FuncSelection] %n %s ] \
          -execcommand [list [namespace code setCurrentFunction] %n %s]

      } else {     
      
         CreateFunctionDefinitionMenuBar $childsite
         LHSCurveFittingTree
         grid columnconfigure $childsite 0 -weight 0
         grid columnconfigure $childsite 1 -weight 0
         grid columnconfigure $childsite 2 -weight 1
         grid columnconfigure $childsite 3 -weight 0
         grid columnconfigure $childsite 4 -weight 0
         grid columnconfigure $childsite 5 -weight 0
        
         set childsite [$parent component childsite]
         set parent1 [::euidl::labeledframe $childsite.funcdefframe]
         $parent1 configure \
              -text [msgcat::mc "Solve for the Following Function"]
         grid $parent1 -column 1 -row 0 -sticky news -rowspan 4

         set childsite [$parent1 component childsite]

         set treeFunctionParent [euidl::hierarchy $childsite.function \
          -querycommand [list [namespace code getFunctionNodes] %n] \
          -selectcommand [list [namespace code FuncSelection] %n %s ] \
          -execcommand [list [namespace code setCurrentFunction] %n %s] \
               -alwaysquery 1 \
               -closedicon mtlclose \
               -openicon mtlopen \
               -nodeicon mtlicon \
               -width 250 \
               -height 250 \
               -borderwidth 1 \
               -style single
         ]

         grid $treeFunctionParent -sticky news  -row 0 -column 0 -columnspan 3
         grid rowconfigure $childsite 0 -weight 1
         grid columnconfigure $childsite 0 -weight 1
         grid rowconfigure $childsite 1 -weight 0

         set treeChildsite $childsite


         euidl::entry $childsite.funcname -variable [scope cF(HyperChoice)]
         #grid $childsite.funcname -row 1 -column 0 -columnspan 3
         bind $childsite.funcname <FocusOut> [code OnFocusOutAfterEditFunctionParam ]

        if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {
           if { [info exists optionalCaseName] } {
              set fname [string trim $optionalCaseName]
              set cF(HyperChoice) [FuncNameToCommand $fname]
           } else {
                if { $matStates(Visco) == 1  } {
                   set fname "MYFIT"
                   set optionalCaseName "MYFIT"
                   set cF(HyperChoice) VISCO,PVHE
                }
                if { $matStates(Plast) == 1  } {
                   set fname "MYFIT"
                   set optionalCaseName "MYFIT"
                   set cF(HyperChoice) PLAS,CPLA
                }
           }
        } else {
           set fname [ CommandToFuncName $cF(HyperChoice) ]
        }

      }

      CreateFunctionDefinitionTable $childsite
      CreatePartialSolveTable $childsite
      
      #if function is nonlinear show the nonlinear options
      BringUpSolutionOption         
      
      #Creates Function Definition Table if necessary
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {
         loadComboTable
      }
      UpdateFunctionParametersFromDatabase
      
      if { $matStates(Hyper) == 1 || $matStates(Creep) == 1 || $matStates(Plast) == 1 } {
         set childsite [$parent component childsite]
         set childsite [$childsite.funcdefframe component childsite]
         #Grid the entry only if it is hyper
         grid $childsite.funcname -row 1 -column 0 -columnspan 3         
      }
      
      #refreshL
      refresh
      StatusBarControl -1
   }

# --------------------------------------------------------------
#  Function Name: CreateFunctionDefinitionMenuBar
#  Purpose:       Creates the Table For Combination models that 
#                 require FCASE command
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc CreateFunctionDefinitionMenuBar { childsite } {

      set allchildren [winfo children $childsite]
      if { [lsearch $allchildren "$childsite.funcdefmenuframe"] > -1 } {
           destroy $childsite.funcdefmenuframe        
      }

      set menuframe [frame $childsite.funcdefmenuframe -relief groove -borderwidth 2 ]
      grid $menuframe -row 2 -column 2 -columnspan 3 -sticky nsew
      
      set childsite $menuframe
      
      menubutton $childsite.functiondefn -text [msgcat::mc "Function"] \
                  -menu $childsite.functiondefn.pulldown -relief flat
      #grid $childsite.functiondefn -row 0 -column 0 -sticky w
      set functionmenu [menu $childsite.functiondefn.pulldown -tearoff 0]
      $functionmenu add command -label New -command [code NewFunction ]
      $functionmenu add command -label Construct -command [code CreateFittingFunction]
      $functionmenu add command -label ExportToAnsys -command [code ExportToAnsys]
      $functionmenu add command -label SaveToMemory -command [code SaveToMemory]
      
      euidl::button $childsite.solvebutton -text [msgcat::mc " Solve "] \
                  -command [ code Solve] 
      grid $childsite.solvebutton -row 0 -column 0 -sticky ew

      euidl::button $childsite.plotbutton -text [msgcat::mc "  Plot  "] \
                  -command [ code LaunchGraphUtility "all" ]
      grid $childsite.plotbutton -row 0 -column 1 -sticky ew
      
      grid columnconfigure $menuframe 0 -weight 1
      grid columnconfigure $menuframe 1 -weight 1
      grid columnconfigure $menuframe 2 -weight 0      
}

# --------------------------------------------------------------
#  Function Name: CreateFunctionDefinitionTable
#  Purpose:       Creates the Table For Combination models that 
#                 require FCASE command
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc CreateFunctionDefinitionTable { childsite } {

   variable parent
   variable funcDefnTable
   variable funcDefnParams
   variable matStates

   set allchildren [winfo children $childsite]

   if { [lsearch $allchildren "$childsite.functiondefinitiontable"] > -1 } {
        catch { grid remove $childsite.functiondefinitiontable }
        catch { grid remove $childsite.optcasenamelabel }
        catch { grid remove $childsite.optcasename }
   } else {

      #euidl::button  $childsite.addtocase \
      #   -text [msgcat::mc "Add \\/\\/"]
      #grid $childsite.addtocase -column 0 -row 3 -columnspan 3 -sticky ew
      #bind $childsite.addtocase <Button-1> [code AppendToFunctionDefnTable]

      #euidl::button  $childsite.clearcase \
      #   -text [msgcat::mc "Clear \\/\\/"]
      #grid $childsite.clearcase -column 0 -row 5 -columnspan 3 -sticky ew
      #bind $childsite.clearcase <Button-1> [code ClearFunctionDefnTable]

      set funcDefnTable [ euidl::table $childsite.functiondefinitiontable \
                -variable [scope funcDefnParams] \
                -rowseparator \n \
                -colseparator \t \
                -validate focusout \
                -colstretchmode fill \
                -maxheight 200 \
                -relief flat \
                -borderwidth 5 \
      ]

      $funcDefnTable config -rowmax 100

      set funcDefnParams(0,-1) " "
      set funcDefnParams(-1,-1) "Index"
      set funcDefnParams(-1,0) "Function Description"
      set funcDefnParams(-1,1) "Command"

      set funcDefnParams(numparams) 0
      $funcDefnTable configure -rows [expr $funcDefnParams(numparams)+1] -cols 3

      euidl::label $childsite.optcasenamelabel -text [msgcat::mc "Case Name"]
      euidl::entry $childsite.optcasename \
            -variable [scope optionalCaseName]

      euidl::entry  $childsite.junkentry
      set tableBGColor [ $childsite.junkentry cget -background ]
      set tableFGColor [ $childsite.junkentry cget -entryforeground ]
      destroy $childsite.junkentry

#      $funcDefnTable configure -background $tableBGColor
#      $funcDefnTable configure -foreground $tableFGColor
#      $funcDefnTable configure -disabledbackground $tableBGColor
#      $funcDefnTable configure -disabledforeground $tableFGColor
#      $funcDefnTable configure -titlebackground $tableBGColor
#      $funcDefnTable configure -cellbackground white
      $funcDefnTable hide col -1
      $funcDefnTable hide col 1
   }

   if { $matStates(Visco) == 1 || $matStates(Plast) == 1} {
      grid $funcDefnTable -sticky ew -column 0 -row 4 -columnspan 2
      grid $childsite.optcasename -row 8 -column 1 -sticky w
      grid $childsite.optcasenamelabel -column 0 -row 8 -sticky w
   }
}

# --------------------------------------------------------------
#  Function Name: CreateFunctionDefinitionTable
#  Purpose:       Creates the Table For Combination models that 
#                 require FCASE command
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc CreatePartialSolveTable { childsite } {

   variable parent
   variable funcDefnTable
   variable matStates
   variable partialSolveParamTable

   set allchildren [winfo children $childsite]

   if { [lsearch $allchildren "$childsite.partialsolvetable"] > -1 } {
        catch { grid remove $childsite.partialsolvetable }
   } else {
      set partialSolveTable [ euidl::table $childsite.partialsolvetable \
                -variable [scope partialSolveParamTable] \
                -rowseparator \n \
                -colseparator \t \
                -validate focusout \
                -colstretchmode fill \
                -maxheight 200 \
                -relief flat \
                -borderwidth 5 \
      ]
      set partialSolveParamTable(0,-1) "Partial Solve"
      set partialSolveParamTable(-1,0) "Partial Solve"
      set partialSolveParamTable(0,0) 1
      set partialSolveParamTable(1,0) 1
      set partialSolveParamTable(2,0) 1

      $partialSolveTable configure -rows 4 -cols 2

      euidl::entry  $childsite.junkentry
      set tableBGColor [ $childsite.junkentry cget -background ]
      set tableFGColor [ $childsite.junkentry cget -entryforeground ]
      destroy $childsite.junkentry

#      $partialSolveTable configure -background $tableBGColor
#      $partialSolveTable configure -foreground $tableFGColor
#      $partialSolveTable configure -disabledbackground $tableBGColor
#      $partialSolveTable configure -disabledforeground $tableFGColor
#      $partialSolveTable configure -titlebackground $tableBGColor
#      $partialSolveTable configure -cellbackground $tableBGColor
      $partialSolveTable width -1 0
      $partialSolveTable width 0 10
      
      set iIndex 0
      for { set iIndex 0 } { $iIndex < 3 } { incr iIndex 1 } {       
         euidl::checkbutton  $childsite.pscb$iIndex
         set mychildsite [$parent component childsite]
         $childsite.pscb$iIndex configure -variable [scope partialSolveParamTable($iIndex,0)] \
                                 -command [ code UpdateForPartialSolve $mychildsite.funcparamframe ]
         $partialSolveTable window configure $iIndex,1 -window $childsite.pscb$iIndex
      }
   }

   if { $matStates(Visco) == 1 } {
      grid $childsite.partialsolvetable -sticky ew -column 2 -row 4 -columnspan 1
   }

}
# --------------------------------------------------------------
#  Function Name: AppendToFunctionDefnTable
#  Purpose:       Adds A Combination Function Data to the Func 
#                 table
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc AppendToFunctionDefnTable {} {
    variable funcDefnTable
    variable funcDefnParams
    variable cF
    variable combinationFunction

    # If no selection do nothing
    if { ! [ info exists cF(HyperChoice) ] } {
        return 
    }

#   Possible Supported Isotropic Hardening Properties   
    set isolist [list ciso biso miso voce powe CISO BISO MISO VOCE POWE]
    
    #If it is a valid combination item, add it to the list
    set foundIndex -1
    set foundCombItemIndex -1
    set belongsToIndex -1
    for { set iIndex 0 } { $iIndex < $combinationFunction(NITEMS) } { incr iIndex 1 } {
        set cF(HyperChoice) [string trim $cF(HyperChoice)]
        if { [ string equal -nocase $cF(HyperChoice) $combinationFunction($iIndex) ] } {
            set foundIndex $iIndex
        }

        #Look to find it is an entity of a combo item
        set foundCombName $combinationFunction($iIndex)
        set numCombItems $combinationFunction($foundCombName,NITEMS)
        for { set combIndex 0 } { $combIndex <  $numCombItems } { incr combIndex 1 } {

           set fParam1 [split $cF(HyperChoice) ,]
           set category1 [lindex $fParam1 0]
           set option1 [lindex $fParam1 1]

           set fParam2 [split $combinationFunction($foundCombName,$combIndex) ,]
           set category2 [lindex $fParam2 0]
           set option2 [lindex $fParam2 1]

#          Check if both are iso properties
           set iIso1 [lsearch $isolist $option1]
           set iIso2 [lsearch $isolist $option2]
           set isOMatch [ string equal -nocase -length 4 $option1 $option2 ]
           set isMatch [expr { $iIso1 > -1 && $iIso2 > -1  || $isOMatch == 1 } ]
           if { [ string equal -nocase -length 4 $category1 $category2 ] && $isMatch } {
              set foundCombItemIndex $combIndex
              set belongsToIndex $iIndex
           }
        }
    }
    
    #if it was found just clear and then add it
    if { $foundIndex != -1 } {
        ClearFunctionDefnTable
        set foundCombName $combinationFunction($foundIndex)
        set numCombItems $combinationFunction($foundCombName,NITEMS)
        for { set combIndex 0 } { $combIndex <  $numCombItems } { incr combIndex 1 } {
            AppendItemToFunctionDefnTable $combinationFunction($foundCombName,$combIndex)
        }
    } else {
        #if this is items that belongs to an combo item, add it else clear and add it
        if { $foundCombItemIndex != -1 && $belongsToIndex != -1 } {
           #If it already exists in table add it
           set fParams [split $cF(HyperChoice) ,]
           set fParamLength [llength $cF(HyperChoice)]
           set bFound 0
           for { set iRIndex 0 } { $iRIndex < $funcDefnParams(numparams) } { incr iRIndex 1 } {
               #Compare first two params
               set category [lindex $fParams 0]
               set option [lindex $fParams 1]
               set funcDefList [split $funcDefnParams($iRIndex,1) ,]
               set categoryF [lindex $funcDefList 0]
               set optionF [lindex $funcDefList 1]

               set iIso [lsearch $isolist $option]
               set iIsoF [lsearch $isolist $optionF]
               set isOMatch [ string equal -nocase -length 4 $option $optionF ]
               set isMatching [expr { $iIso >= 0 && $iIsoF >= 0 || $isOMatch == 1} ]

               if {    [string equal -nocase -length 4 $categoryF  $category ]
                    && $isMatching } {
                   set bFound 1
               }
           }

           if { $bFound == 1 } {
               AppendItemToFunctionDefnTable $cF(HyperChoice)
           }
        } else {
           ClearFunctionDefnTable
           AppendItemToFunctionDefnTable $cF(HyperChoice)
        }
    }
        

    #Check out if this is a "combination" function, if so add all required contained function
    #example visco has prony,shear;prony,bulk;prony,shift

    set funcDefnParams(0,-1) " "
    set funcDefnParams(-1,-1) "Index"
    set funcDefnParams(-1,0) "Function Description"
    set funcDefnParams(-1,1) "Command"

    #Hide all unnecessary rows/columns
    if { [info exists funcDefnTable] && [info exists funcDefnParams(numparams)] } {
       for { set iIndex -1 } { $iIndex < $funcDefnParams(numparams) } { incr iIndex 1 } {
          $funcDefnTable height $iIndex default
       }
       $funcDefnTable hide row 0
       $funcDefnTable hide row [expr $funcDefnParams(numparams) - 1]
       $funcDefnTable configure -titlerows $funcDefnParams(numparams)
    }
}

# --------------------------------------------------------------
#  Function Name: CreateCombinationFunctionDatabase
#  Purpose:       Inits all the necessary data for combo functions
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc CreateCombinationFunctionDatabase {} {

    variable combinationFunction

    set combinationFunction(NITEMS) 3

    #1- VISCO,HYPO
    set combinationFunction(0) "VISCO,HYPO,"
    set combinationFunction(VISCO,HYPO,,NITEMS) 5
    set combinationFunction(VISCO,HYPO,,0) "NEW,PVHE,"
    set combinationFunction(VISCO,HYPO,,1) "VISCO,PSHEAR,5"
    set combinationFunction(VISCO,HYPO,,2) "VISCO,PBULK,5"
    set combinationFunction(VISCO,HYPO,,3) "VISCO,SHIFT,NONE"
    set combinationFunction(VISCO,HYPO,,4) "FINI"

    #1- VISCO,PDEC
    set combinationFunction(1) "VISCO,PDEC,"
    set combinationFunction(VISCO,PDEC,,NITEMS) 4
    set combinationFunction(VISCO,PDEC,,0) "NEW,PDEC,"
    set combinationFunction(VISCO,PDEC,,1) "VISCO,ORDER,5"
    set combinationFunction(VISCO,PDEC,,2) "VISCO,SHIFT,NONE"
    set combinationFunction(VISCO,PDEC,,3) "FINI"
    
    #- CHABOCHE
    set combinationFunction(2) "CASE,CPLA,"
    set combinationFunction(CASE,CPLA,,NITEMS) 4
    set combinationFunction(CASE,CPLA,,0) "NEW,CPLA,"
    set combinationFunction(CASE,CPLA,,1) "PLAS,CHAB,3"
    set combinationFunction(CASE,CPLA,,2) "PLAS,CISO,"
    set combinationFunction(CASE,CPLA,,3) "FINI"
}


# --------------------------------------------------------------
#  Function Name: AppendItemToFunctionDefnTable
#  Purpose:       Adds a single item to the function defn table
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc AppendItemToFunctionDefnTable { cfItem } {
    variable funcDefnTable
    variable funcDefnParams
    variable cF

    # If no selection do nothing
    if { ! [ info exists cfItem ] } {
        return 
    }
    
#   Possible Supported Isotropic Hardening Properties   
    set isolist [list ciso biso miso voce powe CISO BISO MISO VOCE POWE]
    set fParams [split $cfItem ,]
    set fParamLength [llength $fParams]
    set iIndex 0
    set bFound 0
    set iNext $funcDefnParams(numparams)
    for { set iRIndex 0 } { $iRIndex < $funcDefnParams(numparams) } { incr iRIndex 1 } {
        #Compare first two params
        set category [lindex $fParams 0]
        set option [lindex $fParams 1]
        set order " "
        if { $fParamLength > 2 } {
           set order [lindex $fParams 2]
        }
        set funcList [split $funcDefnParams($iRIndex,1) ,]
        set categoryCur [lindex $funcList 0]
        set optionCur [lindex $funcList 1]
        if  { [string equal -nocase -length 4 $order  "undef"] } {
         return
        }

        set iIso [lsearch $isolist $option]
        set iIsoCur [lsearch $isolist $optionCur]
        set isOMatch [ string equal -nocase -length 4 $option $optionCur ]
        set isMatching [expr { $iIso >= 0 && $iIsoCur >= 0 || $isOMatch == 1} ]
        if {    [string equal -nocase -length 4 $categoryCur  $category ]
             && $isMatching } {
            set iNext $iRIndex
            set bFound 1
        }
    }

    set tLabel [CommandToFuncName $cfItem]
    set tLabel [FuncNameToLabel $tLabel]
    set funcDefnParams($iNext,0) $tLabel
    set funcDefnParams($iNext,1) $cfItem

    if { $bFound == 0 } {
        incr funcDefnParams(numparams) 1
    }

    $funcDefnTable configure -rows [expr $funcDefnParams(numparams)+1] -cols 2    
}

# --------------------------------------------------------------
#  Function Name: ClearFunctionDefnTable
#  Purpose:       
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc ClearFunctionDefnTable {} {
    variable funcDefnTable
    variable funcDefnParams
    variable cF
    
    array unset funcDefnParams
    set funcDefnParams(0,-1) " "
    #set all Columns Labels that you are going to create
    set funcDefnParams(-1,-1) "Index"
    set funcDefnParams(-1,0) "Descriptive Name"
    set funcDefnParams(-1,1) "Command"
    set funcDefnParams(numparams) 0
    $funcDefnTable configure -rows [expr $funcDefnParams(numparams)+1] -cols 3
}

# --------------------------------------------------------------
#  Function Name: BringUpSolutionOption
#  Purpose:       Brings Up Nonlinear Solution Options
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
   proc BringUpSolutionOption {} {
       loadRightHandSide
   }

# --------------------------------------------------------------
#  Function Name: loadComboTable
#  Purpose:       
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
   proc loadComboTable {} {
        AppendToFunctionDefnTable
   }

# --------------------------------------------------------------
#  Function Name: 
#  Purpose:       Nonlinear info if nonlinear model
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
   proc ShowSolutionData {} {
      variable matid
      variable cF
      variable NLOpts
      variable CoeffSeed
      variable partialSolveParam
      variable parent
      variable referenceTemperature
      variable matStates
      variable coefftable
      
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      set childsite [$parent component childsite]
      set allchildren [winfo children $childsite]

      if { [lsearch $allchildren "$childsite.funcparamframe"] > -1 } {
          grid $childsite.funcparamframe -column 2 -row 0 -sticky news
          set funcparamframe $childsite.funcparamframe
          set childsite [$funcparamframe component childsite]
      } else {

         set funcparamframe [::euidl::labeledframe $childsite.funcparamframe]

         $funcparamframe configure \
              -text [msgcat::mc "Solution Data"]
         grid $funcparamframe -column 2 -row 0 -sticky news
         grid rowconfigure $childsite 0 -weight 1

         set childsite [$funcparamframe component childsite]

         if { ! [info exists CoeffSeed(numcoeff)] } {
            set numCoeff 0
         } else {
            set numCoeff $CoeffSeed(numcoeff)
         }

         set coefftable [euidl::table $childsite.initcoefftable \
               -variable [scope CoeffSeed] \
               -rowseparator \n \
               -colseparator \t \
               -validate focusout \
               -colstretchmode fill \
               -maxheight 300 \
               -titlecols 2 \
               -titlerows 1 \
            ]

         $coefftable config -rowmax 1000
         set rowmax 1000000


         set CoeffSeed(0,-1) "0"
         #set all Columns Labels that you are going to create
         set CoeffSeed(-1,-1) "Coeff Index"
         set CoeffSeed(-1,0) "Coeff Name"
         set CoeffSeed(-1,1) "Coeff Value"
         set CoeffSeed(-1,2) "Fix"
         for {set i 0} {$i < $numCoeff} {incr i 1} {
            set CoeffSeed($i,-1) [expr $i + 1]
            set CoeffSeed($i,0) "C[expr $i+1]"
            set CoeffSeed($i,1) 1
         }


         $coefftable configure -rows [expr $numCoeff+1] -cols  [expr 1+1+1+1]
         $coefftable width 2 4

         #Add additional column for fixing coeffs
         set iCol 2
         set iRow 0
         for { set iRow 0 } { $iRow < 50 } { incr iRow 1 } {
            euidl::checkbutton  $childsite.coefffixcheck${iRow} \
               -variable [scope CoeffSeed($iRow,2)] 
         }

         for { set iIndex 0 } { $iIndex < $CoeffSeed(numcoeff) } { incr iIndex 1 } {
            $coefftable window configure $iIndex,2 -window $childsite.coefffixcheck${iIndex} -stick ew
         }

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


         #Current Calculated Residual
         set NLOpts(5) "NotEstimated"
         euidl::label $childsite.ernormlabel -text [msgcat::mc "Calculated Residual"]
         euidl::entry $childsite.ernormvalue -variable [scope NLOpts(5)] -relief flat -state disabled

         euidl::label $childsite.normalchecklabel -text [msgcat::mc "Use Normalized Error"]
         euidl::checkbutton  $childsite.normalcheck -variable [scope NLOpts(1)]

         euidl::label $childsite.tempdeplabel -text [msgcat::mc "Temperature Dependency"]
         euidl::checkbutton  $childsite.tempdepcheck -variable [scope NLOpts(6)]

         grid $coefftable -sticky news -column 0 -row 0 -columnspan 2
         grid $childsite.ernormlabel -column 0 -row 1 -sticky ew
         grid $childsite.ernormvalue -column 1 -row 1 -sticky ew
         grid $childsite.normalchecklabel -column 0 -row 2 -sticky ew 
         grid $childsite.normalcheck -column 1 -row 2 -sticky ew 
         grid $childsite.tempdeplabel -column 0 -row 3 -sticky ew 
         grid $childsite.tempdepcheck -column 1 -row 3 -sticky ew 

         grid rowconfigure $childsite 0 -weight 0
         grid rowconfigure $childsite 1 -weight 0
         grid rowconfigure $childsite 2 -weight 0
         grid rowconfigure $childsite 3 -weight 0 
         grid rowconfigure $childsite 4 -weight 0
         grid rowconfigure $childsite 5 -weight 1
         grid rowconfigure $childsite 6 -weight 0
         grid columnconfigure $childsite 0 -weight 1 
         grid columnconfigure $childsite 1 -weight 0 

         #Reference Temp Widget
         euidl::label $childsite.treflabel -text [msgcat::mc "ReferenceTemperature"]
         euidl::combobox $childsite.trefentry -variable [ scope referenceTemperature ]
         bind $childsite.trefentry <Button-1> [ code UpdateReferenceTemperartureList $funcparamframe ]
         bind $childsite.trefentry <Enter> [ code UpdateRefTempComboBoxStatus $funcparamframe ]
         trace variable ::euidl::material::CurveFit::referenceTemperature w [namespace code UpdateCoefficientsByTrace]
         grid $childsite.treflabel  -row 4 -column 0  -sticky new 
         grid $childsite.trefentry -row 4 -column 1    -sticky new          
      }
            
      ToggleFixColumnState normal  

      if { [info exists experimentTempList] } {
         $childsite.trefentry delete list 0 end
         $childsite.trefentry insert list end $experimentTempList
      }

      set NLOpts(1) 1
      #if the function exists load up the coeffs
      ReadCoeffsFromDatabase $matid $fname
   }

# --------------------------------------------------------------
#  Function Name: ViscoElasticSettings
#  Purpose:       Nonlinear info if nonlinear model
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
   proc ViscoElasticSettings { parent1 coefftable } {
      variable matid
      variable cF
      variable NLOpts
      variable CoeffSeed
      variable parent
      variable partialSolveParam
      variable matStates
      variable experimentTempList 
      
      set childsite [$parent1 component childsite]

      set allchildren [winfo children $childsite]

      if { [lsearch $allchildren "$childsite.viscosettingsframe"] > -1 } {
           grid remove $childsite.viscosettingsframe        
           set viscosettingsframe $childsite.viscosettingsframe
           set childsite [$viscosettingsframe component childsite]
           grid remove $childsite.partialsolvechoice
      } else {

         update
         update idletasks 

         set viscosettingsframe [::euidl::labeledframe $childsite.viscosettingsframe]   
         set childsite [$viscosettingsframe component childsite]

         $viscosettingsframe configure \
              -text [msgcat::mc "ViscoElastic Settings"]

         euidl::combobox $childsite.partialsolvechoice -variable [scope partialSolveParam] \
                         -command [ code UpdateForPartialSolve $viscosettingsframe $coefftable ]
         $childsite.partialsolvechoice insert list end [list "Shear Params Only" pshear]
         $childsite.partialsolvechoice insert list end [list "Bulk Params Only" pbulk]
         $childsite.partialsolvechoice insert list end [list "All Params" pvhe]

      }
      
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1} {
         grid $viscosettingsframe -column 0 -row 3 -sticky news -columnspan 2
         grid $childsite.partialsolvechoice  -row 0 -column 0  -columnspan 2 -sticky ew 
      }
   }
# --------------------------------------------------------------
#  Function Name: NonLinearSettings
#  Purpose:       Nonlinear info if nonlinear model
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
   proc NonLinearSettings {} {
      variable matid
      variable cF
      variable NLOpts
      variable CoeffSeed
      variable parent
      variable matStates
      variable coefftable
      
      set childsite [$parent component childsite]

      set allchildren [winfo children $childsite]

      if { [lsearch $allchildren "$childsite.nonlinearsettings"] > -1 } {
          grid remove $childsite.nonlinearsettings
          grid $childsite.nonlinearsettings -column 2 -row 1 -sticky news
          set nonlinearframe  $childsite.nonlinearsettings     
      } else {

         update
         update idletasks 

         set nonlinearframe [::euidl::labeledframe $childsite.nonlinearsettings]

         $nonlinearframe configure \
              -text [msgcat::mc "Regression Settings"]
         grid $nonlinearframe -column 2 -row 1 -sticky news

         set childsite [$nonlinearframe component childsite]

         euidl::label $childsite.numitlab -text [msgcat::mc "Max Iterations"]
         grid $childsite.numitlab -column 0 -row 0 -sticky w

         euidl::entry $childsite.numitent \
            -variable [scope NLOpts(2)]
         grid $childsite.numitent -column 1 -row 0 -sticky w
         set NLOpts(2) 1000

         euidl::label $childsite.tolerlab -text [msgcat::mc "Residual Tolerance"]
         grid $childsite.tolerlab -column 0 -row 1 -sticky w

         euidl::entry $childsite.tolerent \
            -variable [scope NLOpts(3)]
         grid $childsite.tolerent -column 1 -row 1 -sticky w
         set NLOpts(3) 0

         euidl::label $childsite.ctollab -text [msgcat::mc "Coefficient Tolerance"]
         grid $childsite.ctollab -column 0 -row 2 -sticky w

         euidl::entry $childsite.ctolent \
            -variable [scope NLOpts(4)]
         grid $childsite.ctolent -column 1 -row 2 -sticky w
         set NLOpts(4) 0
      }

      #ViscoElasticSettings $nonlinearframe $coefftable

      if {[IsNonlinear $cF(HyperChoice)] == "No"} {
         $nonlinearframe configure -state disabled
      } else {
         $nonlinearframe configure -state normal
      }
      
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1} {
         $nonlinearframe configure -state normal
      }
   }

# --------------------------------------------------------------
#  Function Name: IsNonlinear
#  Purpose:       Decide if the material is nonlinear
#  Arguments:     None
#  Notes:
#
# --------------------------------------------------------------
   proc IsNonlinear {fname} {
 
      variable matid
      variable CoeffSeed

      # Set array of tree labels to show, starting with functions
      set flabel(HYPER,MOON,2) "No"
      set flabel(HYPER,MOON,3) "No"
      set flabel(HYPER,MOON,5) "No"
      set flabel(HYPER,MOON,9) "No"

      set flabel(hyper,moon,2) "No"
      set flabel(hyper,moon,3) "No"
      set flabel(hyper,moon,5) "No"
      set flabel(hyper,moon,9) "No"

      for {set i 1} {$i <= 20} {incr i 1} {

         set flabel(HYPER,YEOH,$i) "No"
         set flabel(hyper,yeoh,$i) "No"

         set flabel(HYPER,POLY,$i)  "No"
         set flabel(hyper,poly,$i)  "No"

         set flabel(HYPER,OGDEN,$i) "Yes"
         set flabel(hyper,ogden,$i) "Yes"

         set flabel(HYPER,OGDE,$i) "Yes"
         set flabel(hyper,ogde,$i) "Yes"

         set flabel(HYPER,FOAM,$i) "Yes"
         set flabel(hyper,foam,$i) "Yes"

	 #Chaboche Plasticity
	 set flabel(PLAS,CHAB,$i)  "Yes"
	 set flabel(plas,chab,$i)  "Yes"
      }

      set flabel(HYPER,BOYCE,)  "Yes"
      set flabel(hyper,boyce,)  "Yes"

      set flabel(HYPER,BOYC)  "Yes"
      set flabel(hyper,boyc)  "Yes"

      set flabel(HYPER,ETUB,)  "Yes"
      set flabel(hyper,ETUB,)  "Yes"

      set flabel(HYPER,GENT,)   "Yes"
      set flabel(hyper,gent,)   "Yes"

      set flabel(HYPER,GENT)   "Yes"
      set flabel(hyper,gent)   "Yes"

      set flabel(HYPER,NEO,) "No"
      set flabel(hyper,neo,) "No"

      set flabel(HYPER,BLAT,) "No"
      set flabel(hyper,blat,) "No"


      #All creep models are non linear
      set flabel(CREEP,SHAR,) "Yes"
      set flabel(CREEP,THAR,) "Yes"
      set flabel(CREEP,GEXP,) "Yes"
      set flabel(CREEP,GGRA,) "Yes"
      set flabel(CREEP,GBLA,) "Yes"
      set flabel(CREEP,MSHA,) "Yes"
      set flabel(CREEP,MTHA,) "Yes"
      set flabel(CREEP,GTHA,) "Yes"
      set flabel(CREEP,GGAR,) "Yes"
      set flabel(CREEP,EXPO,) "Yes"
      set flabel(CREEP,NORT,) "Yes"
      set flabel(CREEP,PSRP,) "Yes"
      set flabel(CREEP,PSTH,) "Yes"

      set flabel(creep,shar,) "Yes"
      set flabel(creep,thar,) "Yes"
      set flabel(creep,gexp,) "Yes"
      set flabel(creep,ggra,) "Yes"
      set flabel(creep,gbla,) "Yes"
      set flabel(creep,msha,) "Yes"
      set flabel(creep,mtha,) "Yes"
      set flabel(creep,gtha,) "Yes"
      set flabel(creep,ggar,) "Yes"
      set flabel(creep,expo,) "Yes"
      set flabel(creep,nort,) "Yes"
      set flabel(creep,psrp,) "Yes"
      set flabel(creep,psth,) "Yes"

      set flabel(CREEP,SHAR) "Yes"
      set flabel(CREEP,THAR) "Yes"
      set flabel(CREEP,GEXP) "Yes"
      set flabel(CREEP,GGRA) "Yes"
      set flabel(CREEP,GBLA) "Yes"
      set flabel(CREEP,MSHA) "Yes"
      set flabel(CREEP,MTHA) "Yes"
      set flabel(CREEP,GTHA) "Yes"
      set flabel(CREEP,GGAR) "Yes"
      set flabel(CREEP,EXPO) "Yes"
      set flabel(CREEP,SNOR) "Yes"
      set flabel(CREEP,PSRP) "Yes"
      set flabel(CREEP,PSTH) "Yes"

      set flabel(creep,shar) "Yes"
      set flabel(creep,thar) "Yes"
      set flabel(creep,gexp) "Yes"
      set flabel(creep,ggra) "Yes"
      set flabel(creep,gbla) "Yes"
      set flabel(creep,msha) "Yes"
      set flabel(creep,mtha) "Yes"
      set flabel(creep,gtha) "Yes"
      set flabel(creep,ggar) "Yes"
      set flabel(creep,expo) "Yes"
      set flabel(creep,nort) "Yes"
      set flabel(creep,psrp) "Yes"
      set flabel(creep,psth) "Yes"

      set flabel(case,pvhe,) "Yes"
      set flabel(CASE,PVHE,) "Yes"

      set flabel(case,cpla,) "Yes"
      set flabel(CASE,CPLA,) "Yes"

      #Labels for Prony Visco HypoElastic
      set shiftLabels [list tn wlf none]
      set numShiftLabels [llength $shiftLabels]
      for {set i 1} {$i <= 20} {incr i 1} {
          for {set j 1} {$j <= 20} {incr j 1} {
             for {set k 0} { $k < $numShiftLabels} {incr k 1} {
                 set sLabel [lindex $shiftLabels $k]
                 set sOrder "[expr $i]_[expr $j]_$sLabel"
                 set flabel(VISCO,PVHE,$sOrder) "Yes"
             }
          }
      }

      for {set i 1} {$i <= 20 } {incr i 1} {
         for {set j 0} { $j < $numShiftLabels} {incr j 1} {
            set sLabel [lindex $shiftLabels $j]
            set sOrder "[expr $i]_$sLabel"
            set flabel(VISCO,PDEC,$sOrder) "Yes"
         }
      }

      if { [catch {set FuncLabel $flabel($fname)} ] } {
         set FuncLabel "No"
      }
      
      return $FuncLabel

   }

# --------------------------------------------------------------
#  Function Name: GetNumberOfCoefficients
#  Purpose:       Gets the Number of Coefficients for a Model
#  Arguments:     fname -- category,type,option
#  Notes:         
#
# --------------------------------------------------------------
proc GetNumberOfCoefficients { fname } {
      variable matid
      variable CoeffSeed   
      variable funcDefnParams   
      variable optionalCaseName   
      variable parent
      variable matStates

      #Default
      set CoeffSeed(numcoeff) 2

      if { ![info exists fname] } {
         return 
      }

      set fname [string trim $fname]

      if { $fname == "" } {
         return 
      }
      
      #Split into components
      
      set fnamelist [split $fname ,]
      set order  [lindex $fnamelist 2]
      set lCategory [lindex $fnamelist 1]
      set lClass [lindex $fnamelist 0]
            
      set numShiftParams(wlf) 3
      set numShiftParams(tn) 2
      set numShiftParams(none) 0

      #if it is a case code if the function exists
      if { ([ string equal -nocase -length 4 $lClass "case" ] || [ string equal -nocase -length 4 $lClass "plas" ] )&&  $matStates(Plast) == 1  } {
        set fnamelist [split $funcDefnParams(0,1) ,]
        set order  [lindex $fnamelist 2]
        set lCategory [lindex $fnamelist 1]
        set lClass [lindex $fnamelist 0]
        set fName  [lindex $fnamelist 1]
        set existKey [ ConstitutiveFunctionExists $matid $fName ]
        if { $existKey == 1 } {
            set CoeffSeed(numcoeff) [ans_getvalue TBFT,$matid,FUNC,$fName,ncon]
        } else  {
           set caseList [ split $funcDefnParams(0,1) , ]
           set comboFuncName [lindex $caseList 1]

           #make sure the name is not filled with blanks
           set optionalCaseName [string trim $optionalCaseName]
           if { [string equal $optionalCaseName ""] } {
              tk_messageBox -parent $parent -title "Error" -icon error -message "Invalid Case/Function Name for Fitting Function. Please enter a CASE name in the entry box provided for CASE Name at the bottom of the middle frame"
              return
           }
           
           #Number of Coefficients
           set numberOfTerms 0
           if { [ string equal -nocase -length 4 $lCategory "cplas" ] } {
              for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
                  set paramList [split $funcDefnParams($iRIndex,1) ,]
                  if { [llength $paramList] == 3 } {
                     set type [lindex $paramList 1]
                     set value [lindex $paramList 2]
                     set type [string trim $type]
                     if {   [string equal -nocase -length 4 $type "chab"]  } {
                        if { ! [string equal -nocase -length 4 $value "none"] } {
                            set numberOfTerms [expr $numberOfTerms + ( 2 * $value + 1 ) ]
                        }
                     } elseif { [string equal -nocase -length 4 $type "miso"] } {
                        if { ! [string equal -nocase -length 4 $value "none"] } {
                            set numberOfTerms [expr $numberOfTerms + ( 2 * $value - 1 ) ]
                        }
                     } elseif { [string equal -nocase -length 4 $type "biso"] } {
                        set value [string tolower $value]
                        set numberOfTerms [expr $numberOfTerms + 2  - 1]
                     } elseif { [string equal -nocase -length 4 $type "voce"] } {
                        set value [string tolower $value]
                        set numberOfTerms [expr $numberOfTerms + 4  - 1]
                     } elseif { [string equal -nocase -length 4 $type "powe"] } {
                        set value [string tolower $value]
                        set numberOfTerms [expr $numberOfTerms + 3  - 1]
                     }
                  }
              }
           }           
           set CoeffSeed(numcoeff) $numberOfTerms
        }
        return
      }

      #if it is a case code if the function exists
      if { [ string equal -nocase -length 4 $lClass "case" ] || [ string equal -nocase -length 4 $lClass "visco" ]} {
        set fnamelist [split $funcDefnParams(0,1) ,]
        set order  [lindex $fnamelist 2]
        set lCategory [lindex $fnamelist 1]
        set lClass [lindex $fnamelist 0]
        set fName  [lindex $fnamelist 1]
        set existKey [ ConstitutiveFunctionExists $matid $fName ]
        if { $existKey == 1 } {
            set CoeffSeed(numcoeff) [ans_getvalue TBFT,$matid,FUNC,$fName,ncon]
        } else  {
           set caseList [ split $funcDefnParams(0,1) , ]
           set comboFuncName [lindex $caseList 1]

           #make sure the name is not filled with blanks
           set optionalCaseName [string trim $optionalCaseName]
           if { [string equal $optionalCaseName ""] } {
              tk_messageBox -parent $parent -title "Error" -icon error -message "Invalid Case/Function Name for Fitting Function. Please enter a CASE name in the entry box provided for CASE Name at the bottom of the middle frame"
              return
           }
           
           #Number of Coefficients
           set numberOfTerms 0
           if { [ string equal -nocase -length 4 $lCategory "pvhe" ] } {
              for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
                  set paramList [split $funcDefnParams($iRIndex,1) ,]
                  if { [llength $paramList] == 3 } {
                     set type [lindex $paramList 1]
                     set value [lindex $paramList 2]
                     set type [string trim $type]
                     if {    [string equal -nocase -length 4 $type "pshear"]  \
                          || [string equal -nocase -length 4 $type "pbulk"]  } {
                        if { ! [string equal -nocase -length 4 $value "none"] } {
                            set numberOfTerms [expr $numberOfTerms + ( 2 * $value ) + 1 ]
                        }
                     } elseif { [string equal -nocase -length 4 $type "shift"] } {
                        set value [string tolower $value]
                        set numberOfTerms [expr $numberOfTerms + $numShiftParams($value) ]
                     }
                  }
              }
           }           
           set CoeffSeed(numcoeff) $numberOfTerms
        }
        return
      }
      
      if { $lCategory == "" } {
         return 
      }

      if { [ string equal -nocase -length 4 $lCategory "pvhe" ] } {
         set CoeffSeed(numcoeff) 0
         set lOrderParams [split $order _]
         set i [lindex $lOrderParams 0]
         if { [string equal -nocase -length 4 $i "none"] } {
            set i 0
         }
         if { $i > 0 } {
            set CoeffSeed(numcoeff) [expr (2 * $i) + 1 ]
         }
         set j [lindex $lOrderParams 1]
         if { [string equal -nocase -length 4 $j "none"] } {
            set j 0
         }
         if { $j > 0 } {
            set CoeffSeed(numcoeff) [expr (2 * j) + 1 + $CoeffSeed(numcoeff)]
         }
         set k [lindex $lOrderParams 2]
         set CoeffSeed(numcoeff) [expr $CoeffSeed(numcoeff) + $numShiftParams($k)]
      } elseif { [ string equal -nocase -length 4 $lCategory "pdec" ] } {
         set lOrderParams [split $order _]
         set i [lindex $lOrderParams 0]
         set j [lindex $lOrderParams 1]
         set CoeffSeed(numcoeff) [expr 2 * $i + 1 + $numShiftParams($j)]
      } elseif { [ string equal -nocase -length 4 $lCategory "foam" ] } {
         set CoeffSeed(numcoeff) 3
         if { [info exists order] && $order != "" } {       
             set CoeffSeed(numcoeff) [expr $order * 3]
         }
      } elseif { [ string equal -nocase -length 4 $lCategory "moon" ] } {
         set CoeffSeed(numcoeff) 3
         if { [info exists order] && $order != "" && \
              ( $order == 2 || $order == 3 || $order == 5 || $order == 9) } {       
             set CoeffSeed(numcoeff) [expr $order + 1 ]
         } else {
             set order 2
             set CoeffSeed(numcoeff) [expr $order + 1 ]
             set fname "hymoon2"
             set cF(HyperChoice) "hyper,moon,2"
         }
      } elseif { [ string equal -nocase -length 4 $lCategory "poly" ] } {
         set CoeffSeed(numcoeff) 3
         if { [info exists order] && $order != "" } {       
             set CoeffSeed(numcoeff) 0
             set orderplus2  [expr $order + 1 ]
             for { set index 2 } { $index <= $orderplus2 } { incr index 1 } {
                 set CoeffSeed(numcoeff) [expr $CoeffSeed(numcoeff) + $index]
             }
             set CoeffSeed(numcoeff) [expr $CoeffSeed(numcoeff) + $order]
         }
      } elseif { [ string equal -nocase -length 4 $lCategory "yeoh" ] } {
         set CoeffSeed(numcoeff) 3
         if { [info exists order] && $order != "" } {       
             set CoeffSeed(numcoeff) [expr $order * 2 ]
         }
      } elseif { [ string equal -nocase -length 4 $lCategory "ogde" ] } {
         set CoeffSeed(numcoeff) 3
         if { [info exists order] && $order != "" } {       
             set CoeffSeed(numcoeff) [expr $order  * 3 ]
         }
      } elseif { [ string equal -nocase -length 4 $lCategory "boyc" ] } {
          set CoeffSeed(numcoeff) 3
      } elseif { [ string equal -nocase -length 4 $lCategory "etub" ] } {
          set CoeffSeed(numcoeff) 4
      } elseif { [ string equal -nocase -length 4 $lCategory "gent" ] } {
          set CoeffSeed(numcoeff) 3
      } elseif { [ string equal -nocase -length 4 $lCategory "blat" ] } {
         set CoeffSeed(numcoeff) 1
      } elseif { [ string equal -nocase -length 3 $lCategory "neo" ] } {
         set CoeffSeed(numcoeff) 2
      # Creep Models
      } elseif { [ string equal -nocase -length 4 $lCategory "shar" ] } {
          set CoeffSeed(numcoeff) 4
      } elseif { [ string equal -nocase -length 4 $lCategory "thar" ] } {
          set CoeffSeed(numcoeff) 4
      } elseif { [ string equal -nocase -length 4 $lCategory "gexp" ] } {
          set CoeffSeed(numcoeff) 5
      } elseif { [ string equal -nocase -length 4 $lCategory "ggra" ] } {
          set CoeffSeed(numcoeff) 8
      } elseif { [ string equal -nocase -length 4 $lCategory "gbla" ] } {
          set CoeffSeed(numcoeff) 7
      } elseif { [ string equal -nocase -length 4 $lCategory "mtha" ] } {
          set CoeffSeed(numcoeff) 4
      } elseif { [ string equal -nocase -length 4 $lCategory "msha" ] } {
          set CoeffSeed(numcoeff) 4
      } elseif { [ string equal -nocase -length 4 $lCategory "ggar" ] } {
          set CoeffSeed(numcoeff) 4
      } elseif { [ string equal -nocase -length 4 $lCategory "expo" ] } {
          set CoeffSeed(numcoeff) 3
      } elseif { [ string equal -nocase -length 4 $lCategory "nort" ] } {
          set CoeffSeed(numcoeff) 3
      } elseif { [ string equal -nocase -length 4 $lCategory "psth" ] } {
          set CoeffSeed(numcoeff) 7
      } elseif { [ string equal -nocase -length 4 $lCategory "psrp" ] } {
          set CoeffSeed(numcoeff) 10
      } elseif { [ string equal -nocase -length 4 $lCategory "gtha" ] } {
          set CoeffSeed(numcoeff) 6
      } elseif { [ string equal -nocase -length 4 $lCategory "chab" ] } {
         set CoeffSeed(numcoeff) 3
         if { [info exists order] && $order != "" && $order != "UNDEF" } {       
             set CoeffSeed(numcoeff) [expr $order  * 2 + 1 ]
         } else {
             set CoeffSeed(numcoeff) 2
         }
         
      } else {
         ans_senderror 2 "Picked Material Model $lCategory is Unknown Type"
         return
      }
}

# --------------------------------------------------------------
#  Function Name: UpdatePartialSolveFromDatabase
#  Purpose:       
#                 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc UpdatePartialSolveFromDatabase {} {
   variable matid
   variable optionalCaseName
   variable partialSolveParam
   variable partialSolveParamTable
   
   set partialSolveParam [ans_getvalue tbft,$matid,,$optionalCaseName,comp]
   set partialSolveParam [string trim $partialSolveParam]
      
   #partialSolveParamTable(0,0)
   return
   if { [string equal -nocase -length 4 $partialSolveParam "pshear"] } {
        set partialSolveParamTable(0,0) 1 
        set partialSolveParamTable(1,0) 0 
        set partialSolveParamTable(2,0) 0 
   } elseif { [string equal -nocase -length 4 $partialSolveParam "pbulk"] } {
        set partialSolveParamTable(0,0) 0 
        set partialSolveParamTable(1,0) 1 
        set partialSolveParamTable(2,0) 0 
   } elseif { [string equal -nocase -length 4 $partialSolveParam "pvhe"] } {
        set partialSolveParamTable(0,0) 1 
        set partialSolveParamTable(1,0) 1 
        set partialSolveParamTable(2,0) 1 
   } elseif { [string equal -nocase -length 4 $partialSolveParam "cpla"] } {
        set partialSolveParamTable(0,0) 1 
        set partialSolveParamTable(1,0) 1 
        set partialSolveParamTable(2,0) 1 
   } else {
      set partialSolveParam "pvhe"
      set partialSolveParamTable(0,0) 1 
      set partialSolveParamTable(1,0) 1 
      set partialSolveParamTable(2,0) 1 
   }
}

# --------------------------------------------------------------
#  Function Name: Update RefTemp ComboBox Status
#  Purpose:       
#           ...
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc UpdateRefTempComboBoxStatus { funcparamframe } {
   variable matid
   variable NLOpts
   variable matStates

   #Update Combobox
   set childsite [$funcparamframe component childsite]
   if { $NLOpts(6) == 0 && $matStates(Visco) != 1 } {
       $childsite.trefentry configure -state disabled
   } else {
       $childsite.trefentry configure -state normal
   }
}

# --------------------------------------------------------------
#  Function Name: Update Coefficients by trace
#  Purpose:       
#           ...
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc UpdateCoefficientsByTrace { myVar arrayIndex values } {
   variable referenceTemperature
   
   if { ! [string equal -nocase -length 4 $referenceTemperature "all"] } {
      UpdateCoefficients
    }
}

# --------------------------------------------------------------
#  Function Name: Update Coefficients
#  Purpose:       
#           ...
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc UpdateCoefficients {} {
   variable matid
   variable cF
   variable referenceTemperature
   variable NLOpts

   if { ![info exists NLOpts(6)] } {
      return 
   }

   if { $NLOpts(6) == 1 } {
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      if { [ConstitutiveFunctionExists $matid $fname] } {
         catch { ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),tref,$referenceTemperature }
      }
      ReadCoeffsFromDatabase $matid $fname
   }
}

# --------------------------------------------------------------
#  Function Name: Update Ref Temp List
#  Purpose:       Set's flags indicating partial solve. Disable 
#                 Coeffs...
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc UpdateReferenceTemperartureList { funcparamframe } {
   variable matid
   variable experimentTempList
   CreateExperimentTemperatureList  $matid "all"
   
   #Update Combobox
   set childsite [$funcparamframe component childsite]
   if { [info exists experimentTempList] } {
      $childsite.trefentry delete list 0 end
      $childsite.trefentry insert list end $experimentTempList
   }  
}

# --------------------------------------------------------------
#  Function Name: UpdateForPartialSolve
#  Purpose:       Set's flags indicating partial solve. Disable 
#                 Coeffs...
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc UpdateForPartialSolve { funcparamframe } {
   variable partialSolveParam
   variable partialSolveParamTable
   variable matid
   variable cF
   variable experimentTempList
   variable coefftable
   variable funcDefnParams
   variable CoeffSeed
   variable matStates
      
   if { $matStates(Visco) != 1 } {
      return
   }

   if { ![info exists coefftable] } {
      return
   }
   
   #Return if it is not a Function
   set fname [ CommandToFuncName $cF(HyperChoice) ]
   set fname [string trim $fname]
   set existKey [ ConstitutiveFunctionExists $matid $fname ]

   if { ! [info exists partialSolveParamTable] } {
      return
   }
   
   if { ! [info exists funcDefnParams] } {
      return
   }

   set funcType "unknown"
   if { $existKey == 0 } {         
      set fnamelist [split $funcDefnParams(0,1) ,]
      set funcType  [lindex $fnamelist 1]
      set funcType [string trim $funcType]
   } else {
      #If the function type is not PVHE exit
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      set fname [string trim $fname]
      set funcType "unknown"
      catch { set funcType [ans_getvalue tbft,$matid,,$fname,type] }
      set funcType [string trim $funcType]
   }

   set sOrder 1
   set bOrder 1
   set sType none


   if { ! [string equal -nocase -length 4 $funcType "cpla"]  && ! [string equal -nocase -length 4 $funcType "pvhe"] } {
      return 
   }

   if { $existKey == 1 } {
      #Disable all other coeffs other than the ones active
      set sOrder [ans_getvalue tbft,$matid,,$fname,sorder]   
      set bOrder [ans_getvalue tbft,$matid,,$fname,border]   
      set sType [ans_getvalue tbft,$matid,,$fname,shift]   
      set CoeffSeed(numcoeff) [ans_getvalue tbft,$matid,,$fname,ncon]   
   } else {

      if { ! [info exists funcDefnParams] } {
         return
      }            
      set caseList [ split $funcDefnParams(0,1) , ]
      set comboFuncName [lindex $caseList 1]

      if { [ string equal -nocase -length 4 $comboFuncName "pvhe" ] } {
         for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
             set paramList [split $funcDefnParams($iRIndex,1) ,]
             if { [llength $paramList] == 3 } {
                set type [lindex $paramList 1]
                set value [lindex $paramList 2]
                set type [string trim $type]
                if {    [string equal -nocase -length 4 $type "pshear"] } {
                   set sOrder $value
                } elseif { [string equal -nocase -length 4 $type "pbulk"] } {
                   set bOrder $value
                } elseif { [string equal -nocase -length 4 $type "shift"] } {
                   set sType [string tolower $value]                   
                }
             }
         }
      } else {           
         return
      }
   }
   
   set start 0
   if { ![info exists CoeffSeed(numcoeff)] } {
      return
   }
   set end  $CoeffSeed(numcoeff)
   for { set iIndex $start } { $iIndex < $end } { incr iIndex 1 } {
      $coefftable tag row {} $iIndex
   }
   
   #partialSolveParamTable(0,0)
   if { $partialSolveParamTable(0,0) == 1 && \
        $partialSolveParamTable(1,0) == 0 && \
        $partialSolveParamTable(2,0) == 0 } {
                set partialSolveParam "pShear"
   } elseif { $partialSolveParamTable(0,0) == 0 && \
        $partialSolveParamTable(1,0) == 1 && \
        $partialSolveParamTable(2,0) == 0 } {
        
        set partialSolveParam "pBulk"
   } elseif { $partialSolveParamTable(0,0) == 1 && \
        $partialSolveParamTable(1,0) == 1 && \
        $partialSolveParamTable(2,0) == 1 } {
        
        set partialSolveParam "pvhe"
   } elseif { $partialSolveParamTable(2,0) == 1 } {
      set partialSolveParamTable(0,0) 1 
      set partialSolveParamTable(1,0) 1
      set partialSolveParam "pvhe"
   } else {
      set partialSolveParam "pvhe"
   }
   
   if { [string equal -nocase -length 4 $partialSolveParam "pShear"] } {
      #Disable 2n+1 to num coeff rows
      set start 0
      if { ! [string equal -nocase -length 4 "none" $sOrder] } {
          set start [expr 2*$sOrder+1]
      }
      set end  $CoeffSeed(numcoeff)
      for { set iIndex $start } { $iIndex < $end } { incr iIndex 1 } {
         $coefftable tag row disabled $iIndex
      }
      CreateExperimentTemperatureList  $matid "sdec"
   } elseif { [string equal -nocase -length 4 $partialSolveParam "pBulk"] } {
      #Disable 2n+1 to num coeff rows
      set start 0
      set end 0
      if { ! [string equal -nocase -length 4 "none" $sOrder] } {
          set end  [expr 2*$sOrder+1]
      }
      for { set iIndex $start } { $iIndex < $end } { incr iIndex 1 } {
         $coefftable tag row disabled $iIndex
      }

      set start 0
      if { ! [string equal -nocase -length 4 "none" $sOrder] } {
          set start  [expr $start+(2*$sOrder+1)]
      }
      if { ! [string equal -nocase -length 4 "none" $bOrder] } {
          set start  [expr $start+(2*$bOrder+1)]
      }

      set end  $CoeffSeed(numcoeff)
      for { set iIndex $start } { $iIndex < $end } { incr iIndex 1 } {
         $coefftable tag row disabled $iIndex
      }
      CreateExperimentTemperatureList  $matid "bdec"
   } else {
      CreateExperimentTemperatureList  $matid "all"
   }
   
   #Update Combobox
   set childsite [$funcparamframe component childsite]
   if { [info exists experimentTempList] } {
      $childsite.trefentry delete list 0 end
      $childsite.trefentry insert list end $experimentTempList
   }
   
}

# --------------------------------------------------------------
#  Function Name: HyperChoice
#  Purpose:       Dialog box to choose Hyperelastic models
#  Arguments:     None
#  Notes:         Orphan - advanced feature that is not called
#                 This one was replaced by HyperChoiceTree
# 
# --------------------------------------------------------------
   proc HyperChoice {} {
      variable parent
      variable childsite
      variable emptyfolder
      variable matid
      variable matModelArr
      variable expCurve
      variable cF

      set childsite [$parent component childsite]
      if {[info exists childsite]} {
         destroy $childsite.funcdefframe
         destroy $childsite.expframe
         destroy $childsite.funcparamframe
         destroy $childsite.nonlinearsettings
      }

      set childsite [$parent component childsite]
      set parent1 [::euidl::labeledframe $childsite.newframe]
      $parent1 configure \
           -text [msgcat::mc "Solve for the Following Function"]
      grid $parent1 -column 1 -row 1 -sticky news

      set childsite [$parent1 component childsite]

      euidl::label $childsite.polylbl -text [msgcat::mc "Polynomial"]
      grid $childsite.polylbl -column 0 -row 3 -sticky w -rowspan 4

      euidl::radiobutton $childsite.polychk1 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,POLY,1
      euidl::label $childsite.polylbl1 -text [msgcat::mc "1st Order"]

      grid $childsite.polychk1 -column 1 -row 3 -sticky e
      grid $childsite.polylbl1 -column 2 -row 3 -sticky w

      euidl::radiobutton $childsite.polychk2 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,POLY,2
      euidl::label $childsite.polylbl2 -text [msgcat::mc "2nd Order"]

      grid $childsite.polychk2 -column 1 -row 4 -sticky e
      grid $childsite.polylbl2 -column 2 -row 4 -sticky w

      euidl::radiobutton $childsite.polychk3 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,POLY,3
      euidl::label $childsite.polylbl3 -text [msgcat::mc "3rd Order"]

      grid $childsite.polychk3 -column 1 -row 5 -sticky e
      grid $childsite.polylbl3 -column 2 -row 5 -sticky w


      euidl::label $childsite.moonlbl -text [msgcat::mc "Mooney"]
      grid $childsite.moonlbl -column 0 -row 6 -sticky w -rowspan 3

      euidl::radiobutton $childsite.moonchk1 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,MOON,2
      euidl::label $childsite.moonlbl1 -text [msgcat::mc "2 Parameter"]

      grid $childsite.moonchk1 -column 1 -row 6 -sticky e
      grid $childsite.moonlbl1 -column 2 -row 6 -sticky w

      euidl::radiobutton $childsite.moonchk2 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,MOON,5
      euidl::label $childsite.moonlbl2 -text [msgcat::mc "5 Parameter"]

      grid $childsite.moonchk2 -column 1 -row 7 -sticky e
      grid $childsite.moonlbl2 -column 2 -row 7 -sticky w

      euidl::radiobutton $childsite.moonchk3 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,MOON,9
      euidl::label $childsite.moonlbl3 -text [msgcat::mc "9 Parameter"]

      grid $childsite.moonchk3 -column 1 -row 8 -sticky e
      grid $childsite.moonlbl3 -column 2 -row 8 -sticky w




      euidl::radiobutton $childsite.chk3 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,MOON,2
      euidl::label $childsite.lbl3 -text [msgcat::mc "Mooney"]

      grid $childsite.chk3 -column 0 -row 12 -sticky e
      grid $childsite.lbl3 -column 1 -row 12 -sticky w

      euidl::radiobutton $childsite.chk4 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,OGDE,1
      euidl::label $childsite.lbl4 -text [msgcat::mc "Ogden"]

      grid $childsite.chk4 -column 0 -row 13 -sticky e
      grid $childsite.lbl4 -column 1 -row 13 -sticky w

      euidl::radiobutton $childsite.chk5 \
         -variable [scope cF(HyperChoice) ] \
         -value HYPER,YEOH,1
      euidl::label $childsite.lbl5 -text [msgcat::mc "Yeoh"]

      grid $childsite.chk5 -column 0 -row 14 -sticky e
      grid $childsite.lbl5 -column 1 -row 14 -sticky w

      unset childsite

      wizardstate "normal" 

      update idletasks
   }

# --------------------------------------------------------------
#  Function Name: CreateFittingFunction
#  Purpose:       Create the Constitutive Function
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc CreateFittingFunction {} {
      variable cF
      variable matid
      variable NLOpts
      variable CoeffSeed
      variable matStates
      variable funcDefnParams
      variable optionalCaseName
      variable coefftable
      global tcl_platform

      #If the function is to be created by case command
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {         
         set caseList [ split $funcDefnParams(0,1) , ]
         set comboFuncName [lindex $caseList 1]
         
         #make sure the name is not filled with blanks
         set optionalCaseName [string trim $optionalCaseName]
         if { [string equal $optionalCaseName ""] } {
            ans_senderror 2 "Invalid Case/Function Name for Fitting Function \n"
            return
         }
         set cF(HyperChoice) "CASE,$optionalCaseName,"

          catch {ans_sendcommand TBFT,FCASE,$matid,NEW,$comboFuncName,$optionalCaseName}
          for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
              catch {ans_sendcommand TBFT,FADD,$matid,$funcDefnParams($iRIndex,1)}
          }
          catch {ans_sendcommand TBFT,FCASE,$matid,FINI}

      } else {
          #Additional check for hyper,mooney
          set ModelParams [split $cF(HyperChoice) ,] 
          if { [string equal -nocase -length 4 [lindex $ModelParams 1] "MOON"]} {
            set morder [lindex $ModelParams 2]
            if { !( $morder == 2 || $morder == 3 || $morder == 5 || $morder == 9) } {
               ans_senderror 2 "Invalid Num Coeffs for Mooney Model \n"
               return
            }          
          }
          catch {ans_sendcommand TBFT,FADD,$matid,$cF(HyperChoice)}
      }

      refreshL
      update
      refresh
      set fname [ CommandToFuncName $cF(HyperChoice) ]

      #ReadCoeffsFromDatabase $matid $fname
      #UpdateCoeffTableParameters 
      #UpdateFunctionParametersFromDatabase
      NonLinearSettings
      refresh
   }
# --------------------------------------------------------------
#  Function Name: InitializeCoefficients
#  Purpose:       Initialize Coefficients to 1
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc InitializeCoefficients {} {
      variable CoeffSeed      
      variable coefftable
      variable matStates
      variable cF

      for {set i 0} {$i < $CoeffSeed(numcoeff) } {incr i 1} {
         set CoeffSeed($i,-1) [expr $i+1]  
         set CoeffSeed($i,0) "C[expr $i+1]"
         set CoeffSeed($i,1) 1
         if { $matStates(Creep) == 1 } {
            set CoeffSeed($i,1) 0
         }
         set CoeffSeed($i,2) 0
      }

      ToggleFixColumnState normal  
   }

# --------------------------------------------------------------
#  Function Name: InitializeCoefficientNames
#  Purpose:       Initialize Coefficient Names
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc InitializeCoefficientNames {} {
      variable CoeffSeed      
      variable cF
      variable funcDefnParams
      variable matStates

      set choice ""
      if [info exists cF(HyperChoice)]    {
            set choice $cF(HyperChoice)
      }
    set inp [split $choice ,] 

    #Setting Coefficients for Hyperelastic
    set names {}
    if { [string equal -nocase -length 4 [lindex $inp 1] "MOON"]} {
        set order [lindex $inp 2]
        switch [lindex $inp 2] {
            2 {
                set names {C10 C01}
            }
            3 {
                set names {C10 C01 C11}
            }
            5 {
                set names {C10 C01 C20 C11 C02}
            }
            9 {
                set names {C10 C01 C20 C11 C02 C30 C21 C12 C03}
            }
        }
        set j 0
        foreach n $names {
            set CoeffSeed($j,0) ${n}
            incr j
        }

        set CoeffSeed($j,0) d
        incr j
    }

    if { [string equal -nocase -length 4 [lindex $inp 1] "OGDE"]} {
        set names {mu a}
        set order [lindex $inp 2]
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}_$i
                incr j
            }
        }
        for {set i 1} {$i <= $order} {incr i 1} {
            set CoeffSeed($j,0) d_$i
            incr j
        }

    }

    if { [string equal -nocase -length 4 [lindex $inp 1] "NEO"]} {
        set names {mu d}
        set order 1
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}
                incr j
            }
        }
    }

    if { [string equal -nocase -length 4 [lindex $inp 1] "POLY"]} {
        set order [lindex $inp 2]
        set j 0
        for {set i 0} {$i<=$order} {incr i} {
            if {$i != 0} {
                set k $i
                for {set m 0} {$m<=$i} {incr m} {
                    set CoeffSeed($j,0) C${k}${m}
                    incr j
                    incr k -1
                }
            }
        }
        for {set p 1} {$p <= $order} {incr p} {
            set CoeffSeed($j,0) d_$p
            incr j
        }
    }

    if { [string equal -nocase -length 4 [lindex $inp 1] "BOYCE"]} {
        set names {mu {lambda L} d}
        set order 1
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}
                incr j
            }
        }
    }    

    if { [string equal -nocase -length 4 [lindex $inp 1] "ETUB"]} {
        set names {Gc Ge Beta Delta}
        set order 1
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}
                incr j
            }
        }
    }    

    if { [string equal -nocase -length 4 [lindex $inp 1] "GENT"]} {
        set names {mu Jm d}
        set order 1
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}
                incr j
            }
        }
    }    

    if { [string equal -nocase -length 4 [lindex $inp 1] "YEOH"]} {
        set order [lindex $inp 2]
        set names {c}
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
                foreach n $names {
                set CoeffSeed($j,0) ${n}_${i}0
                incr j
                }
        }
        for {set i 1} {$i <= $order} {incr i 1} {
            set CoeffSeed($j,0) d_$i
            incr j
        }
    }

    if { [string equal -nocase -length 4 [lindex $inp 1] "BLAT"]} {
        set names {mu}
        set order 1
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}
                incr j
            }
        }
    }

    if { [string equal -nocase -length 4 [lindex $inp 1] "FOAM"]} {
        set names {mu a}
        set order [lindex $inp 2]
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}_$i
                incr j
            }
        }
        for {set i 1} {$i <= $order} {incr i 1} {
            set CoeffSeed($j,0) b_$i
            incr j
        }
    }   


    #Setting coefficients for chaboche
    if {   [string equal -nocase -length 4 [lindex $inp 1] "CHAB"]
        || $matStates(Plast) == 1 } {
        set names {C G}
        set order [lindex $inp 2]
        if { [string equal -nocase -length 4 $order "UNDE"]} {
            set order 0
        }
        
#        set j 0
#        for {set i 1} {$i <= $order} {incr i 1} {
#            foreach n $names {
#                set CoeffSeed($j,0) ${n}_$i
#                incr j
#            }
#        }
#        set CoeffSeed($j,0) "YS"

        set j 0
        for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
            set paramList [split $funcDefnParams($iRIndex,1) ,]
            if { [llength $paramList] == 3 } {
                set type [lindex $paramList 1]
                set value [lindex $paramList 2]
                set type [string trim $type]
                if { [string equal -nocase -length 4 $type "CHAB"] } {
                    set terms 0
                    if { ! [string equal -nocase -length 4 $value "none"] } {
                        set terms [expr $value ]
                    }
                    for {set i 1} {$i <= $terms} {incr i 1} {
                         set CoeffSeed($j,0) "C$i Kin"
                         incr j
                         set CoeffSeed($j,0) "G$i Kin"
                         incr j
                    }
                    set CoeffSeed($j,0) "YS Kin"
                 }
             }
         }

         for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
             set paramList [split $funcDefnParams($iRIndex,1) ,]
             if { [llength $paramList] == 3 } {
                 set type [lindex $paramList 1]
                 set value [lindex $paramList 2]
                 set type [string trim $type]
                 if { [string equal -nocase -length 4 $type "MISO"] } {
                    set terms 0
                    if { ! [string equal -nocase -length 4 $value "none"] } {
                        set terms [expr $value ]
                    }
                     for {set i 1} {$i <= $terms} {incr i 1} {
                          set CoeffSeed($j,0) "Eps$i Miso"
                          incr j
                          set CoeffSeed($j,0) "Sig$i Miso"
                          incr j
                     }
                  }
                  if { [string equal -nocase -length 4 $type "BISO"] } {
                     set CoeffSeed($j,0) "YS"
                     incr j
                     set CoeffSeed($j,0) "TM"
                     incr j
                  }
                  if { [string equal -nocase -length 4 $type "VOCE"] } {
                     set CoeffSeed($j,0) "YS"
                     incr j
                     set CoeffSeed($j,0) "R0"
                     incr j
                     set CoeffSeed($j,0) "RInf"
                     incr j
                     set CoeffSeed($j,0) "B"
                     incr j
                  }
                  if { [string equal -nocase -length 4 $type "POWE"] } {
                     set CoeffSeed($j,0) "YS0"
                     incr j
                     set CoeffSeed($j,0) "N"
                     incr j
                     set CoeffSeed($j,0) "G"
                     incr j
                  }
              }
          }
        return
    }   

    
#Setting Coefficients for Creep

    if { [string equal -nocase -length 4 [lindex $inp 0] "CREEP"]} { 
        if { [string equal -nocase -length 4 [lindex $inp 1] "MSHA"]} { 
            set CoeffSeed(0,0) C1^2
            } 
        if { [string equal -nocase -length 4 [lindex $inp 1] "PSRP"]} { 
        set names {C1 C2 C3 C4 C7 C8 C9 C10 C11 C12}
        set order 1
        set j 0
        for {set i 1} {$i <= $order} {incr i 1} {
            foreach n $names {
                set CoeffSeed($j,0) ${n}
                incr j
            }
        }
   }
}      
   

#Setting Coefficients for Visco

    if { [string equal -nocase -length 4 [lindex $inp 0] "VISCO"]} {
       set numShiftParams(wlf) 3
       set numShiftParams(tn) 2
       set numShiftParams(none) 0        
       set j 0
       for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
           set paramList [split $funcDefnParams($iRIndex,1) ,]
           if { [llength $paramList] == 3 } {
               set type [lindex $paramList 1]
               set value [lindex $paramList 2]
               set type [string trim $type]
               if { [string equal -nocase -length 4 $type "pshear"] } {
                   if { ! [string equal -nocase -length 4 $value "none"] } {
                       set terms [expr $value ]
                       set CoeffSeed($j,0) "A0  Shear"
                       incr j
                   } else {
                       set terms 0
                   }
                   for {set i 1} {$i <= $terms} {incr i 1} {
                        set CoeffSeed($j,0) "A$i Shear"
                        incr j
                        set CoeffSeed($j,0) "t$i Shear"
                        incr j
                   }
                }
            }
        }

       for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
           set paramList [split $funcDefnParams($iRIndex,1) ,]
           if { [llength $paramList] == 3 } {
               set type [lindex $paramList 1]
               set value [lindex $paramList 2]
               set type [string trim $type]
               if { [string equal -nocase -length 4 $type "pbulk"] } {
                   if { ! [string equal -nocase -length 4 $value "none"] } {
                       set terms [expr  $value ]
                       set CoeffSeed($j,0) "A0 Bulk"
                       incr j
                   } else {
                       set terms 0
                   }
                   for {set i 1} {$i <= $terms} {incr i 1} {
                        set CoeffSeed($j,0) "A$i Bulk"
                        incr j
                        set CoeffSeed($j,0) "t$i Bulk"
                        incr j
                   }
                }
            }
        }

       for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
           set paramList [split $funcDefnParams($iRIndex,1) ,]
           if { [llength $paramList] == 3 } {
               set type [lindex $paramList 1]
               set value [lindex $paramList 2]
               set type [string trim $type]
               if { [string equal -nocase -length 4 $type "shift"] } {
                   set value [string tolower $value]
                   set terms $numShiftParams($value)
                    set CoeffSeed($j,0) tref
                    incr j
                   if {$terms>0} {
                       set CoeffSeed($j,0) C1
                       incr j
                   }
                   if {$terms>2} {
                       set CoeffSeed($j,0) C2
                       incr j
                   }
                }
            }
        }    

   }
}

# --------------------------------------------------------------
#  Function Name: ToggleFixColumnState
#  Purpose:       Updates the Coefficient Table Parameters
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
proc ToggleFixColumnState { colstate } {
      variable coefftable
      variable parent
      
      set childsite [$parent component childsite]
      set funcparamframe $childsite.funcparamframe
      set childsite [$funcparamframe component childsite]

      for { set iIndex 0} { $iIndex < 50 } { incr iIndex 1 } {
         $childsite.coefffixcheck${iIndex} configure -state $colstate
      }
}

# --------------------------------------------------------------
#  Function Name: UpdateCoeffTableParameters
#  Purpose:       Updates the Coefficient Table Parameters
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc UpdateCoeffTableParameters {} {
      variable coefftable
      variable CoeffSeed
      variable matid
      variable cF
      variable matStates
      variable parent
      
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      set childsite [$parent component childsite]
      set funcparamframe $childsite.funcparamframe
      set childsite [$funcparamframe component childsite]


      #Return if it is not a Function
      #set fname [ CommandToFuncName $cF(HyperChoice) ]
      #set fname [string trim $fname]
      #set existKey [ ConstitutiveFunctionExists $matid $fname ]

      #if { $existKey == 0 } {
      #      return
      #}
      
      #Before u change the number of row unconfigure all comboboxes
      for { set iIndex 0 } { $iIndex < 50 } { incr iIndex 1 } {
         $coefftable window configure $iIndex,2 -window [list ]
      }
      
      if { [info exists coefftable] && [info exists CoeffSeed(numcoeff)] } {
          $coefftable configure -rows [expr $CoeffSeed(numcoeff)+1] -cols  4
          ToggleFixColumnState normal  

          for { set iIndex 0 } { $iIndex < $CoeffSeed(numcoeff) } { incr iIndex 1 } {
             $coefftable window configure $iIndex,2 -window $childsite.coefffixcheck${iIndex} -stick ew
          }
      }

   }
   
# --------------------------------------------------------------
#  Function Name: ReadConstitutiveFunctionParametersFromDatabase
#  Purpose:       Updates the Coefficient Table Parameters
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc UpdateFunctionParametersFromDatabase {} {
      variable NLOpts
      variable cF
      variable matid
      
      
      #Return if it is not a Function
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      set fname [string trim $fname]
      set existKey [ ConstitutiveFunctionExists $matid $fname ]
      if { $existKey == 0 } {
         return
      }

      #Normalized Flag
      set NLOpts(1) [ans_getvalue tbft,$matid,,$fname,norm]

      #Number of iterations
      set NLOpts(2) [ans_getvalue tbft,$matid,,$fname,numi]
      
      #Convergence Tolerance
      set NLOpts(3) [ans_getvalue tbft,$matid,,$fname,ctol]

      #Residual Tolerance
      set NLOpts(4) [ans_getvalue tbft,$matid,,$fname,rtol]

      #Residual Tolerance
      set NLOpts(5) [ans_getvalue tbft,$matid,,$fname,rtol]

      #Residual Tolerance
      set NLOpts(6) [ans_getvalue tbft,$matid,,$fname,tdep]

      #Update Visco Specific Data    
      UpdateViscoCaseTable
      
   }


# --------------------------------------------------------------
#  Function Name: UpdateViscoCaseTable
#  Purpose:       Reads Visco Specific Data from Database
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc UpdateViscoCaseTable {} {
      variable cF
      variable matid
      variable partialSolveParam
      variable referenceTemperature
      variable optionalCaseName
      variable funcDefnTable
      variable funcDefnParams
      #Return if it is not a Function
      set optionalCaseName [ CommandToFuncName $cF(HyperChoice) ]
      set optionalCaseName [string trim $optionalCaseName]
      set existKey [ ConstitutiveFunctionExists $matid $optionalCaseName ]
      if { $existKey == 0 } {
         return
      }
      
      set funcType [ ans_getvalue tbft,$matid,,$optionalCaseName,type]
      set funcType [string trim $funcType]
         
      #If it is Visco Set Partial Solve Params
      #Later make this more general with a function that verifies if it is a partial solve situtation
      if { [string equal -length 4 -nocase $funcType "pvhe"] } {
         set sOrder [ans_getvalue tbft,$matid,,$optionalCaseName,sorder]
         if { $sOrder == 0 } { set sOrder NONE }
         set bOrder [ans_getvalue tbft,$matid,,$optionalCaseName,border]
         if { $bOrder == 0 } { set bOrder NONE }
         set shiftParam [ans_getvalue tbft,$matid,,$optionalCaseName,shift]
         ClearFunctionDefnTable
         AppendItemToFunctionDefnTable "new,pvhe,$optionalCaseName"
         AppendItemToFunctionDefnTable "visco,pshear,$sOrder"
         AppendItemToFunctionDefnTable "visco,pbulk,$bOrder"
         AppendItemToFunctionDefnTable "visco,shift,$shiftParam"
         AppendItemToFunctionDefnTable "fini"

         set referenceTemperature [ans_getvalue tbft,$matid,,$optionalCaseName,tref]
         set partialSolveParam [ans_getvalue tbft,$matid,,$optionalCaseName,comp]
         set partialSolveParam [string trim $partialSolveParam]
         UpdatePartialSolveFromDatabase
         
         #Set the case name
         if { [info exists funcDefnTable] && [info exists funcDefnParams(numparams)] } {
            for { set iIndex -1 } { $iIndex < $funcDefnParams(numparams) } { incr iIndex 1 } {
               $funcDefnTable height $iIndex default
            }
            $funcDefnTable hide row 0
            $funcDefnTable hide row [expr $funcDefnParams(numparams) - 1]
            $funcDefnTable configure -titlerows $funcDefnParams(numparams)
         }
      }     
      if { [string equal -length 4 -nocase $funcType "chab"] } {
         set kOrder [ans_getvalue tbft,$matid,,$optionalCaseName,korder]
         if { $kOrder == 0 } { set kOrder NONE }
         set iType [ans_getvalue tbft,$matid,,$optionalCaseName,ihtype]
         set iOrder [ans_getvalue tbft,$matid,,$optionalCaseName,iorder]
         if { $iOrder == 0 } { set iOrder NONE }
         ClearFunctionDefnTable
         AppendItemToFunctionDefnTable "new,cpla,$optionalCaseName"
         AppendItemToFunctionDefnTable "plas,chab,$kOrder"
         if { $iType == 1 } {   AppendItemToFunctionDefnTable "plas,biso,"        }
         if { $iType == 2 } {   AppendItemToFunctionDefnTable "plas,miso,$iOrder" }
         if { $iType == 3 } {   AppendItemToFunctionDefnTable "plas,voce,"        }
         if { $iType == 4 } {   AppendItemToFunctionDefnTable "plas,powe,"        }
         AppendItemToFunctionDefnTable "fini"

         if { [info exists funcDefnTable] && [info exists funcDefnParams(numparams)] } {
            for { set iIndex -1 } { $iIndex < $funcDefnParams(numparams) } { incr iIndex 1 } {
               $funcDefnTable height $iIndex default
            }
            $funcDefnTable hide row 0
            $funcDefnTable hide col 1
            $funcDefnTable hide row [expr $funcDefnParams(numparams) - 1]
            $funcDefnTable configure -titlerows $funcDefnParams(numparams)
         }
      }     

   }
# --------------------------------------------------------------
#  Function Name: SolveFittingFunction
#  Purpose:       Solve and Updates the Coefficients
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc SolveFittingFunction {} {
      variable cF
      variable matid
      variable NLOpts
      variable CoeffSeed
      variable funcDefnParams
      variable optionalCaseName
      variable matStates
      variable partialSolveParam
      variable referenceTemperature
      global tcl_platform
      variable funcDefnParams
      variable parent

      set iNumErr [ans_evalexpr erinqr(5)]

      StatusBarControl 2
      #If Number of experimental data is zero quit
      set NumExps [ans_getvalue tbft,$matid,nexp]     
      if { $NumExps < 1 } {
         StatusBarControl 4
         ans_senderror 2 "Cannot Solve Function without Experimental Data"
         return
      }

      set CurveFitMatIDExists [CurveFitExists $matid]
      if { $CurveFitMatIDExists == 0 } {
         StatusBarControl 4
         return
      }

      #Add function if it does not exist or return error
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {         
        set fname $optionalCaseName
      }
      set existKey 0
      set existKey [ ConstitutiveFunctionExists $matid $fname ]
      if { $existKey == 0 } {
         CreateFittingFunction
      } else {
      #Check if the number of terms match else throw an error
         
         set fName $optionalCaseName

         set sStored 0
         set bStored 0
         set kStored 0
         set iStored 0
         set shiftValue "none"
         
         for { set iRIndex 1 } { $iRIndex < [expr $funcDefnParams(numparams) - 1 ] } { incr iRIndex 1 } {
             set paramList [split $funcDefnParams($iRIndex,1) ,]
             if { [llength $paramList] == 3 } {
                set type [lindex $paramList 1]
                set value [lindex $paramList 2]
                puts "Refer $type $value \n"
                set type [string trim $type]
                if {    [string equal -nocase -length 4 $type "pshear"] } {
                   if { ! [string equal -nocase -length 4 $value "none"] } {
                       set sStored $value
                   }
                } elseif { [string equal -nocase -length 4 $type "pbulk"]  } {
                   if { ! [string equal -nocase -length 4 $value "none"] } {
                       set bStored $value
                   }
                } elseif { [string equal -nocase -length 4 $type "shift"] } {
                   set shiftValue [string tolower $value]
                } elseif { [string equal -nocase -length 4 $type "chab"]  } {
                   if { ! [string equal -nocase -length 4 $value "none"] } {
                       set kStored $value
                   }
                } elseif { [string equal -nocase -length 4 $type "powe"]  } {
                    set iStored "powe"
                } elseif { [string equal -nocase -length 4 $type "voce"]  } {
                    set iStored "voce"
                } elseif { [string equal -nocase -length 4 $type "biso"]  } {
                    set iStored "biso"
                } elseif { [string equal -nocase -length 4 $type "miso"]  } {
                    set iStored "miso$value"
                }
             }
         }
         
         if { $matStates(Visco) == 1  } {
            set sOrder 0
            set bOrder 0
            set shValue "none"
            catch { set sOrder [ ans_getvalue tbft,$matid,func,$fName,sorder] }
            catch { set bOrder [ ans_getvalue tbft,$matid,func,$fName,border] }
            catch { set shValue [ ans_getvalue tbft,$matid,func,$fName,shift] }
            set shValue [string trim $shValue]
            if { $sOrder != $sStored || $bOrder != $bStored || ![string equal -nocase -length 4 $shValue $shiftValue] } {
               StatusBarControl 4
               ans_senderror 3 "The order/parameters of the prony model has changed. Use a different case name"
               return
            }
         }

         if { $matStates(Plast) == 1  } {
            set kOrder 0
            set iOrder 0
            set ihtype 0
            
            catch { set kOrder [ ans_getvalue tbft,$matid,func,$fName,korder] }
            catch { set iOrder [ ans_getvalue tbft,$matid,func,$fName,iorder] }
            catch { set ihtype [ ans_getvalue tbft,$matid,func,$fName,ihtype] }
            set ihtype [string trim $ihtype]
            if { $ihtype == 0  } {
                set ihtype "ciso"
            } elseif { $ihtype == 1  } {
                set ihtype "biso"
            } elseif { $ihtype == 2  } {
                set ihtype "miso$iOrder"
            } elseif { $ihtype == 3 } {
                set ihtype "voce"
            } elseif { $ihtype == 4  } {
                set ihtype "powe"
            }
            
            if { $kOrder != $kStored || $ihtype != $iStored } {
               StatusBarControl 4
               ans_senderror 3 "The order/parameters of the chaboche model has changed. Use a different case name"
               return
            }
         }

      }

      set fname [ CommandToFuncName $cF(HyperChoice) ]
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {         
        set fname $optionalCaseName
      }
      set existKey [ ConstitutiveFunctionExists $matid $fname ]
      if { $existKey == 0 } {
         StatusBarControl 4
         ans_senderror 2 "Unable to create Fitting function to solve. Please set correct parameters"
         return
      }
      #Check to see if user forgot to give an Function Name
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {         
         if { ![info exists optionalCaseName] } {
            StatusBarControl 4
            ans_senderror 2 "Case Name has not been input. Give case name before u solve."
            return
         }
         set userName [string trim $optionalCaseName]
         if { $userName == "" } {
            StatusBarControl 4
            ans_senderror 2 "Case Name has not been input. Give case name before u solve."
            return
         }         
      }

      set funcType "unknown"
      set funcName [string trim $fname]
      if { $matStates(Visco) == 1 || $matStates(Plast) == 1 } {         
         set caseList [ split $funcDefnParams(0,1) , ]
         set comboFuncName [lindex $caseList 1]
         set cF(HyperChoice) "CASE,$optionalCaseName,"
         set fname $optionalCaseName
         set CoeffSeed(numcoeff) [ans_getvalue TBFT,$matid,FUNC,$optionalCaseName,ncon]
         
         set fnamelist [split $funcDefnParams(0,1) ,]
         set funcType  [lindex $fnamelist 1]
         set funcType [string trim $funcType]
      } else {
         catch { set funcType [ ans_getvalue tbft,$matid,func,$funcName,type] }
      }

      if {[IsNonlinear $cF(HyperChoice)] == "Yes" || $matStates(Visco) == 1 || $matStates(Creep) == 1 || $matStates(Plast) == 1 } {
         if { [info exists CoeffSeed(numcoeff)] } {
            for {set i 0} {$i < $CoeffSeed(numcoeff)} {incr i 1} {
              if { [info exists CoeffSeed($i,1)] } {
                 catch {ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),[expr $i+1],$CoeffSeed($i,1)}
              }
            }
         }
         
         #If it is Visco Set Partial Solve Params
         #Later make this more general with a function that verifies if it is a partial solve situtation
         if { [string equal -length 4 -nocase $funcType "pvhe"] } {

            if { ! [info exists partialSolveParam]  } {
               StatusBarControl 4
               ans_senderror 2 "Partial Solve Option has not been defined."
               return
            }

            set partialSolveParam [string trim $partialSolveParam]

            if { $partialSolveParam == "" } {
               StatusBarControl 4
               ans_senderror 2 "Partial Solve Option has not been defined."
               return
            }

            #If Partial Solve option is pvhe. We solve at all temps.
            if  { ! [string equal -length 4 -nocase $partialSolveParam "pvhe"] } {
               if { ! [info exists referenceTemperature] } {
                  StatusBarControl 4
                  ans_senderror 2 "Reference Temperature has not been defined."
                  return
               } else {
                  set referenceTemperature [string trim $referenceTemperature]
                  if { $referenceTemperature == "" } {
                     StatusBarControl 4
                     ans_senderror 2 "Reference Temperature has not been defined."
                     return
                  } else {
                     catch { ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),tref,$referenceTemperature }
                  }
               }
            }
            catch { ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),comp,$partialSolveParam }
         }
         
         if { [info exists CoeffSeed(numcoeff)] } {
            #if the function is ogden,poly,yeoh,arruda,gent you can fix only the non volu coeffs
            set numFixable $CoeffSeed(numcoeff)
            
            #Set the number of coefficients that can be fixed for Hyper models with Volumeteric coeffs
            #Volumetric coeffs are cannot be fixed >now< as they are linear.
            if {[IsNonlinear $cF(HyperChoice)] == "Yes" && $matStates(Hyper) == 1 } {
               if {    [string equal -nocase -length 4 "boyce" $funcType] || [string equal -nocase -length 4 "gent" $funcType] } {
                  set numFixable [expr $numFixable - 1]
               }

               if { [string equal -nocase -length 4 "ogde" $funcType] } {
                  set numFixable [expr ($CoeffSeed(numcoeff)/3)*2]
               }
            }

            for {set i 0} {$i < $numFixable} {incr i 1} {
              if { [info exists CoeffSeed($i,2)] } {
                 catch {ans_sendcommand TBFT,FIX,$matid,$cF(HyperChoice),[expr $i+1],$CoeffSeed($i,2)}
              }
            }
         }
        
         #Temperature Dependent Solve
         if { [info exists NLOpts(6)] } {
            if { $NLOpts(6) == 1 } {
               catch { ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),tdep,$NLOpts(6) }

               if { ! [info exists referenceTemperature] } {
                   StatusBarControl 4
                   ans_senderror 2 "Reference Temperature has not been defined."
                   return
               } else {
                   set referenceTemperature [string trim $referenceTemperature]
                   if { $referenceTemperature == "" } {
                        StatusBarControl 4
                        ans_senderror 2 "Reference Temperature has not been defined."
                        return
                   } else {
                          catch { ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),tref,$referenceTemperature }
                   }
               }
            }
         }

         ::apdl::noerr 1
         catch {ans_sendcommand TBFT,SOLVE,$matid,$cF(HyperChoice),$NLOpts(1),$NLOpts(2),$NLOpts(3),$NLOpts(4)}
         ::apdl::noerr 0
      } else {

         #Temperature Dependent Solve
         if { [info exists NLOpts(6)] } {
            if { $NLOpts(6) == 1 } {
               catch { ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),tdep,$NLOpts(6) }

               if { ! [info exists referenceTemperature] } {
                   StatusBarControl 4
                   ans_senderror 2 "Reference Temperature has not been defined."
                   return
               } else {
                   set referenceTemperature [string trim $referenceTemperature]
                   if { $referenceTemperature == "" } {
                       StatusBarControl 4
                       ans_senderror 2 "Reference Temperature has not been defined."
                       return
                   } else {
                          catch { ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),tref,$referenceTemperature }
                   }
               }
            }
         }
         ::apdl::noerr 1
         catch {ans_sendcommand TBFT,SOLVE,$matid,$cF(HyperChoice),$NLOpts(1) }
         ::apdl::noerr 0
      }

      ReadCoeffsFromDatabase $matid $fname
      set NLOpts(5) "Undefined"
      ::apdl::noerr 1
      catch { set NLOpts(5) [ans_getvalue TBFT,$matid,FUNC,$fname,resi] }
      ::apdl::noerr 0
      
      StatusBarControl 3

      set iNumErrAftSol [ans_evalexpr erinqr(5)]
      
      set ErrorMessage "Solution is Completed \n"
      set iIcon "info"
      if { $iNumErrAftSol != $iNumErr } {
          set iIcon "error"
          set ErrorMessage "Error During Solution.\n"
      }

      tk_messageBox -icon $iIcon -title [msgcat::mc "$iIcon"] -parent $parent \
        -type ok \
        -message [msgcat::mc "$ErrorMessage"]
   }


# --------------------------------------------------------------
#  Function Name: MakeHyperFunc
#  Purpose:       Solve and plot the function
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc MakeHyperFunc {} {
      variable cF
      variable matid
      variable NLOpts
      variable CoeffSeed
      global tcl_platform

      variable editFunc

      catch {ans_sendcommand TBFT,FADD,$matid,$cF(HyperChoice)}
      if {[IsNonlinear $cF(HyperChoice)] == "Yes"} {
         for {set i 0} {$i < $CoeffSeed(numcoeff)} {incr i 1} {
           if { $CoeffSeed($i,1) != "" } {
              catch {ans_sendcommand TBFT,SET,$matid,$cF(HyperChoice),[expr $i+1],$CoeffSeed($i,1)}
           }
         }
         catch {ans_sendcommand TBFT,SOLVE,$matid,$cF(HyperChoice),$NLOpts(1),$NLOpts(2),$NLOpts(3),$NLOpts(4)}
      } else {
         catch {ans_sendcommand TBFT,SOLVE,$matid,$cF(HyperChoice),$NLOpts(1) }
      }


   }


   proc NewFunction {} {
      variable cF
      variable matid
      variable optionalCaseName

      set optionalCaseName "NewCase"
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      ReadCoeffsFromDatabase $matid $fname
      UpdateCoeffTableParameters 
   }
   
   proc ExportToAnsys {} {
      SaveOneFunc
   }

   proc SaveToMemory {} {
      ans_senderror 1 "This Function is not implemented yet"
   }

   proc Solve {} {
      SolveFittingFunction
   }
   
   proc PlotFromPullDown {} {
      variable cF
      variable matid
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      PlotExperimentalData $matid $fname
   }

# --------------------------------------------------------------
#  Function Name: ExperimentExists
#  Purpose:       Function to determine experiment existence
#  Arguments:     Experiment Type
#  Notes:
#
# --------------------------------------------------------------
   proc ExperimentExists {thisMatId ExpType } {

      set existkey 0
      set expnum 1
      set maxExp [ans_getvalue tbft,$thisMatId,nexp]
      set maxExp [ans_evalexpr $maxExp]
      while {$expnum <= $maxExp} {
         set etype [ans_getvalue tbft,$thisMatId,expe,$expnum,type]
         set etype [string trim $etype]
         if { [string equal -nocase $ExpType $etype] } {
            set existkey 1
         }
         incr expnum
      }
      return $existkey
   }

# --------------------------------------------------------------
#  Function Name: CurveFitExists
#  Purpose:       Function to determine curve fit existence
#  Arguments:     MaterialID
#  Notes:
#
# --------------------------------------------------------------
   proc CurveFitExists {thisMatId} {

      set existkey 0
      set fitnum 1
      set maxFit [ans_getvalue tbft,,nmat]
      set maxFit [ans_evalexpr $maxFit]
      while {$fitnum <= $maxFit} {
         set ftype [ans_getvalue tbft,,matnum,$fitnum]
         if { $ftype == $thisMatId } {
            set existkey 1
         }
         incr fitnum
      }
      return $existkey
   }

# --------------------------------------------------------------
#  Function Name: ConstitutiveFunctionExists
#  Purpose:       Function to determine Function existence
#  Arguments:     MaterialID
#  Notes:
#
# --------------------------------------------------------------
    proc ConstitutiveFunctionExists { matId fName } {
        variable existkey
        
        set existkey 0
        if { ! [info exists matId] } {
            return 0
        }

        if { ! [info exists fName] } {
            return 0
        }

        set idExists [CurveFitExists $matId]
        if { $idExists == 0 } {
            return 0
        }

        set existkey 0
        set numFuncs [ans_getvalue tbft,$matId,nfun]

        for { set index 1 } { $index <= $numFuncs } { set index [expr $index + 1] } {
            set curFunc [ans_getvalue tbft,$matId,func,$index,fname]
            set curFunc [string trim $curFunc]
            if { [ string equal $curFunc $fName] } {
                set existkey 1
            }
        }

        return $existkey
    }

# --------------------------------------------------------------
#  Function Name: AddExperimentData
#  Purpose:       Dialog box to define experimental data
#  Arguments:     Experiment Type
#  Notes:         
# 
# --------------------------------------------------------------
   proc AddExperimentData { ExpType } {
      variable parent
      variable childsite
      variable emptyfolder
      variable matid
      variable matModelArr
      variable expCurve
      variable expFile
      variable numExpDataTables
      variable scrolledParent


      variable replacekey

      $parent configure -helpcommand [list ans_loadhelp Hlp_mcf]
      $parent configure -nexttext [msgcat::mc "Next >"]

      set childsite [$parent component childsite]

      LHSCurveFittingTree

      set childsite [$parent component childsite]
      set allchildren [winfo children $childsite]

      set allchildren [winfo children $childsite]

      if {[winfo exists $childsite.plotframe]} {
          destroy $childsite.plotframe
      }   

      if { [lsearch $allchildren "$childsite.funcdefmenuframe"] > -1 } {
           catch { grid remove $childsite.funcdefmenuframe }
      }

      if { [lsearch $allchildren "$childsite.nonlinearsettings"] > -1 } {
         catch { grid remove $childsite.nonlinearsettings }
      }

      if { [lsearch $allchildren "$childsite.funcdefframe"] > -1 } {
         catch { grid remove $childsite.funcdefframe }
      }

      if { [lsearch $allchildren "$childsite.funcparamframe"] > -1 } {
         catch { grid remove $childsite.funcparamframe }
      }

      if { [lsearch $allchildren "$childsite.nonlinearsettings"] > -1 } {
         catch { grid remove $childsite.nonlinearsettings }
      }

      set replacekey [ExperimentExists $matid $ExpType]
      if {$replacekey == 1} {
         set explabel "Replace Experimental Curve"
      } else {
         set explabel "Define Experimental Curve"
      }

      if { [lsearch $allchildren "$childsite.expframe"] > -1 } {
           grid $childsite.expframe -column 1 -row 0 -sticky news -rowspan 2
           grid columnconfigure $childsite 0 -weight 0
           grid columnconfigure $childsite 1 -weight 1
           grid columnconfigure $childsite 2 -weight 0
           grid columnconfigure $childsite 3 -weight 0
           grid columnconfigure $childsite 4 -weight 0
           grid columnconfigure $childsite 5 -weight 0

           set childsitescrolled [$scrolledParent childsite]
           set maxTables $numExpDataTables
           for { set iIndex 0 } { $iIndex < $maxTables } { incr iIndex 1 } {
              DeleteLastExperimentalDataTable $childsitescrolled 
           }
           
           AddAnotherExperimentalDataTable $childsitescrolled $ExpType
           LoadExperimentalData $matid $ExpType
           wizardstate "normal" 
           set childsite [$childsite.expframe component childsite]

           grid rowconfigure $childsite 1 -weight 1
           grid columnconfigure $childsite 0 -weight 1
           grid columnconfigure $childsite 1 -weight 1
           grid columnconfigure $childsite 2 -weight 1
           grid columnconfigure $childsite 3 -weight 1
           grid columnconfigure $childsite 4 -weight 1
           grid columnconfigure $childsite 5 -weight 0
           
           #Configure Add button
           $childsite.addtablebutton configure \
                 -command [ code AddAnotherExperimentalDataTable $childsitescrolled $ExpType ]
           $childsite.deletetablebutton configure \
                 -command [ code DeleteCurrentExperimentalDataTable $childsitescrolled ]
           $childsite.browsetablebutton configure \
                 -command [ code OpenCloseFileBrowseWindow $ExpType ]

      } else {

         set numExpDataTables 0

         set childsite [$parent component childsite]
         set expframe [::euidl::labeledframe $childsite.expframe ]
         $expframe configure -text [msgcat::mc  $explabel]
         grid $expframe -column 1 -row 0 -sticky news -rowspan 2
         #pack $expframe -fill both -expand 1

         set childsite [$expframe component childsite]

         set nicelabel [ExpTypeToTitle $ExpType]
         euidl::label $childsite.title \
               -text [msgcat::mc "%s for Material %s" $nicelabel $matid]
         grid $childsite.title -column 0 -row 0 -columnspan 5 -pady 5 -sticky w

         euidl::button $childsite.addpointbutton \
            -text [msgcat::mc "         "] -state disabled -relief flat

         euidl::button $childsite.deletepointbutton \
            -text [msgcat::mc "         "] -state disabled -relief flat

         euidl::button $childsite.addtablebutton \
            -text [msgcat::mc "Add DataSet"]

         euidl::button $childsite.deletetablebutton \
            -text [msgcat::mc "Delete DataSet"]

         euidl::button $childsite.browsetablebutton \
            -text [msgcat::mc "Read From File"]



         grid $childsite.addpointbutton -column 0 -row 2 -pady 5 -sticky ew -columnspan 1 -padx 0
         grid $childsite.deletepointbutton -column 1 -row 2 -pady 5 -sticky ew -columnspan 1 -padx 0
         grid $childsite.addtablebutton -column 2 -row 2 -pady 5 -sticky ew -columnspan 1 -padx 0
         grid $childsite.deletetablebutton -column 3 -row 2 -pady 5 -sticky ew -columnspan 1 -padx 0
         grid $childsite.browsetablebutton -column 4 -row 2 -pady 5 -sticky ew -columnspan 1 -padx 0

         set expscrolledframe [::euidl::scrolledframe $childsite.newscrolledexpdataframe]
         set scrolledParent $expscrolledframe
         $expscrolledframe configure -width 600 -height 300  -borderwidth 1

         grid $childsite.newscrolledexpdataframe  -column 0 -row 1 -columnspan 5 -sticky news
         set childsitescrolled [$expscrolledframe childsite]

         # Give the tables window more weight so it fill the remaining space
         grid rowconfigure $childsite 1 -weight 1
         grid columnconfigure $childsite 0 -weight 1
         grid columnconfigure $childsite 1 -weight 1
         grid columnconfigure $childsite 2 -weight 1
         grid columnconfigure $childsite 3 -weight 1
         grid columnconfigure $childsite 4 -weight 1
         grid columnconfigure $childsite 5 -weight 0

         wizardstate "normal" 
         $childsite.addtablebutton configure \
               -command [ code AddAnotherExperimentalDataTable $childsitescrolled $ExpType ]
         $childsite.deletetablebutton configure \
               -command [ code DeleteCurrentExperimentalDataTable $childsitescrolled ]
         $childsite.browsetablebutton configure \
               -command [ code OpenCloseFileBrowseWindow $ExpType ]

         AddAnotherExperimentalDataTable $childsitescrolled $ExpType


         LoadExperimentalData $matid $ExpType

         update
         update idletasks
      }
      
      #Configure other stuff
      set nicelabel [ExpTypeToTitle $ExpType]
      $childsite.title configure -text [msgcat::mc "%s for Material %s" $nicelabel $matid]
      
      
      #refreshL
      refresh
   }


# --------------------------------------------------------------
#  Function Name: CreateExperimentTemperatureList
#  Purpose:       Loads Experimental Data from Database
#  Arguments:     MaterialID and ExpType
#  Notes:         
# 
# --------------------------------------------------------------
proc CreateExperimentTemperatureList  { matID expType } {
   variable experimentTempList

   #Get number of experiments
   set numExps [ ans_getvalue tbft,$matID,nexp ] 
   set lExpIndex 0
   set experimentTempList [list ]

   for { set index 1 } { $index <= $numExps } { incr index 1 } {

      set indexminus1 [expr $index - 1 ]
      set curExpType "unknown"
      set curExpType [ans_getvalue tbft,$matID,expe,$index,type]
      set curExpType [string trim $curExpType]

      #If experiment type matches      
      if { [string equal -nocase $expType $curExpType] || [string equal -nocase $expType "all" ]} {
         #Load Experimental Data Attribs
         set numAttribs [ans_getvalue tbft,$matID,expe,$index,attnum]
         set searchStatus [lsearch $experimentTempList "all"]
         if { $searchStatus == -1 } {
            lappend experimentTempList "all" "all"
         }
         for { set iAttIndex 0 } { $iAttIndex < $numAttribs} { incr iAttIndex 1 } {
            set attIPlus [expr $iAttIndex+1]
            set attName [ans_getvalue tbft,$matID,expe,$index,attname,$attIPlus]
            set attValD [ans_getvalue tbft,$matID,expe,$index,attvald,$attIPlus]
            if { [string equal -nocase -length 4 $attName "temp"] } {
               #If it already is not in the list append
               set searchStatus [lsearch $experimentTempList $attValD]
               if { $searchStatus == -1 } {
                  lappend experimentTempList $attValD $attValD
               }
            }
         }
      }
   }
   
}

# --------------------------------------------------------------
#  Function Name: LoadExperimentalData
#  Purpose:       Loads Experimental Data from Database
#  Arguments:     MaterialID and ExpType
#  Notes:         
# 
# --------------------------------------------------------------
proc LoadExperimentalData { matID expType } {
   variable scrolledParent
   variable validAttribList
   variable matStates
   variable numExpDataTables
   variable validAttribList
   
   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
   }

   if { ! [info exists validAttribList ] } {
      InitializeValidAttribs
   }

   set eExists [ExperimentExists $matID $expType]
   if { $eExists != 1 } {
      return 0
   }

   set childsitescrolled [$scrolledParent childsite]
   DeleteLastExperimentalDataTable $childsitescrolled
   
   set rIndex 0
   set cIndex 0
   set colSize 0
   set rowSize 0
   catch { unset myarray }
   set expdatatemp(numrow) 0
   set expdatatemp(numcol) 0
   set maxColSize 0

   set numExps [ ans_getvalue tbft,$matID,nexp ] 
   set lExpIndex 0

   for { set index 1 } { $index <= $numExps } { incr index 1 } {

      set indexminus1 [expr $index - 1 ]
      catch { unset expdata$index }
      catch { unset expattribdata$index }

      set curExpType "unknown"
      set curExpType [ans_getvalue tbft,$matID,expe,$index,type]
      set curExpType [string trim $curExpType]
      
      if { [string equal -nocase $expType $curExpType] } {
         AddAnotherExperimentalDataTable $childsitescrolled $expType
         set lExpIndex [expr $lExpIndex + 1]

         set rowSize [ans_getvalue tbft,$matID,expe,$index,numrow]

         #Loop through all points
         for { set rIndex 0 } { $rIndex < $rowSize } { incr rIndex 1 } {
            set rPlus [expr $rIndex+1]
            set colSize [ans_getvalue tbft,$matID,expe,$index,numcol,$rPlus]
            if { $maxColSize < $colSize } {
               set maxColSize $colSize
            }
            set expdatatemp(numcol) [expr $colSize+1]
            set expdatatemp($rIndex,-1) [expr $rIndex+1]
            for { set cIndex 0 } { $cIndex < $colSize } { incr cIndex 1 } {
               set cPlus [expr $cIndex+1]
               set expdatatemp($rIndex,$cIndex) \
                  [ans_getvalue tbft,$matID,expe,$index,data,$rPlus,$cPlus]              
            }
         }

         #copy the data
         set expdatatemp(numrow) $rowSize
         set expdatatemp(numcol) $maxColSize
         array set expdata$lExpIndex [array get expdatatemp]
         
         
         #Load Experimental Data Attribs
         set expAttribDataTemp(numrow) [ans_getvalue tbft,$matID,expe,$index,attnum]
         set expAttribDataTemp(numcol) 2
         set iValAttInd 0
         for { set iAttIndex 0 } { $iAttIndex < $expAttribDataTemp(numrow) } { incr iAttIndex 1 } {
            set attIndxPlus [expr $iAttIndex+1]
            set curAttName [ans_getvalue tbft,$matID,expe,$index,attname,$attIndxPlus]
            set isValidAttrib 0
            set isValidAttrib [ IsValidAttrib $expType $curAttName ]
            if { $isValidAttrib == 1 } {
               set expAttribDataTemp($iValAttInd,0) [ans_getvalue tbft,$matID,expe,$index,attname,$attIndxPlus]
               set expAttribDataTemp($iValAttInd,1) [ans_getvalue tbft,$matID,expe,$index,attvals,$attIndxPlus]
               set expAttribDataTemp($iValAttInd,1) [string trim $expAttribDataTemp($iValAttInd,1) ]
               if { $expAttribDataTemp($iValAttInd,1) == "undefined" || $expAttribDataTemp($iValAttInd,1) == "" } {
                  set attValI [ans_getvalue tbft,$matID,expe,$index,attvali,$attIndxPlus]
                  set attValD [ans_getvalue tbft,$matID,expe,$index,attvald,$attIndxPlus]
                  set attValS [ans_getvalue tbft,$matID,expe,$index,attvals,$attIndxPlus]
                  if { $attValS != "" } {
                     set expAttribDataTemp($iValAttInd,1) $attValS
                  }
                  if { $attValI != 0 } {
                     set expAttribDataTemp($iValAttInd,1) $attValI
                  }
                  if { $attValD != 0 } {
                     set expAttribDataTemp($iValAttInd,1) $attValD
                  }
               }
               incr iValAttInd 1
            }
         }

         set expAttribDataTemp(numrow) $iValAttInd

         set expdatatemp(numrow) $rowSize
         set expdatatemp(numcol) $maxColSize
         array set expdata$lExpIndex [array get expdatatemp]

         set expAttribDataTemp(-1,0) "Additional Param"
         set expAttribDataTemp(-1,1) "Value"
         array set expattribdata$lExpIndex [array get expAttribDataTemp]
         UpdateTablePropetries $lExpIndex $childsitescrolled

         UpdateColumnNamesFromTclArray $lExpIndex

         #For Foam add a f to the experiment name and query
         set expIndex $lExpIndex
         set ncol [array get expdata$expIndex numcol]
         set ncol [lindex $ncol 1]
         if { $ncol == 3 } {
            set isUnia [string equal -nocase -length 4 "unia" $expType]
            set isBiax [string equal -nocase -length 4 "biax" $expType]
            set isShea [string equal -nocase -length 4 "shea" $expType]
            set isSShea [string equal -nocase -length 4 "sshe" $expType]
            if { ($isUnia == 1 || $isBiax == 1 || $isShea == 1) && $isSShea != 1 } {

                 set newExpType "f$expType"

                 #Now fill the headers
                 set newExpType [string trim $newExpType]
                 set newExpType [string tolower $newExpType]

                 for { set iIndex 0 } { $iIndex < $validAttribList($newExpType,ncol) } { incr iIndex 1 } {
                    set expdata[expr $numExpDataTables](-1,$iIndex) $validAttribList($newExpType,col,$iIndex)
                 }

            }
         }
         
         #3 cols mean freq domain data
         if { $ncol == 3 } {
            set issdec [string equal -nocase -length 4 "sdec" $expType]
            set isbdec [string equal -nocase -length 4 "bdec" $expType]
            if { $issdec == 1 || $isbdec == 1  } {
                set expdatatemp(-1,0) "FREQ"
                set expdatatemp(-1,1) "STORAGE MOD"
                set expdatatemp(-1,2) "LOSS MOD"
            }
         }
         array set expdata$lExpIndex [array get expdatatemp]
         
      }
   }
   


   return 1
}

# --------------------------------------------------------------
#  Function Name: UpdateTablePropetries
#  Purpose:       Updates Tk Table Attribs
#  Arguments:  
#  Notes:
#
# --------------------------------------------------------------
proc UpdateTablePropetries { expIndex parentdialog } {
   variable parent
   variable expFile
   variable numExpDataTables
   variable validAttribList

   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
       variable expnumrow$index
       variable expnumcol$index
   }

   #show exp data
   set nrow 0
   set ncol 0
   set nrow [array get expdata$expIndex numrow]
   set nrow [lindex $nrow 1]
   set ncol [array get expdata$expIndex numcol]
   set ncol [lindex $ncol 1]
   $parentdialog.expdatatable$expIndex configure \
     -rows [expr $nrow + 1]\
     -cols [expr $ncol + 1]

   #show exp data attribs
   set nrow [array get expattribdata$expIndex numrow]
   set nrow [lindex $nrow 1]
   set ncol [array get expattribdata$expIndex numcol]
   set ncol [lindex $ncol 1]
   $parentdialog.expattribtable$expIndex configure \
     -rows [expr $nrow + 1]\
     -cols [expr $ncol + 1]

   $parentdialog.expattribtable$expIndex configure -titlecols 2
   #$parentdialog.expattribtable$expIndex height -1 0
}

# --------------------------------------------------------------
#  Function Name: AddAnotherExperimentalDataTable
#  Purpose:       Adds another experimental data table
#  Arguments:  
#  Notes:
#
# --------------------------------------------------------------
proc AddAnotherExperimentalDataTable { parentdialog expType } {
   variable numExpDataTables
   variable parent
   variable expFile
   variable currentExpIndex
   variable validAttribList
   variable scrolledParent

   if { ! [info exists validAttribList ] } {
      InitializeValidAttribs
   }

   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
       variable expnumrow$index
       variable expnumcol$index
   }

   set numExpDataTables [expr $numExpDataTables + 1 ]
   SetCurrentExpIndex $numExpDataTables
   

   set expFile($numExpDataTables) ""
   set expdata[expr $numExpDataTables](-1,-1) ""
   set expdata[expr $numExpDataTables](-1,0) "Strain"
   set expdata[expr $numExpDataTables](-1,1) "Stress"
   set expdata[expr $numExpDataTables](0,-1) 1
   set expdata[expr $numExpDataTables](0,0) ""
   set expdata[expr $numExpDataTables](0,1) ""

   euidl::table $parentdialog.expdatatable$numExpDataTables \
         -variable [scope expdata$numExpDataTables ] \
         -rowseparator \n \
         -colseparator \t \
         -validate focusout \
         -validatedata ansreal \
         -maxheight 5000 \
         -colstretchmode fill \
         -titlerows 1

   $parentdialog.expdatatable$numExpDataTables configure \
         -rows 2 \
         -cols 3 

   $parentdialog.expdatatable$numExpDataTables selection clear all
   $parentdialog.expdatatable$numExpDataTables selection set 0,0
   $parentdialog.expdatatable$numExpDataTables activate 0,0
   $parentdialog.expdatatable$numExpDataTables selection anchor 0,0
   $parentdialog.expdatatable$numExpDataTables see active

   $parentdialog.expdatatable$numExpDataTables width -1 5
   
   if { $numExpDataTables != 1 } {
      $parentdialog.expdatatable$numExpDataTables width -1 0
   }

   set expattribdata[expr $numExpDataTables](-1,-1) ""
   set expattribdata[expr $numExpDataTables](-1,0) "Addl Param Name"
   set expattribdata[expr $numExpDataTables](-1,1) "Value"
   set expattribdata[expr $numExpDataTables](0,-1) ""
   set expattribdata[expr $numExpDataTables](0,0) ""
   set expattribdata[expr $numExpDataTables](0,1) ""

   euidl::table $parentdialog.expattribtable$numExpDataTables \
         -variable [scope expattribdata$numExpDataTables ] \
         -rowseparator \n \
         -colseparator \t \
         -validate focusout \
         -maxheight 5000 \
         -colstretchmode fill \
         -takefocus 0 \
         -titlerows 1
   $parentdialog.expattribtable$numExpDataTables width -1 0

   $parentdialog.expattribtable$numExpDataTables configure \
         -rows 1 \
         -cols 3 
   $parentdialog.expattribtable$numExpDataTables width -1 0

   $parentdialog.expattribtable$numExpDataTables selection clear all
   $parentdialog.expattribtable$numExpDataTables selection set 0,0
   $parentdialog.expattribtable$numExpDataTables activate 0,0
   $parentdialog.expattribtable$numExpDataTables selection anchor 0,0
   $parentdialog.expattribtable$numExpDataTables see active
   $parentdialog.expattribtable$numExpDataTables configure -titlecols 2
   #$parentdialog.expattribtable$numExpDataTables height -1 0

   if { $numExpDataTables == 1 } {
      grid $parentdialog.expattribtable$numExpDataTables  \
         -column [expr 2*($numExpDataTables-1) ] -row 3 -columnspan 1  -sticky nse \
         -padx 0 -pady 0 -ipadx 0 -ipady 0
   } else {
      grid $parentdialog.expattribtable$numExpDataTables  \
         -column [expr 2*($numExpDataTables-1) ] -row 3 -columnspan 1  -sticky nsew \
         -padx 0 -pady 0 -ipadx 0 -ipady 0
   }
   grid $parentdialog.expdatatable$numExpDataTables  \
      -column [expr 2*($numExpDataTables-1) ] -row 4 -columnspan 1  -sticky nsew \
      -padx 0 -pady 0 -ipadx 0 -ipady 0
      
   #Bindings to set current table
   bind $parentdialog.expattribtable$numExpDataTables <Button-1> [code SetCurrentExpIndex $numExpDataTables]
   bind $parentdialog.expattribtable$numExpDataTables <Leave> [code UpdateColumnNamesFromTclArray $numExpDataTables]
   bind $parentdialog.expdatatable$numExpDataTables <Button-1> [code SetCurrentExpIndex $numExpDataTables]
   
   for { set iIndex 1 } { $iIndex < [expr 2 * $numExpDataTables] } { incr iIndex 1 } {
      grid columnconfigure $parentdialog $iIndex -weight 0
   }
   grid columnconfigure $parentdialog [expr 2 * $numExpDataTables] -weight 1
   
   #Clear all other selections except the last data table
   for { set iIndex 1 } { $iIndex < $numExpDataTables } { incr iIndex 1 } {
      $parentdialog.expattribtable$iIndex selection clear all
      $parentdialog.expdatatable$iIndex selection clear all
   }
   $parentdialog.expattribtable$numExpDataTables selection clear all
   focus $parentdialog.expdatatable$numExpDataTables
   
   #initialize column names
   set expType [string trim $expType]
   set expType [string tolower $expType]
   
   for { set iIndex 0 } { $iIndex < $validAttribList($expType,ncol) } { incr iIndex 1 } {
      set expdata[expr $numExpDataTables](-1,$iIndex) $validAttribList($expType,col,$iIndex)
   }

   for { set iIndex 0 } { $iIndex < $validAttribList($expType,natt) } { incr iIndex 1 } {
      set expattribdata[expr $numExpDataTables]($iIndex,0) $validAttribList($expType,attr,$iIndex)
   }

   #Resize the scrolled widget bar
   after 200 [update]
   refresh   
   $scrolledParent xview scroll -10 units
   after 200 [update]
   refresh   
   $scrolledParent xview scroll 20 units
   after 200 [update]
   refresh   
}
# --------------------------------------------------------------
#  Function Name: SetCurrentExpIndex
#  Purpose:       Deletes last added experimental data table
#  Arguments:  
#  Notes:
#
# --------------------------------------------------------------
proc SetCurrentExpIndex { index } {
   variable currentExpIndex
   set currentExpIndex $index
}

# --------------------------------------------------------------
#  Function Name: DeleteCurrentExperimentalDataTable
#  Purpose:       Deletes current added experimental data table
#  Arguments:  
#  Notes:
#
# --------------------------------------------------------------
proc DeleteCurrentExperimentalDataTable { parentdialog } {
   variable currentExpIndex
   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
   }
   variable numExpDataTables
   variable scrolledParent

   if { ! [info exists numExpDataTables] } {
      return
   }

   if { 0 == $numExpDataTables } {
      return
   }

   #Now swap data
   set isLastDeleted 1
   if { $currentExpIndex != $numExpDataTables } {
      for { set iIndex $currentExpIndex } { $iIndex < $numExpDataTables } { incr iIndex 1 } {
         set iNext [expr $iIndex + 1]
         array set expFile$iIndex [array get expFile$iNext]
         array set expdata$iIndex [array get expdata$iNext]
         array set expattribdata$iIndex [array get expattribdata$iNext]
      }
      set isLastDeleted 0
   }

   DeleteLastExperimentalDataTable $parentdialog

   #Now configure the current table
   if { $isLastDeleted == 0 } {
       UpdateTablePropetries $currentExpIndex $parentdialog
   }

   #Resize the scrolled widget bar
   $scrolledParent xview scroll -1 units
}

# --------------------------------------------------------------
#  Function Name: DeleteLastExperimentalDataTable
#  Purpose:       Deletes last added experimental data table
#  Arguments:  
#  Notes:
#
# --------------------------------------------------------------
proc DeleteLastExperimentalDataTable { parentdialog } {
   variable numExpDataTables
   variable parent
   variable expFile
   variable currentExpIndex

   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
       variable expnumrow$index
       variable expnumcol$index
   }

   if { $currentExpIndex == $numExpDataTables } {
      set currentExpIndex [expr $currentExpIndex - 1]
   }

   if { $numExpDataTables > 0 } {
      grid remove $parentdialog.expdatatable$numExpDataTables
      grid remove $parentdialog.expattribtable$numExpDataTables

      destroy $parentdialog.expdatatable$numExpDataTables
      destroy $parentdialog.expattribtable$numExpDataTables

      catch { array unset expFile$numExpDataTables }
      catch { array unset expdata$numExpDataTables }
      catch { array unset expattribdata$numExpDataTables }
      catch { unset expnumrow$numExpDataTables }
      catch { unset expnumcol$numExpDataTables }
      set numExpDataTables [ expr $numExpDataTables - 1]
   }
}

# --------------------------------------------------------------
#  Function Name: LoadFileToTable
#  Purpose:       Loads the contents of the file to the table
#  Arguments:  
#  Notes:
#
# --------------------------------------------------------------
proc LoadFileToTable { expIndex parentdialog expType } {
   variable parent
   variable expFile
   variable numExpDataTables
   variable validAttribList
   
   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
       variable expnumrow$index
       variable expnumcol$index
   }

   # ans_sendcommand *LIST,$expFile($expIndex)
   set status 0
   if { ! [ info exists expFile($expIndex) ] } {
      return
   }

   if { $expFile($expIndex) == "" } {
      return
   }

   if { ![info exists numExpDataTables] } {
      ans_senderror 2 "DEV ERROR : Undefined Variable in LoadFileToTable."
      return 0      
   }

   if { $numExpDataTables < 1 } {
      ans_senderror 2 "Cannot load experimental data without any tables in Page."
      return 0      
   }

   $parentdialog.expdatatable$expIndex configure \
     -rows 1\
     -cols 1
   $parentdialog.expattribtable$expIndex configure \
     -rows 1 \
     -cols 1
   set status [ReadExperimentalDataFromFile $expFile($expIndex) $expIndex]

   #Reset the table attribs
   if { $status == 1 } {
      #show exp data
      set nrow 0
      set ncol 0
      set nrow [array get expdata$expIndex numrow]
      set nrow [lindex $nrow 1]
      set ncol [array get expdata$expIndex numcol]
      set ncol [lindex $ncol 1]
      $parentdialog.expdatatable$expIndex configure \
        -rows [expr $nrow + 1]\
        -cols [expr $ncol + 1]

      #show exp data attribs
      set nrow [array get expattribdata$expIndex numrow]
      set nrow [lindex $nrow 1]
      set ncol [array get expattribdata$expIndex numcol]
      set ncol [lindex $ncol 1]
      if { $ncol < 2 } {
         set ncol 2
      }
      $parentdialog.expattribtable$expIndex configure \
        -rows [expr $nrow + 1]\
        -cols [expr $ncol + 1]
   }

   #For Foam add a f to the experiment name and query
   set ncol [array get expdata$expIndex numcol]
   set ncol [lindex $ncol 1]
   if { $ncol == 3 } {
      set isUnia [string equal -nocase -length 4 "unia" $expType]
      set isBiax [string equal -nocase -length 4 "biax" $expType]
      set isShea [string equal -nocase -length 4 "shea" $expType]
      set isSShea [string equal -nocase -length 4 "sshe" $expType]
      if { ($isUnia == 1 || $isBiax == 1 || $isShea == 1) && $isSShea != 1 } {
           
           set newExpType "f$expType"
           
           #Now fill the headers
           set newExpType [string trim $newExpType]
           set newExpType [string tolower $newExpType]

           for { set iIndex 0 } { $iIndex < $validAttribList($newExpType,ncol) } { incr iIndex 1 } {
              set expdata[expr $numExpDataTables](-1,$iIndex) $validAttribList($newExpType,col,$iIndex)
           }
           
      }
   }
   
   #3 cols mean freq domain data
   array set expdatatemp [array get expdata$expIndex ]
   if { $ncol == 3 } {
      set issdec [string equal -nocase -length 4 "sdec" $expType]
      set isbdec [string equal -nocase -length 4 "bdec" $expType]
      if { $issdec == 1 || $isbdec == 1  } {
          set expdatatemp(-1,0) "FREQ"
          set expdatatemp(-1,1) "STORAGE MOD"
          set expdatatemp(-1,2) "LOSS MOD"
      }
   }
   array set expdata$expIndex [array get expdatatemp ]

}

# --------------------------------------------------------------
#  Function Name: ExperimentDataCommand
#  Purpose:       Function to take the table from AddExperimentData
#                 and execute the proper Ansys commands
#  Arguments:     Experiment Type
#  Notes:         
# 
# --------------------------------------------------------------
   proc ExperimentDataCommand { ExpType } {

      variable matid
      variable expCurve
      variable expFile
      variable numExpDataTables
      variable replacekey
      variable parent
      
      for { set index 1 } { $index < 50 } { incr index 1 } {
          variable expdata$index
          variable expattribdata$index
          variable expnumrow$index
          variable expnumcol$index
      }
      
      ToggleParentState 1

      # If replace key is true delete all experimental data for this type
      if {$replacekey == 1} {
         set numExistingExps [ans_getvalue tbft,$matid,nexp]
         for { set index $numExistingExps } { $index >= 1 } { incr index -1 } {
            set curExpType "unknown"
            catch { set curExpType [ans_getvalue tbft,$matid,expe,$index,type] }
            set curExpType [string trim $curExpType]
            if { [string equal -nocase $ExpType $curExpType] } {
               catch {ans_sendcommand TBFT,EDEL,$matid,$ExpType}
            }
         }
      }

      #Write all new experimental data
      for { set index 1 } { $index <= $numExpDataTables } { incr index 1 } {
         set JobName [::ansys::getJobname]
         set fileName "${JobName}_${ExpType}_${index}.exp"
         set printStatus [ans_evalexpr wrinqr(1)]
         catch {ans_sendcommand ) /nopr}
         set status 0
         set status [WriteExperimentalDataToFile $fileName $index ]
         if { $status == 1 } {         
            ans_sendcommand /com,Curve Fitting Experimental Data Written To $fileName
            catch {ans_sendcommand TBFT,EADD,$matid,$ExpType,$fileName}
         } else {
#            tk_messageBox -parent $parent -title "Warning" -icon warning -message "Invalid Data Or No Data in Table. Skipped the Data"
         }
         if { $printStatus == 1 } {
            catch {ans_sendcommand ) /gopr}
         }
      }

      #clean up
      for { set index 1 } { $index <= $numExpDataTables } { incr index 1 } {
         unset expdata$index
      }

      refreshL
      refresh
      ToggleParentState 0
   }

# --------------------------------------------------------------
#  Function Name: ExpTypeToTitle
#  Purpose:       This routine maps database experiments names
#                 to titles for use in the curve definition box
#  Arguments:     ExpType -experiment type
#  Notes:         
#
# --------------------------------------------------------------

   proc ExpTypeToTitle { ExpType } {

      set etitle(UNIA) "Uniaxial test data"
      set etitle(BIAX) "Biaxial test data"
      set etitle(SHEA) "Shear test data"
      set etitle(SSHE) "Simple Shear test data"
      set etitle(VOLU) "Volumetric test data"
      set etitle(SDEC) "Shear Data(Time/Freq Domain) - Viscoelastic  "
      set etitle(BDEC) "Bulk Data(Time/Freq Domain) - Viscoelastic  "


      if { [catch {set ExpTitle $etitle($ExpType)} ] } {
         set ExpTitle "Experiment is $ExpType"
      }
      return $ExpTitle

   }
# --------------------------------------------------------------
#  Function Name: SolutionParameters
#  Purpose:       Dialog box to define solution parameters.
#                 Useful for unconverged curve fits or bad seeds
#                 or fine tuning solution
#  Arguments:     None (yet)
#  Notes:         Orphan (currently) can be called as advanced
#                 feature
# 
# --------------------------------------------------------------
   proc SolutionParameters {} {
      variable parent
      variable childsite
      variable emptyfolder
      variable matid
      variable matModelArr

      set childsite [$parent component childsite]
      if {[info exists childsite]} {
         destroy $childsite.expframe
         destroy $childsite.funcparamframe
         destroy $childsite.nonlinearsettings
      }

      set childsite [$parent component childsite]
      set parent1 [::euidl::labeledframe $childsite.newframe]
      $parent1 configure \
           -text [msgcat::mc "Solution Parameters"]
      grid $parent1 -column 1 -row 1 -sticky news

      unset childsite
      set childsite [$parent1 component childsite]

       wizardstate "normal" 

       update idletasks

   }

# --------------------------------------------------------------
#  Function Name: ResultsPage
#  Purpose:       Lists curve fits by error norm.  User decides
#                 which one is active here.
#  Arguments:     None
#  Notes:         Showing only one at a time now.  This is an orphan.
# 
# --------------------------------------------------------------
   proc ResultsPage {} {
      variable parent
      variable childsite
      variable emptyfolder
      variable matid
      variable matModelArr
      variable coeffs
      variable experror

      set childsite [$parent component childsite]
      if {[info exists childsite]} {
         destroy $childsite.newframe
         destroy $childsite.expframe
         destroy $childsite.funcparamframe
         destroy $childsite.nonlinearsettings
      }

      set childsite [$parent component childsite]
      set parent1 [::euidl::labeledframe $childsite.newframe]
      $parent1 configure -text [msgcat::mc "Summary and Results"]
      grid $parent1 -column 1 -row 1 -sticky new
      #pack $parent1 -fill both -expand true

      unset childsite
      set childsite [$parent1 component childsite]
    
      set graphUnia [::euidl::label $childsite.graphunia ]
      $graphUnia configure -text [msgcat::mc "UNIA Graph Goes Here"] -height 3 -anchor w
      grid $graphUnia -column 0 -row 0 -sticky w -padx 3 -pady 3

      set graphBiax [::euidl::label $childsite.graphbiax ]
      $graphBiax configure -text [msgcat::mc "BIAX Graph Goes Here"] -height 3 -anchor e
      grid $graphBiax -column 3 -row 0 -sticky e -padx 3 -pady 3

      set graphShea [::euidl::label $childsite.graphshea ]
      $graphShea configure -text [msgcat::mc "SHEA Graph Goes Here"] -height 3 -anchor w
      grid $graphShea -column 0 -row 3 -sticky w -padx 3 -pady 3

      set graphVolu [::euidl::label $childsite.graphvolu ]
      $graphVolu configure -text [msgcat::mc "VOLU Graph Goes Here"] -height 3 -anchor e
      grid $graphVolu -column 3 -row 3 -sticky e -padx 3 -pady 3

      euidl::table $childsite.coefftable \
            -variable [scope coeffs] \
            -rowseparator \n \
            -colseparator \t \
            -validate focusout \
            -validatedata ansreal \
            -titlerows 7

      $childsite.coefftable configure \
            -rows 6 \
            -cols 2
 
      set coeffs(-1,-1) "Coeff"
      set coeffs(-1,0) "Value"

      set coeffs(0,-1) "C01"
      set coeffs(0,0) "1.3"

      set coeffs(1,-1) "C10"
      set coeffs(1,0) "0.3"

      set coeffs(2,-1) "C20"
      set coeffs(2,0) "3.4"

      set coeffs(3,-1) "C12"
      set coeffs(3,0) "4.3"

      set coeffs(4,-1) "C22"
      set coeffs(4,0) "6.3"

      set coeffs(5,-1) "D"
      set coeffs(5,0) ".13"

      grid $childsite.coefftable -column 0 -row 4

      euidl::table $childsite.errortable \
            -variable [scope experror] \
            -rowseparator \n \
            -colseparator \t \
            -validate focusout \
            -validatedata ansreal \
            -titlerows 5

      $childsite.errortable configure \
            -rows 5 \
            -cols 2
 
      set experror(-1,-1) "Experiment"
      set experror(-1,0) "Error"

      set experror(0,-1) "Uniaxial"
      set experror(0,0) "1.3"

      set experror(1,-1) "Biaxial"
      set experror(1,0) "1.3"

      set experror(2,-1) "Shear"
      set experror(2,0) "2.4"

      set experror(3,-1) "Volumetric"
      set experror(3,0) "0.3"


      grid $childsite.errortable -column 3 -row 4

      wizardstate "normal" 

      update idletasks
   }

# --------------------------------------------------------------
#  Function Name: Calculations
#  Purpose:       Calls the TBFT commands to solve for all coefficients
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc Calculations {} {

      variable matid

      catch { ans_sendcommand !tbft,,norm,1 }
      catch { ans_sendcommand !tbft,,lm-mu,10 }
      catch { ans_sendcommand !tbft,,lm-gamma,0.10 }
      catch { ans_sendcommand !tbft,init,0,1 }
      catch { ans_sendcommand !tbft,init,1,1 }
      catch { ans_sendcommand !tbft,,numi,100 }

      foreach hyper { MOON,2 MOON,3 MOON,5 MOON,9 \
                      POLY,1 POLY,2 POLY,3 \
                      OGDE,1 OGDE,2 OGDE,3 \
                      YEOH,1 YEOH,2 YEOH,3 \
                    } {
                   #   set funcexist [ans_getvalue tbft,$matid,]
                      set funcexist 1
                         if {$funcexist == 1} {
                            ::apdl::noerr 1
                            catch {ans_sendcommand TBFT,SOLVE,$matid,HYPER,$hyper, $NLOpts(1) }
                         }
                      }

   }

# --------------------------------------------------------------
#  Function Name: SummaryPage
#  Purpose:       Lists curve fits by error norm.  User decides
#                 which one is active here.
#  Arguments:     None
#  Notes:         Duplicate of ResultsPage.  Should delete one.
# 
# --------------------------------------------------------------
   proc SummaryPage {} {
      variable parent
      variable childsite
      variable emptyfolder
      variable matid
      variable matModelArr
      variable coeffs
      variable compareerror
      variable exportflag

      # Calculate the coefficients
      Calculations

      set childsite [$parent component childsite]
      if {[info exists childsite]} {
         destroy $childsite.newframe
         destroy $childsite.expframe
         destroy $childsite.funcparamframe
         destroy $childsite.nonlinearsettings
      }

      set childsite [$parent component childsite]
      set parent1 [::euidl::labeledframe $childsite.newframe]
      $parent1 configure -text [msgcat::mc "Summary"]
      grid $parent1 -column 1 -row 1 -sticky new
      #pack $parent1 -fill both -expand true

      unset childsite
      set childsite [$parent1 component childsite]
    
      euidl::table $childsite.summarytable \
            -variable [scope compareerror] \
            -rowseparator \n \
            -colseparator \t \
            -validate focusout \
            -validatedata ansreal

      set maxFunc [ans_getvalue tbft,$matid,nfun]
      set maxFunc [ans_evalexpr $maxFunc]

      $childsite.summarytable configure \
            -rows $maxFunc \
            -titlerows $maxFunc \
            -cols 3
 
      set compareerror(-1,-1) "Curve Fit"
      set compareerror(-1,0) "Calculated Error"
      set compareerror(-1,1) "Export To Ansys"

      set funcnum 1
      while {$funcnum <= $maxFunc} {
         set f [ans_getvalue tbft,$matid,func,$funcnum,fname]
         set f [string trim $f]
         set compareerror([expr $funcnum-1],-1) [FuncNameToLabel $f]
         set compareerror([expr $funcnum-1],0) "error $funcnum"
         set compareerror([expr $funcnum-1],0) [ans_getvalue tbft,$matid,,$f,resi]

         euidl::checkbutton  $childsite.summarytablecheck{$funcnum} \
            -variable [scope exportflag($funcnum)] 
         $childsite.summarytable window configure [expr $funcnum-1],1 -window $childsite.summarytablecheck{$funcnum}

         set compareerror([expr $funcnum-1],9) [FuncNameToCommand $f]

         incr funcnum

      }

      grid $childsite.summarytable -column 3 -row 4

      wizardstate "normal" 

      update idletasks
   }

# --------------------------------------------------------------
#  Function Name: ReadCoeffsFromDatabase
#  Purpose:       Reads Coefficients from database
#                 
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
proc ReadCoeffsFromDatabase { matid fname } {
    variable CoeffSeed
    variable matStates
    set existKey [ ConstitutiveFunctionExists $matid $fname ]
    if { $existKey == 1 } {
       ::apdl::noerr 1
       catch { set CoeffSeed(numcoeff) [ans_getvalue TBFT,$matid,FUNC,$fname,ncon] }

       for {set i 1} {$i <= $CoeffSeed(numcoeff)} {incr i 1} {
            set CoeffSeed([expr $i-1],-1) $i
       }

       for {set i 1} {$i <= $CoeffSeed(numcoeff)} {incr i 1} {
            set CoeffSeed([expr $i-1],1) "1"
            set CoeffSeed([expr $i-1],2) 0
       }

       for {set i 1} {$i <= $CoeffSeed(numcoeff)} {incr i 1} {
            catch { set CoeffSeed([expr $i-1],1) [ans_getvalue TBFT,$matid,FUNC,$fname,cons,$i] }
            catch { set CoeffSeed([expr $i-1],2) [ans_getvalue TBFT,$matid,FUNC,$fname,fixe,$i] }
       }
       ::apdl::noerr 0
    } else {
       if { [info exists CoeffSeed(numcoeff)] } {
          for {set i 1} {$i <= $CoeffSeed(numcoeff)} {incr i 1} {
               set CoeffSeed([expr $i-1],1) "1"
               set CoeffSeed([expr $i-1],2) 0
          }
       }
    }
    
    InitializeCoefficientNames
}

# --------------------------------------------------------------
#  Function Name: WriteExperimentalDataToFile
#  Purpose:       WriteExperimentalDataToFile
#                 
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
proc WriteExperimentalDataToFile { fname currentExp } {
   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
   }
   
   if { [ info exists expdata$currentExp ] && [info exists expattribdata$currentExp] } {
      array set tempArray [array get expdata$currentExp]
      array set tempAttribArray [array get expattribdata$currentExp]
      if { [info exists tempArray(numrow)] } {
         if { $tempArray(numrow) > 0 } {
            if { [file exists $fname] } {
               file delete $fname
            }
            set newFile [open $fname "w" ]

            #Write Experimental Data attribs
            if { [info exists tempAttribArray(numrow)] } {
               for {set iRIndex 0} {$iRIndex < $tempAttribArray(numrow)} {incr iRIndex 1} {
                  if { $tempAttribArray(numcol) > 0 } {
                     set currentRowString $tempAttribArray($iRIndex,0)
                     set currentRowString [string trim $currentRowString]
                     for {set iCIndex 1} {$iCIndex < $tempAttribArray(numcol)} {incr iCIndex 1} {
                        if { ![info exists tempAttribArray($iRIndex,$iCIndex)] } {
                            close $newFile
                            return 0
                        }
                        set tempAttribArray($iRIndex,$iCIndex) [string trim $tempAttribArray($iRIndex,$iCIndex)]
                        set currentRowString "${currentRowString},$tempAttribArray($iRIndex,$iCIndex)"
                     }
                     set currentRowString "/${currentRowString}"
                     if { [catch {puts $newFile $currentRowString }]} {
                        close $newFile
                        return 0
                     }
                  }
               }
            }

            #Write Experimental Data Points
            for {set iRIndex 0} {$iRIndex < $tempArray(numrow)} {incr iRIndex 1} {
               if { $tempArray(numcol) > 0 } {
                  set currentRowString ""
                  for {set iCIndex 0} {$iCIndex < $tempArray(numcol)} {incr iCIndex 1} {
                     if { ! [info exists tempArray($iRIndex,$iCIndex)] } {
                        close $newFile
                        return 0
                     }
                     set currentRowString "${currentRowString} $tempArray($iRIndex,$iCIndex)"
                  }
                                    
                  if { [catch {puts $newFile $currentRowString }]} {
                        close $newFile
                        return 0
                  }                  
               }
            }
            
            #Close the File Stream
            close $newFile
            
            return 1
         }
      }
   }

   return 0
}

# --------------------------------------------------------------
#  Function Name: ReadExperimentalDataFromFile
#  Purpose:       ReadExperimentalDataFromFile
#                 
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
proc ReadExperimentalDataFromFile { fname currentExp } {
   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
   }
   variable currentWorkDir
   variable numExpDataTables

   if { ![info exists fname] || ![info exists currentExp] } {
      ans_senderror 2 "DEV ERROR : File Name or Exp Index is Invalid."
      return 0
   }

   if { ![info exists numExpDataTables] } {
      ans_senderror 2 "DEV ERROR : Undefined Variable in ReadExperimentalDataFromFile."
      return 0      
   }

   if { $numExpDataTables < 1 } {
      ans_senderror 2 "Cannot load experimental data without any tables in Page."
      return 0      
   }

   catch { unset expdata$index }
   catch { unset expattribdata$index }
   
   if { ![file exists $fname] } {
      ans_senderror 2 "File $fname does not exist."
      return 0
   }
   
   set currentWorkDir [file dirname $fname]

   ToggleParentState 1

   #Read Line by Line and Add to expdata array   
   set fileStream [open $fname r]

   set rIndex 0
   set cIndex 0
   set colSize 0
   set rowSize 0
   catch { unset myarray }
   set expdatatemp(numrow) 0
   set expdatatemp(numcol) 0
   set maxColSize 0

   set rAttribIndex 0
   set cAttribIndex 0
   set expAttribDataTemp(numrow) 0
   set expAttribDataTemp(numcol) 0
   set numAttribsRows 0
   set numAttribCols 0
   set maxAttribColSize 0

   while { [gets $fileStream parsedString] >= 0  } {
      #If the first char is a / ignore
      set parsedString [string trim $parsedString]
      if { $parsedString != "" } {
         set firstChar [string index $parsedString 0]
         if { $firstChar != "/" } {

            #Process each line
            #set parsedString [split $parsedString space ]
            set isComma [string first "," $parsedString]
            if { $isComma  > -1 } {
                set parsedString [split $parsedString "," ]
            }
            
            set x {}
            foreach item $parsedString { 
               if { ![string is punct $item] } {
                  lappend x $item 
               }
            } 
            set parsedString $x

            set cIndex 0
            set colSize [llength $parsedString]
            if { $maxColSize < $colSize } {
               set maxColSize $colSize
            }
            set expdatatemp(numcol) [expr $colSize+1]
            set expdatatemp($rIndex,-1) [expr $rIndex+1]
            for { set cIndex 0 } { $cIndex < $colSize } { incr cIndex 1 } {
               set expdatatemp($rIndex,$cIndex) [lindex $parsedString $cIndex]     
            }
            incr rIndex 1
            incr rowSize 1
         } else {
            set parsedString [string trim $parsedString / ]
            set parsedString [split $parsedString ","]
            set cAttribIndex 0
            set numAttribCols [llength $parsedString]
            if { $maxAttribColSize < $numAttribCols } {
               set maxAttribColSize $numAttribCols
            }
            set expAttribDataTemp(numcol) [expr $numAttribCols+1]
            set expAttribDataTemp($rAttribIndex,-1) ""
            for { set cAttribIndex 0 } { $cAttribIndex < $numAttribCols } { incr cAttribIndex 1 } {
               set expAttribDataTemp($rAttribIndex,$cAttribIndex) [lindex $parsedString $cAttribIndex]              }
            incr rAttribIndex 1
            incr numAttribsRows 1        
         }
      }
   }

   #copy the data
   set expdatatemp(numrow) $rowSize
   set expdatatemp(numcol) $maxColSize

   array set expdata$currentExp [array get expdatatemp]

   #copy the attribs
   set expAttribDataTemp(numrow) $numAttribsRows
   set expAttribDataTemp(numcol) $numAttribCols
   set expAttribDataTemp(-1,0) "Additional Param"
   set expAttribDataTemp(-1,1) "Value"
   array set expattribdata$currentExp [array get expAttribDataTemp]
   
   #Close the file stream
   close $fileStream

   UpdateColumnNamesFromTclArray $currentExp

   ToggleParentState 0
   return 1
}

# --------------------------------------------------------------
#  Function Name: PlotExperimentalData
#  Purpose:       PlotExperimentalData
#                 
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
proc UpdateColumnNamesFromTclArray { currentExp } {
   variable array ColumnNames
   for { set index 1 } { $index < 50 } { incr index 1 } {
       variable expdata$index
       variable expattribdata$index
   }
   variable currentWorkDir
   variable numExpDataTables
   variable matStates
   
   if { $matStates(Creep) != 1 } {
      return
   }

   
   set ColumnNames(0) "Unknown Type "
   set ColumnNames(1) "Unknown Type "
   set ColumnNames(2) "Unknown Type "
   set ColumnNames(3) "Unknown Type "
   set ColumnNames(4) "Unknown Type "
   set ColumnNames(5) "Unknown Type "
   set ColumnNames(6) "Unknown Type "

   #Load Experimental Data Attribs
   set numAtts [array get expdata$currentExp numrow]
#   set numAtts [array get expattribdata$currentExp numrow]

   if { ![info exists numAtts] } {
      return
   }
   if { $numAtts == "" } {
      return
   }
   set numAtts [lindex $numAtts 1]
   set numAtts [expr $numAtts]
   
   for { set iColIndex 0 } { $iColIndex < $numAtts } { incr iColIndex 1 } {
       for { set iAttIndex 0 } { $iAttIndex < $numAtts } { incr iAttIndex 1 } {
          set curAttName [array get expattribdata$currentExp $iAttIndex,0 ]
          set curAttName [lindex $curAttName 1]
          set curAttName [string trim $curAttName]
          if { [string equal -nocase -length 4 $curAttName "[expr $iColIndex+1]"] } {
              set ColumnNames($iColIndex) [array get expattribdata$currentExp $iAttIndex,1 ]
              set ColumnNames($iColIndex) [lindex $ColumnNames($iColIndex) 1]
              set $ColumnNames($iColIndex) [string trim $ColumnNames($iColIndex)]
              if { [string is space $ColumnNames($iColIndex)] } {
                  set ColumnNames($iColIndex) "Unknown Type"
              }
              array set expdata$currentExp [list "-1,$iColIndex" [ ExpandedCreepName $ColumnNames($iColIndex)]]
          }
       }       
    }
}

# --------------------------------------------------------------
#  Function Name: PlotExperimentalData
#  Purpose:       PlotExperimentalData
#                 
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
proc PlotExperimentalData { matid fname } {

    variable editFunc
    variable cF
    global tcl_platform

   #Add function if it does not exist or return error
   set existKey [ ConstitutiveFunctionExists $matid $fname ]


   if { $existKey == 1 } {

      if {$editFunc == -999} {
         set maxFunc [ans_getvalue tbft,$matid,nfun]
         set funcnum [ans_evalexpr $maxFunc]
         set fname [ CommandToFuncName $cF(HyperChoice) ]
      } else {
         set funcnum $editFunc
         set fname [ans_getvalue tbft,$matid,func,$funcnum,fname]
         set fname [string trim $fname]
         set cF(HyperChoice) [FuncNameToCommand $fname]
      }

      set funcParam [split $cF(HyperChoice) , ]
      set category [lindex $funcParam 0]
     

      if { [info exists category] } {
         if { [string equal -nocase -length 4 $category "hyper"] } {
            set expNameList [list UNIA BIAX SHEA SSHE VOLU]
         } elseif { [string equal -nocase -length 4 $category "case"] } {
            set expNameList [list SDEC BDEC]     
         } else {
           return
         }
      }

      # save the current view settings
      catch {ans_sendcommand /GSAVE,oldview}

      # frontal view
      catch {ans_sendcommand )/VIEW,,0,0,1}
      catch {ans_sendcommand )/ANG,,0}
      catch {ans_sendcommand )/AUTO,FIT}


      #Set the colors and style
      ans_sendcommand /color,grbak,0
      ans_sendcommand /color,grid,0
      ans_sendcommand /color,curve,0,1
      ans_sendcommand /gmarker,1,1,1
      ans_sendcommand /plopts,info,0
      ans_sendcommand /plopts,title,0
      ans_sendcommand /gropts,view,1

      set TextSizeSave [ans_getvalue common,,d3dcom,,int,4]
      set CurrentPlatform $tcl_platform(platform)
      set UnixPlatform "unix"
      if { [string match $CurrentPlatform $UnixPlatform] } {
 #       ans_sendcommand /dev,font,1,courier,medium,r,9,,,,, 
         ans_sendcommand /dev,text,1,80
      } else {
 #       ans_sendcommand /dev,font,1,Times*New*Roman,400,,10
         ans_sendcommand /dev,text,1,80
      }
      ans_sendcommand ERASE
      ans_sendcommand /NOERASE

      ans_sendcommand /WINDOW,1,OFF
      ans_sendcommand /WINDOW,2,OFF
      ans_sendcommand /WINDOW,3,OFF
      ans_sendcommand /WINDOW,4,OFF

      ans_sendcommand /GCOLUMN,,TESTDATA
      ans_sendcommand /GCOLUMN,2,CURVEFIT

      ans_sendcommand /AXLAB,X,STRAIN
      ans_sendcommand /AXLAB,Y,STRESS

      ans_sendcommand /WINDOW,1,LTOP
      ans_sendcommand /WINDOW,1,ON

      set expName ""
      unset expName
      set expName [lindex $expNameList 0]


      if { [ string equal -nocase $expName "sdec" ] || [ string equal -nocase $expName "bdec" ] } {
         catch {ans_sendcommand /GROPT,LOGX,ON  }
         catch {ans_sendcommand /GROPT,LOGY,OFF }
      }

      if { [info exists expName] } {
         set plotkey [ExperimentExists $matid $expName]
         if {$plotkey == 1} {
            catch {ans_sendcommand TBFT,PLOT,$matid,$expName,$cF(HyperChoice),,,PREVIEW}
         }
      }

      ans_sendcommand /WINDOW,2,RTOP
      ans_sendcommand /WINDOW,1,OFF
      ans_sendcommand /WINDOW,2,ON
      set expName ""
      unset expName
      set expName [lindex $expNameList 1]
      if { [info exists expName] } {
         set plotkey [ExperimentExists $matid $expName]
         if {$plotkey == 1} {
            catch {ans_sendcommand TBFT,PLOT,$matid,$expName,$cF(HyperChoice),,,PREVIEW}
         }
      }

      ans_sendcommand /WINDOW,3,LBOT
      ans_sendcommand /WINDOW,2,OFF
      ans_sendcommand /WINDOW,3,ON
      set expName ""
      unset expName
      set expName [lindex $expNameList 2]
      if { [info exists expName] } {
         set plotkey [ExperimentExists $matid $expName]
         if {$plotkey == 1} {
            catch {ans_sendcommand TBFT,PLOT,$matid,$expName,$cF(HyperChoice),,,PREVIEW}
         }
      }

      ans_sendcommand /WINDOW,4,RBOT
      ans_sendcommand /WINDOW,3,OFF
      ans_sendcommand /WINDOW,4,ON
      set expName ""
      unset expName
      set expName [lindex $expNameList 3]
      if { [info exists expName] } {
         set plotkey [ExperimentExists $matid $expName]
         if {$plotkey == 1} {
            catch {ans_sendcommand TBFT,PLOT,$matid,$expName,$cF(HyperChoice),,,PREVIEW}
         }
      }

      # restore original graphics settings
      catch {ans_sendcommand /GRESU,oldview}
      catch {ans_sendcommand /dev,text,1,$TextSizeSave}

      #refreshL
   }
}

# --------------------------------------------------------------
#  Function Name: SummaryPageForOneFunc
#  Purpose:       Shows coefficients and error norm
#                 
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc SummaryPageForOneFunc {} {
      variable parent
      variable childsite
      variable cF
      variable matid
      variable CoeffSeed

      variable editFunc

      # Calculate the coefficients

      $parent configure -helpcommand [list ans_loadhelp Hlp_mcf]
      $parent configure -nexttext [msgcat::mc "Save & Close"]

      set childsite [$parent component childsite]
      if {[info exists childsite]} {
         destroy $childsite.newframe
         destroy $childsite.expframe
         destroy $childsite.funcparamframe
         destroy $childsite.nonlinearsettings
      }

      set childsite [$parent component childsite]
      set parent1 [::euidl::labeledframe $childsite.newframe]
      $parent1 configure -text [msgcat::mc "Summary"]
      grid $parent1 -column 1 -row 1 -sticky new
      #pack $parent1 -fill both -expand true

      unset childsite
      set childsite [$parent1 component childsite]
    

      if {$editFunc == -999} {
         set maxFunc [ans_getvalue tbft,$matid,nfun]
         set funcnum [ans_evalexpr $maxFunc]
         set fname [ CommandToFuncName $cF(HyperChoice) ]
      } else {
         set funcnum $editFunc
         set fname [ans_getvalue tbft,$matid,func,$funcnum,fname]
         set fname [string trim $fname]
         set cF(HyperChoice) [FuncNameToCommand $fname]
      }

      PlotExperimentalData $matid $fname

      set flabel [ FuncNameToLabel $fname ]

      catch {set ernorm [ans_getvalue TBFT,$matid,FUNC,$fname,resi]}
      catch {set ncoeff [ans_getvalue TBFT,$matid,FUNC,$fname,ncon]}

      euidl::label $childsite.ftitle -text [msgcat::mc "Function shown is %s" $flabel]
      grid $childsite.ftitle -row 0 -column 0

      euidl::label $childsite.ernorm -text [msgcat::mc "Error norm is %s" $ernorm]
      grid $childsite.ernorm -row 1 -column 0

      ReadCoeffsFromDatabase $matid $fname

      for {set i 1} {$i <= $ncoeff} {incr i 1} {
           euidl::label $childsite.words$i -text [msgcat::mc "C%s = %s" $i $CoeffSeed([expr $i-1],1)]
           grid $childsite.words$i -row [expr $i+1] -column 0
      }

     euidl::label $childsite.endlabel -text [msgcat::mc "Hit next to save"]
 
     #grid $childsite.endlabel -row [expr $i + 2] -column 0


      wizardstate "normal" 
   }

# --------------------------------------------------------------
#  Function Name: SaveOneFunc
#  Purpose:       Writes chosen function to ansys
#                 
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc SaveOneFunc {} {
      variable cF
      variable matid

      #Return if it is not a Function
      set fname [ CommandToFuncName $cF(HyperChoice) ]
      set fname [string trim $fname]
      set existKey [ ConstitutiveFunctionExists $matid $fname ]
      if { $existKey == 0 } {
         ans_senderror 2 "Fitting Function does not yet exist. Unable to save."
         return
      }
      ans_sendcommand TBFT,FSET,$matid,$cF(HyperChoice)

   }

# --------------------------------------------------------------
#  Function Name: PlotCurves
#  Purpose:       Plots the curves
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
   proc PlotCurves {} {

      variable matid
      variable compareerror
      variable exportflag

      set maxFunc [ans_getvalue tbft,$matid,nfun]
      set maxFunc [ans_evalexpr $maxFunc]

      set funcnum 1
      while {$funcnum <= $maxFunc} {
         if {$exportflag($funcnum) == 1} {
            ans_sendcommand ERASE
            ans_sendcommand /NOERASE

            ans_sendcommand /WINDOW,1,OFF
            ans_sendcommand /WINDOW,2,OFF
            ans_sendcommand /WINDOW,3,OFF
            ans_sendcommand /WINDOW,4,OFF

            ans_sendcommand /WINDOW,1,LTOP
            ans_sendcommand /WINDOW,1,ON
            ans_sendcommand TBFT,PLOT,$matid,UNIA,$compareerror([expr $funcnum-1],9)

            ans_sendcommand /WINDOW,2,RTOP
            ans_sendcommand /WINDOW,1,OFF
            ans_sendcommand /WINDOW,2,ON
            ans_sendcommand TBFT,PLOT,$matid,BIAX,$compareerror([expr $funcnum-1],9)

            ans_sendcommand /WINDOW,3,LBOT
            ans_sendcommand /WINDOW,2,OFF
            ans_sendcommand /WINDOW,3,ON
            ans_sendcommand TBFT,PLOT,$matid,SHEA,$compareerror([expr $funcnum-1],9)

            ans_sendcommand /WINDOW,4,RBOT
            ans_sendcommand /WINDOW,3,OFF
            ans_sendcommand /WINDOW,4,ON
            ans_sendcommand TBFT,PLOT,$matid,VOLU,$compareerror([expr $funcnum-1],9)

            return
         }
         incr funcnum

      }

   }

# --------------------------------------------------------------
#  Function Name: wizardstate
#  Purpose:       Sets the state of the wizard buttons
#  Arguments:     state (normal or disabled)
#  Notes:         
# 
# --------------------------------------------------------------
   proc wizardstate { state } {
       variable parent

       $parent configure \
          -finishstate $state \
          -nextstate $state \
          -prevstate $state

   }

# --------------------------------------------------------------
#  Function Name: cancel
#  Purpose:       exit out of wizard, not dialog box
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
   proc cancel {} {

      variable parent
      variable ansysWorkDir

      #Reset PWD to pwd
      catch { cd $ansysWorkDir }

      set childsite [$parent component childsite]
      if {[info exists childsite]} {
         destroy $childsite.expframe
         destroy $childsite.funcdefframe
      }


      wizardstate "disabled"

   }

# --------------------------------------------------------------
#  Function Name: exit
#  Purpose:       exit out of dialog box
#  Arguments:     
#  Notes:         
# 
# --------------------------------------------------------------
   proc exit {} {
       variable ::euidl::material::CurveFit::matModelArr

       variable parent
       variable fromMaterialGUI
       variable exitFromCFITGUIFLAG
       variable ansysWorkDir
       
       #Reset PWD to pwd
       catch { cd $ansysWorkDir }

       if {$fromMaterialGUI == 0} {
          ans_greygui 0 1
          ans_greygui 1 1
          ans_greygui 3 1
          ans_greygui 4 1
       }
      
       ans_sendcommand )/NOPR
       catch {ans_sendcommand )_zbigmat= }
       catch {ans_sendcommand )_zfromat= }
       ans_sendcommand )/GO
 
       euidl::material::CurveFit::matTable_State 1     

       wm withdraw $parent
      
       # Set the printing to what the customer had it set to coming in
       if {$matModelArr(printStatus)} {
          ans_sendcommand )/GO
       } else {
          ans_sendcommand )/NOPR
       }

       wizardstate "disabled"

       if {$fromMaterialGUI != 0} {

          euidl::material::ModelControl::matTable_State 1
          if {[winfo exists .modControl]} {
             set matparent .modControl
             wm deiconify $matparent
             raise $matparent
             set exitFromCFITGUIFLAG 1
          }

          return
       }

   }

# --------------------------------------------------------------
#  Function Name: dummy_func
#  Purpose:       Dummy callback function - placeholder
#  Arguments:     None
#  Notes:         
# 
# --------------------------------------------------------------
   proc dummy_func {} {

      puts "dummy function"

   }

# --------------------------------------------------------------
#  Function Name: FuncNameToLabel
#  Purpose:       convert database function name to display label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------

   proc FuncNameToLabel { fname } {
   
      variable FuncLabel

      set caseList [ split $fname , ]
      if { [llength $caseList] >= 3 } {
         set param1 [lindex $caseList 0]
         set param2 [lindex $caseList 1]
         set param3 [lindex $caseList 2]
         
         if { [string equal -nocase -length 4 $param1 "visco"] } {

            if { [string equal -nocase -length 4 $param2 "pshear"] } {
               set FuncLabel "Shear Terms { Order $param3 } "
            }
            
            if { [string equal -nocase -length 4 $param2 "pbulk"] } {
               set FuncLabel "Bulk Terms { Order $param3 } "
            }
            
            if { [string equal -nocase -length 4 $param2 "shift"] } {
               set FuncLabel "Shift Function is $param3 "
            }
            
            return $FuncLabel
         }
      }

      # Set array of tree labels to show, starting with functions
      set flabel(hyogde1) "Ogden (Order 1)"
      set flabel(HYOGDE1) "Ogden (Order 1)"
      set flabel(hyogde2) "Ogden (Order 2)"
      set flabel(HYOGDE2) "Ogden (Order 2)"
      set flabel(hyogde3) "Ogden (Order 3)"
      set flabel(HYOGDE3) "Ogden (Order 3)"

      set flabel(hymoon2) "Mooney (2 parameter)"
      set flabel(HYMOON2) "Mooney (2 parameter)"
      set flabel(hymoon3) "Mooney (3 parameter)"
      set flabel(HYMOON3) "Mooney (3 parameter)"
      set flabel(hymoon5) "Mooney (5 parameter)"
      set flabel(HYMOON5) "Mooney (5 parameter)"
      set flabel(hymoon9) "Mooney (9 parameter)"
      set flabel(HYMOON9) "Mooney (9 parameter)"

      set flabel(hyyeoh1) "Yeoh (Order 1)"
      set flabel(HYYEOH1) "Yeoh (Order 1)"
      set flabel(hyyeoh2) "Yeoh (Order 2)"
      set flabel(HYYEOH2) "Yeoh (Order 2)"
      set flabel(hyyeoh3) "Yeoh (Order 3)"
      set flabel(HYYEOH3) "Yeoh (Order 3)"

      set flabel(hypoly1) "Polynomial (Order 1)"
      set flabel(HYPOLY1) "Polynomial (Order 1)"
      set flabel(hypoly2) "Polynomial (Order 2)"
      set flabel(HYPOLY2) "Polynomial (Order 2)"
      set flabel(hypoly3) "Polynomial (Order 3)"
      set flabel(HYPOLY3) "Polynomial (Order 3)"

      set flabel(hyboyc)  "Arruda-Boyce"
      set flabel(HYBOYC)  "Arruda-Boyce"

      set flabel(hyetub)  "Extended Tube Model"
      set flabel(HYETUB)  "Extended Tube Model"

      set flabel(hygent)  "Gent"
      set flabel(HYGENT)  "Gent"

      set flabel(hyneo)  "Neo-Hookean"
      set flabel(HYNEO)  "Neo-Hookean"

      set flabel(hyblat1)  "Blatz-Ko"
      set flabel(HYBLAT1)  "Blatz-Ko"
      set flabel(hyblat)  "Blatz-Ko"
      set flabel(HYBLAT)  "Blatz-Ko"

      set flabel(hyfoam1) "Ogden HyperFoam (Order 1)"
      set flabel(hyfoam2) "Ogden HyperFoam (Order 2)"
      set flabel(hyfoam3) "Ogden HyperFoam (Order 3)"
      set flabel(HYFOAM1) "Ogden HyperFoam (Order 1)"
      set flabel(HYFOAM2) "Ogden HyperFoam (Order 2)"
      set flabel(HYFOAM3) "Ogden HyperFoam (Order 3)"


      #Chaboche
      set flabel(plchab1)  "Chaboche Hardening (Order 1)"
      set flabel(PLCHAB1)  "Chaboche Hardening (Order 1)"
      set flabel(plchab2)  "Chaboche Hardening (Order 2)"
      set flabel(PLCHAB2)  "Chaboche Hardening (Order 2)"
      set flabel(plchab3)  "Chaboche Hardening (Order 3)"
      set flabel(PLCHAB3)  "Chaboche Hardening (Order 3)"
      set flabel(plchab4)  "Chaboche Hardening (Order 4)"
      set flabel(PLCHAB4)  "Chaboche Hardening (Order 4)"
      set flabel(plchab5)  "Chaboche Hardening (Order 5)"
      set flabel(PLCHAB5)  "Chaboche Hardening (Order 5)"

      #Isotropic Hardening
      set flabel(plciso)  "None"
      set flabel(plbiso)  "Bilinear Isotropic"
      set flabel(PLBISO)  "Bilinear Isotropic"
      for {set i 1} {$i <= 20} {incr i 1} {
            set sOrder "Multilinear Isotropic $i Term"
            set sOrderParam "plmiso[expr $i]"
            set flabel($sOrderParam) $sOrder
      }
      set flabel(plvoce)  "Voce Hardening Law"
      set flabel(PLVOCE)  "Voce Hardening Law"

      set flabel(plpowe)  "Power Law "
      set flabel(PLPOWE)  "Power Law "

            #All creep models are non linear
      set flabel(CRSHAR) "Strain Hardening"
      set flabel(CRTHAR) "Time Hardening"
      set flabel(CRGEXP) "Generalized Exponential"
      set flabel(CRGGRA) "Generalized Graham"
      set flabel(CRGBLA) "Generalized Blackburn"
      set flabel(CRMSHA) "Modified Strain Hardening"
      set flabel(CRMTHA) "Modified Time Hardening"
      set flabel(CRGTHA) "Generalized Time Hardening"
      set flabel(CRGGAR) "Generalized Garofalo"
      set flabel(CREXPO) "Exponential Form"
      set flabel(CRNORT) "Norton"
      set flabel(CRPSTH) "Time Hardening"
      set flabel(CRPSRP) "Rational Polynomial"

      set flabel(crshar) "Strain Hardening"
      set flabel(crthar) "Time Hardening"
      set flabel(crgexp) "Generalized Exponential"
      set flabel(crggra) "Generalized Graham"
      set flabel(crgbla) "Generalized Blackburn"
      set flabel(crmsha) "Modified Strain Hardening"
      set flabel(crmtha) "Modified Time Hardening"
      set flabel(crgtha) "Generalized Time Hardening"
      set flabel(crggar) "Generalized Garofalo"
      set flabel(crexpo) "Exponential Form"
      set flabel(crnort) "Norton"
      set flabel(crpsth) "Time Hardening"
      set flabel(crpsrt) "Rational Polynomial"

      set shiftLabels [list tn wlf none]
      set numShiftLabels [llength $shiftLabels]

      for {set i 1} {$i <= 20} {incr i 1} {
            set sOrder "PRONY SHEAR (Order $i)"
            set sOrderParam "vish[expr $i]"
            set flabel($sOrderParam) $sOrder
      }

      for {set i 1} {$i <= 20} {incr i 1} {
            set sOrder "PRONY BULK (Order $i)"
            set sOrderParam "vibk[expr $i]"
            set flabel($sOrderParam) $sOrder
      }

      set shiftLabels [list TN WLF NONE]
      set numShiftLabels [llength $shiftLabels]

      for {set i 0} {$i < 3} {incr i 1} {
            set sLabel [lindex $shiftLabels $i]
            set sOrder "Shift Function is $sLabel"
            set sOrderParam "vish[string tolower $sLabel]"
            set flabel($sOrderParam) $sOrder
      }

      if { [catch {set FuncLabel $flabel($fname)} ] } {
         set FuncLabel $fname
      }
      return $FuncLabel
   }


# --------------------------------------------------------------
#  Function Name: FuncNameToCommand
#  Purpose:       convert database function name to command label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------

   proc FuncNameToCommand { fname } {

      variable FuncLabel

      # Trim all the spaces      
      set fname [string trim $fname]

      # Set array of tree labels to show, starting with functions
      for {set i 1} {$i <= 20} {incr i 1} {

         set flabel(hyogde$i) "HYPER,OGDEN,$i"
         set flabel(HYOGDE$i) "HYPER,OGDEN,$i"

         set flabel(hyyeoh$i) "HYPER,YEOH,$i"
         set flabel(HYYEOH$i) "HYPER,YEOH,$i"

         set flabel(hypoly$i) "HYPER,POLY,$i"
         set flabel(HYPOLY$i) "HYPER,POLY,$i"

         set flabel(hyfoam$i) "HYPER,FOAM,$i"
         set flabel(HYfoam$i) "HYPER,FOAM,$i"

         #chaboche plasticity
         set flabel(plchab$i)  "PLAS,CHAB,$i"
         set flabel(PLCHAB$i)  "PLAS,CHAB,$i"

         set flabel(plmiso$i)  "PLAS,MISO,$i"
         set flabel(PLMISO$i)  "PLAS,MISO,$i"
      }

      set flabel(plbiso)  "PLAS,BISO,"
      set flabel(PLBISO)  "PLAS,BISO,"

      set flabel(plvoce)  "PLAS,VOCE,"
      set flabel(PLVOCE)  "PLAS,VOCE,"

      set flabel(plpowe)  "PLAS,POWE,"
      set flabel(PLPOWE)  "PLAS,POWE,"

      set flabel(hymoon2) "HYPER,MOON,2"
      set flabel(HYMOON2) "HYPER,MOON,2"
      set flabel(hymoon3) "HYPER,MOON,3"
      set flabel(HYMOON3) "HYPER,MOON,3"
      set flabel(hymoon5) "HYPER,MOON,5"
      set flabel(HYMOON5) "HYPER,MOON,5"
      set flabel(hymoon9) "HYPER,MOON,9"
      set flabel(HYMOON9) "HYPER,MOON,9"

      set flabel(hyboyc)  "HYPER,BOYCE,"
      set flabel(HYBOYC)  "HYPER,BOYCE,"

      set flabel(hyetub)  "HYPER,ETUB,"
      set flabel(HYETUB)  "HYPER,ETUB,"

      set flabel(hygent)  "HYPER,GENT,"
      set flabel(HYGENT)  "HYPER,GENT,"

      set flabel(hyneo)  "HYPER,NEO,"
      set flabel(HYNEO)  "HYPER,NEO,"

      set flabel(hyblat1)  "HYPER,BLAT,"
      set flabel(HYBLAT1)  "HYPER,BLAT,"
      set flabel(hyblat)  "HYPER,BLAT,"
      set flabel(HYBLAT)  "HYPER,BLAT,"

      
      #Creep Stuff
      set flabel(crshar) "CREEP,SHAR,"
      set flabel(crthar) "CREEP,THAR,"
      set flabel(crgexp) "CREEP,GEXP,"
      set flabel(crggra) "CREEP,GGRA,"
      set flabel(crgbla) "CREEP,GBLA,"
      set flabel(crmsha) "CREEP,MSHA,"
      set flabel(crmtha) "CREEP,MTHA,"
      set flabel(crgtha) "CREEP,GTHA,"
      set flabel(crggar) "CREEP,GGAR,"
      set flabel(crexpo) "CREEP,EXPO,"
      set flabel(crnort) "CREEP,NORT,"
      set flabel(crpsth) "CREEP,PSTH,"
      set flabel(crpsrp) "CREEP,PSRP,"

      set flabel(CRSHAR) "CREEP,SHAR,"
      set flabel(CRTHAR) "CREEP,THAR,"
      set flabel(CRGEXP) "CREEP,GEXP,"
      set flabel(CRGGRA) "CREEP,GGRA,"
      set flabel(CRGBLA) "CREEP,GBLA,"
      set flabel(CRMSHA) "CREEP,MSHA,"
      set flabel(CRMTHA) "CREEP,MTHA,"
      set flabel(CRGTHA) "CREEP,GTHA,"
      set flabel(CRGGAR) "CREEP,GGAR,"
      set flabel(CREXPO) "CREEP,EXPO,"
      set flabel(CRNORT) "CREEP,NORT,"
      set flabel(CRPSTH) "CREEP,PSTH,"
      set flabel(CRPSRP) "CREEP,PSRP,"

      set shiftLabels [list tn wlf none]
      set numShiftLabels [llength $shiftLabels]
      for {set i 4} {$i <= 5} {incr i 1} {
          for {set j 4} {$j <= 5} {incr j 1} {
             for {set k 0} { $k < $numShiftLabels} {incr k 1} {
                 set sLabel [lindex $shiftLabels $k]
                 set sOrder "VISCO,PVHE,[expr $i]_[expr $j]_$sLabel"
                 set sOrderParam "vipvhe[expr $i]_[expr $j]_$sLabel"
                 set flabel($sOrderParam) $sOrder
             }
          }
      }

      for {set i 1} {$i <= 5} {incr i 1} {
         for {set j 0} { $j < $numShiftLabels} {incr j 1} {
            set sLabel [lindex $shiftLabels $j]
            set sOrder "VISCO,PDEC,[expr $i]_$sLabel"
            set sOrderParam "pipdec[expr $i]_$sLabel"
            set flabel($sOrderParam) $sOrder
         }
      }

      for {set i 1} {$i <= 20} {incr i 1} {
            set sOrder "VISCO,SHEAR,$i"
            set sOrderParam "vish[expr $i]"
            set flabel($sOrderParam) $sOrder
      }

      for {set i 1} {$i <= 20} {incr i 1} {
            set sOrder "VISCO,BULK,$i"
            set sOrderParam "vibk[expr $i]"
            set flabel($sOrderParam) $sOrder
      }

      set shiftLabels [list TN WLF NONE]
      set numShiftLabels [llength $shiftLabels]

      for {set i 0} {$i < 3} {incr i 1} {
            set sLabel [lindex $shiftLabels $i]
            set sOrder "VISCO,SHIFT,$sLabel"
            set sOrderParam "vish[string tolower $sLabel]"
            set flabel($sOrderParam) $sOrder
      }

      if { ![info exists flabel($fname)] } {
         set FuncLabel "CASE,$fname,"
         return $FuncLabel
      }

      set FuncLabel $flabel($fname)
      return $FuncLabel

   }

# --------------------------------------------------------------
#  Function Name: CommandToFuncName
#  Purpose:       convert database function name to command label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------

   proc CommandToFuncName { fname } {

      variable matStates

      set caseList [ split $fname , ]
      set isCase [lindex $caseList 0]
      if { [string equal -nocase -length 4 $isCase "case" ] } {
          set comboFuncName [lindex $caseList 1]
          return $comboFuncName
      }

      # Set array of tree labels to show, starting with functions
      set flabel(HYPER,MOON,2) "hymoon2"
      set flabel(HYPER,MOON,3) "hymoon3"
      set flabel(HYPER,MOON,5) "hymoon5"
      set flabel(HYPER,MOON,9) "hymoon9"

      set flabel(hyper,moon,2) "hymoon2"
      set flabel(hyper,moon,3) "hymoon3"
      set flabel(hyper,moon,5) "hymoon5"
      set flabel(hyper,moon,9) "hymoon9"

      for {set i 1} {$i <= 20} {incr i 1} {

         set flabel(HYPER,YEOH,$i) "hyyeoh$i"
         set flabel(hyper,yeoh,$i) "hyyeoh$i"

         set flabel(HYPER,POLY,$i)  "hypoly$i"    
         set flabel(hyper,poly,$i)  "hypoly$i"    

         set flabel(HYPER,OGDEN,$i) "hyogde$i"
         set flabel(hyper,ogden,$i) "hyogde$i"

         set flabel(HYPER,OGDE,$i) "hyogde$i"
         set flabel(hyper,ogde,$i) "hyogde$i"

         set flabel(HYPER,FOAM,$i) "hyfoam$i"
         set flabel(hyper,foam,$i) "hyfoam$i"

         #chaboche
         set flabel(PLAS,CHAB,$i)  "plchab$i"
         set flabel(plas,chab,$i)  "plchab$i"

         set flabel(PLAS,MISO,$i)  "plmiso$i"
         set flabel(plas,miso,$i)  "plmiso$i"
                  
      }

      set flabel(PLAS,BISO,)  "plbiso"
      set flabel(plas,biso,)  "plbiso"

      set flabel(PLAS,BISO)  "plbiso"
      set flabel(plas,biso)  "plbiso"

      set flabel(PLAS,CISO,)  "plciso"
      set flabel(plas,ciso,)  "plciso"

      set flabel(PLAS,CISO)  "plciso"
      set flabel(plas,ciso)  "plciso"

      set flabel(PLAS,VOCE,)  "plvoce"
      set flabel(plas,voce,)  "plvoce"

      set flabel(PLAS,POWE)  "plpowe"
      set flabel(plas,powe)  "plpowe"

      set flabel(HYPER,BOYCE,)  "hyboyc"
      set flabel(hyper,boyce,)  "hyboyc"

      set flabel(HYPER,BOYC)  "hyboyc"
      set flabel(hyper,boyc)  "hyboyc"

      set flabel(HYPER,ETUB)  "hyetub"
      set flabel(hyper,etub)  "hyetub"

      set flabel(HYPER,ETUB,)  "hyetub"
      set flabel(hyper,etub,)  "hyetub"

      set flabel(HYPER,GENT,)   "hygent"
      set flabel(hyper,gent,)   "hygent"

      set flabel(HYPER,GENT)   "hygent"
      set flabel(hyper,gent)   "hygent"

      set flabel(HYPER,NEO,)   "hyneo"
      set flabel(hyper,neo,)   "hyneo"

      set flabel(HYPER,NEO)   "hyneo"
      set flabel(hyper,neo)   "hyneo"

      set flabel(HYPER,BLAT,)   "hyblat"
      set flabel(hyper,blat,)   "hyblat"

      set flabel(HYPER,BLAT)   "hyblat"
      set flabel(hyper,blat)   "hyblat"
      
      #Creep Specific
      set flabel(CREEP,SHAR,)   "crshar"
      set flabel(CREEP,THAR,)   "crthar"
      set flabel(CREEP,GEXP,)   "crgexp"
      set flabel(CREEP,GGRA,)   "crggra"
      set flabel(CREEP,GBLA,)   "crgbla"
      set flabel(CREEP,MSHA,)   "crmsha"
      set flabel(CREEP,MTHA,)   "crmtha"
      set flabel(CREEP,GTHA,)   "crgtha"
      set flabel(CREEP,GGAR,)   "crggar"
      set flabel(CREEP,EXPO,)   "crexpo"
      set flabel(CREEP,NORT,)   "crnort"
      set flabel(CREEP,PSTH,)   "crpsth"
      set flabel(CREEP,PSRP,)   "crpsrp"

      set flabel(creep,shar,)   "crshar"
      set flabel(creep,thar,)   "crthar"
      set flabel(creep,gexp,)   "crgexp"
      set flabel(creep,ggra,)   "crggra"
      set flabel(creep,gbla,)   "crgbla"
      set flabel(creep,msha,)   "crmsha"
      set flabel(creep,mtha,)   "crmtha"
      set flabel(creep,gtha,)   "crgtha"
      set flabel(creep,ggar,)   "crggar"
      set flabel(creep,expo,)   "crexpo"
      set flabel(creep,nort,)   "crnort"
      set flabel(creep,psth,)   "crpsth"
      set flabel(creep,psrp,)   "crpsrp"

      set flabel(CREEP,SHAR)   "crshar"
      set flabel(CREEP,THAR)   "crthar"
      set flabel(CREEP,GEXP)   "crgexp"
      set flabel(CREEP,GGRA)   "crggra"
      set flabel(CREEP,GBLA)   "crgbla"
      set flabel(CREEP,MSHA)   "crmsha"
      set flabel(CREEP,MTHA)   "crmtha"
      set flabel(CREEP,GTHA)   "crgtha"
      set flabel(CREEP,GGAR)   "crggar"
      set flabel(CREEP,EXPO)   "crexpo"
      set flabel(CREEP,NORT)   "crnort"
      set flabel(CREEP,PSTH)   "crpsth"
      set flabel(CREEP,PSRP)   "crpsrp"

      set flabel(creep,shar)   "crshar"
      set flabel(creep,thar)   "crthar"
      set flabel(creep,gexp)   "crgexp"
      set flabel(creep,ggra)   "crggra"
      set flabel(creep,gbla)   "crgbla"
      set flabel(creep,msha)   "crmsha"
      set flabel(creep,mtha)   "crmtha"
      set flabel(creep,gtha)   "crgtha"
      set flabel(creep,ggar)   "crggar"
      set flabel(creep,expo)   "crexpo"
      set flabel(creep,nort)   "crnort"
      set flabel(creep,psth)   "crpsth"
      set flabel(creep,psrp)   "crpsrp"

      set shiftLabels [list tn wlf none]
      set numShiftLabels [llength $shiftLabels]
      for {set i 4} {$i <= 5} {incr i 1} {
          for {set j 4} {$j <= 5} {incr j 1} {
             for {set k 0} { $k < $numShiftLabels} {incr k 1} {
                 set sLabel [lindex $shiftLabels $k]
                 set sOrder "vipvhe[expr $i]_[expr $j]_$sLabel"
                 set sOrderParam "[expr $i]_[expr $j]_$sLabel"
                 set flabel(VISCO,PVHE,$sOrderParam) $sOrder
             }
          }
      }

      for {set i 1} {$i <= 5} {incr i 1} {
         for {set j 0} { $j < $numShiftLabels} {incr j 1} {
            set sLabel [lindex $shiftLabels $j]
            set sOrder "vipdec[expr $i]_$sLabel"
            set sOrderParam "[expr $i]_$sLabel"
            set flabel(VISCO,PDEC,$sOrderParam) $sOrder
         }
      }

      for {set i 1} {$i <= 20} {incr i 1} {
            set sOrder "VISCO,SHEAR,$i"
            set sOrderParam "vish[expr $i]"
            set flabel($sOrder) $sOrderParam
      }

      for {set i 1} {$i <= 20} {incr i 1} {
            set sOrder "VISCO,BULK,$i"
            set sOrderParam "vibk[expr $i]"
            set flabel($sOrder) $sOrderParam
      }

      set shiftLabels [list TN WLF NONE]
      set numShiftLabels [llength $shiftLabels]

      for {set i 0} {$i < 3} {incr i 1} {
            set sLabel [lindex $shiftLabels $i]
            set sOrder "VISCO,SHIFT,$sLabel"
            set sOrderParam "vish[string tolower $sLabel]"
            set flabel($sOrder) $sOrderParam
      }

      if { [catch {set FuncLabel $flabel($fname)} ] } {
         set FuncLabel $fname
      }
      return $FuncLabel
   }

# --------------------------------------------------------------
#  Function Name: ExpNameToLabelWithId
#  Purpose:       convert database function name to display label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
proc ExpNameToLabelWithId { ename expindex } {
    set curexpname [ExpNameToLabel $ename]
    set finalexpname "Exp:$expindex $curexpname"
}

# --------------------------------------------------------------
#  Function Name: ExpNameToLabel
#  Purpose:       convert database function name to display label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------

   proc ExpNameToLabel { ename } {

      # Set array of tree labels to show
      set elabel(unia) "Uniaxial Tension"
      set elabel(UNIA) "Uniaxial Tension"
      set elabel(biax) "Biaxial"
      set elabel(BIAX) "Biaxial"
      set elabel(shea) "Shear"
      set elabel(SHEA) "Shear"
      set elabel(sshe) "Simple Shear"
      set elabel(SSHE) "Simple Shear"
      set elabel(volu) "Volumetric"
      set elabel(VOLU) "Volumetric"
      set elabel(sdec) "Shear Modulus(Decay) Vs Time or Freq"
      set elabel(SDEC) "Shear Modulus(Decay) Vs Time or Freq"
      set elabel(bdec) "Bulk Modulus(Decay) Vs Time or Freq"
      set elabel(BDEC) "Bulk Modulus(Decay) Vs Time or Freq"
      set elabel(creep) "Creep Experimental Data"
      set elabel(CREEP) "Creep Experimental Data"

      if { [catch {set ExpLabel $elabel($ename)} ] } {
         set ExpLabel $ename
      }
      return $ExpLabel

   }

   proc matTable_State { tablestate } {

      variable treeMaterialParent
      variable modControlMenu

      if { [info exists tablestate] } {
         if { $tablestate == 1 } {
            foreach m {Function Edit Help} {
               $modControlMenu entryconfigure [msgcat::mc $m] -state normal
            }
            if { [info exists treeMaterialParent ] } {
               $treeMaterialParent configure -state normal
            }

            #refreshL
         } else {

            foreach m {Function Edit Help} {
               $modControlMenu entryconfigure [msgcat::mc $m] -state disabled
            }
            if { [info exists treeMaterialParent ] } {
               $treeMaterialParent configure -state disabled
            }

            #refreshL
         }
      }
   }

# --------------------------------------------------------------
#  Function Name: InitializeValidAttribs
#  Purpose:       convert database function name to display label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
proc InitializeValidAttribs {} {

    variable validAttribList

    set validAttribList(nexp) 12
    set validAttribList(expe,0) "unia"
    set validAttribList(expe,1) "biax"
    set validAttribList(expe,2) "shea"
    set validAttribList(expe,3) "volu"
    set validAttribList(expe,4) "sdec"
    set validAttribList(expe,5) "bdec"
    set validAttribList(expe,6) "creep"
    set validAttribList(expe,7) "funia"
    set validAttribList(expe,8) "fbiax"
    set validAttribList(expe,9) "fshea"
    set validAttribList(expe,10) "fvolu"
    set validAttribList(expe,11) "sshe"

    set validAttribList(unia,natt) 1
    set validAttribList(unia,attr,0) "temp"
    set validAttribList(unia,ncol) 2
    set validAttribList(unia,col,0) "Strain"
    set validAttribList(unia,col,1) "Stress"

    set validAttribList(biax,natt) 1
    set validAttribList(biax,attr,0) "temp"
    set validAttribList(biax,ncol) 2
    set validAttribList(biax,col,0) "Strain"
    set validAttribList(biax,col,1) "Stress"

    set validAttribList(shea,natt) 1
    set validAttribList(shea,attr,0) "temp"
    set validAttribList(shea,ncol) 2
    set validAttribList(shea,col,0) "Strain"
    set validAttribList(shea,col,1) "Stress"

    set validAttribList(sshe,natt) 1
    set validAttribList(sshe,attr,0) "temp"
    set validAttribList(sshe,ncol) 3
    set validAttribList(sshe,col,0) "Strain"
    set validAttribList(sshe,col,1) "Shear Stress"
    set validAttribList(sshe,col,2) "Normal Stress"

    set validAttribList(volu,natt) 1
    set validAttribList(volu,attr,0) "temp"
    set validAttribList(volu,ncol) 2
    set validAttribList(volu,col,0) "Strain"
    set validAttribList(volu,col,1) "Stress"

    set validAttribList(sdec,natt) 2
    set validAttribList(sdec,attr,0) "temp"
    set validAttribList(sdec,attr,1) "1"
    set validAttribList(sdec,ncol) 2
    set validAttribList(sdec,col,0) "Time"
    set validAttribList(sdec,col,1) "Shear modulus"

    set validAttribList(bdec,natt) 2
    set validAttribList(bdec,attr,0) "temp"
    set validAttribList(bdec,attr,1) "1"
    set validAttribList(bdec,ncol) 2
    set validAttribList(bdec,col,0) "Time"
    set validAttribList(bdec,col,1) "Bulk modulus"

    set validAttribList(creep,natt) 9
    set validAttribList(creep,attr,0) "1"
    set validAttribList(creep,attr,1) "2"
    set validAttribList(creep,attr,2) "3"
    set validAttribList(creep,attr,3) "4"
    set validAttribList(creep,attr,4) "time"
    set validAttribList(creep,attr,5) "dcre"
    set validAttribList(creep,attr,6) "creq"
    set validAttribList(creep,attr,7) "seqv"
    set validAttribList(creep,attr,8) "temp"
    set validAttribList(creep,ncol) 2
    set validAttribList(creep,col,0) "time"
    set validAttribList(creep,col,1) "equi stress"

    set validAttribList(funia,natt) 0
    set validAttribList(funia,ncol) 3
    set validAttribList(funia,col,0) "Strain"
    set validAttribList(funia,col,1) "Lateral Strain"
    set validAttribList(funia,col,2) "Engineering stress"

    set validAttribList(fbiax,natt) 0
    set validAttribList(fbiax,ncol) 3
    set validAttribList(fbiax,col,0) "Strain"
    set validAttribList(fbiax,col,1) "Thickness Strain"
    set validAttribList(fbiax,col,2) "Engineering Stress"

    set validAttribList(fshea,natt) 0
    set validAttribList(fshea,ncol) 3
    set validAttribList(fshea,col,0) "Strain"
    set validAttribList(fshea,col,1) "Thickness Strain"
    set validAttribList(fshea,col,2) "Engineering Stress"

    set validAttribList(fvolu,natt) 0
    set validAttribList(fvolu,ncol) 2
    set validAttribList(fvolu,col,0) "Volumetric Strain"
    set validAttribList(fvolu,col,1) "Stress"
}

# --------------------------------------------------------------
#  Function Name: GetNumValidAttribs
#  Purpose:       convert database function name to display label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
   proc GetNumValidAttribs { expName } {
      variable validAttribList
      set numAtts 0
      for { set iIndex 0 } { $iIndex < $validAttribList(nexp) } { incr iIndex 1 } {
         set curExpName $validAttribList(expe,$iIndex)
         if { [string equal -nocase -length 4 $curExpName $expName] } {
            set numAtts $validAttribList($curExpName,natt)
         }
      }

      return $numAtts
   }

# --------------------------------------------------------------
#  Function Name: GetIthAttrib
#  Purpose:       convert database function name to display label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
   proc GetIthAttrib { expName index } {
      variable validAttribList
      set attVal "undefined"
      for { set iIndex 0 } { $iIndex < $validAttribList(nexp) } { incr iIndex 1 } {
         set curExpName $validAttribList(expe,$iIndex)
         if { [string equal -nocase -length 4 $curExpName $expName] } {
            set attVal validAttribList($curExpName,attr,$iIndex)
            return $attVal
         }
      }

      return $attVal
   }
   
# --------------------------------------------------------------
#  Function Name: GetIthAttrib
#  Purpose:       convert database function name to display label
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
   proc IsValidAttrib { expName attName } {
      variable validAttribList
      set isValid 0      
      for { set iIndex 0 } { $iIndex < $validAttribList(nexp) } { incr iIndex 1 } {
         set curExpName $validAttribList(expe,$iIndex)
         if { [string equal -nocase -length 4 $curExpName $expName] } {
            for { set iEIndex 0 } { $iEIndex < $validAttribList($curExpName,natt) } { incr iEIndex 1 } {
               set curAttName $validAttribList($curExpName,attr,$iEIndex)
               set attName [string trim $attName]
               set curAttName [string trim $curAttName]
               if { [string equal -nocase -length 4 $curAttName $attName] } {
                  set isValid 1
               }
            }
         }
      }

      return $isValid
   }

# --------------------------------------------------------------
#  Function Name: GetTempOfExperiment
#  Purpose:       Gets the Temp of ExpIndex
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
proc GetTempOfExperiment { MatId ExpIndex } {
   variable funcTemp
   
   set numAttribs [ans_getvalue tbft,$MatId,expe,$ExpIndex,attnum]
         
   for { set iAttIndex 0 } { $iAttIndex < $numAttribs} { incr iAttIndex 1 } {
      set attIndxPlus [expr $iAttIndex+1]
      set attName [ans_getvalue tbft,$MatId,expe,$ExpIndex,attname,$attIndxPlus]
      set attValD [ans_getvalue tbft,$MatId,expe,$ExpIndex,attvald,$attIndxPlus]
      if { [string equal -nocase -length 4 $attName "temp"] } {
         set funcTemp $attValD 
         return $funcTemp
      }
   }

   return 0.0
}
      
# --------------------------------------------------------------
#  Function Name: KillGraphUtility
#  Purpose:       Kills The Graph Utility
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
proc KillGraphUtility {} {
   variable graphParent
   variable parent
   
   catch { wm inconify $graphParent }
   catch { lower $graphParent }
   catch { destroy $graphParent  }
   catch {   wm deiconify $parent  }
   catch {   raise $parent  }
}

         
# --------------------------------------------------------------
#  Function Name: MAT_GetExpColTypes
#  Purpose:       Get the column names for all exps
#  Arguments:     
#  Notes:        
#
# --------------------------------------------------------------
proc MAT_GetExpColTypes { expid } {
   variable matid
   variable cF
   variable GraphVar
   variable parent
   variable avlTypes
     
   #Return if it is not a Function
   set fname [ CommandToFuncName $cF(HyperChoice) ]
   set fname [string trim $fname]
   set existKey [ ConstitutiveFunctionExists $matid $fname ]
   
   if { $existKey == 0 } {
      ans_senderror 2 "Invalid Case/Function Name for Fitting Function \n"
      return
   }
   
   #Check if it is a creep model
   set avlTypes [list]
   set attList [list]
   set expNameList [list]
   set expIDList [list]
   set numGraphObjects 0
   set numExperiments [ans_getvalue tbft,$matid,nexp]
   set eType [ans_getvalue tbft,$matid,expe,$expid,type]
   set eType [string trim $eType]
   set eType [string tolower $eType]
   lappend expNameList $eType
   if { [string equal -nocase -length 4 $eType "creep"] } {
      set iNumAtt [ans_getvalue tbft,$matid,expe,$expid,natt]
      for {set iIndex 0} {$iIndex < $iNumAtt} {incr iIndex 1} {
         set attIdx [expr $iIndex+1]
         set attName [ans_getvalue tbft,$matid,expe,$expid,attname,$attIdx]
         set attName [string trim $attName]
         set attName [string tolower $attName]

         set attValS [ans_getvalue tbft,$matid,expe,$expid,attvals,$attIdx]
         set attValS [string trim $attValS]
         set attValS [string tolower $attValS]
                  
         for { set iCol 1 } { $iCol < 10 } { incr iCol 1 } {
            set ColName "$iCol"
            set ColNameLen [string length $ColName]
            if { [string equal -length $ColNameLen -nocase $ColName $attName] } {
               if { [lsearch avlTypes $attValS] < 0 } {
                  lappend avlTypes $attValS
               }
            }
         }
      }
   }
   
   return $avlTypes
}


# --------------------------------------------------------------
#  Function Name: LaunchGraphUtility
#  Purpose:       Launches The Graph Utility
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
proc LaunchGraphUtility { expid } {

   variable matid
   variable cF
   variable optionalCaseName
   variable graphParent
   variable parent
   variable detailedExpName
   variable detailedFuncName
   variable detailedGraphName
   variable validAttribList
   variable numGraphObjects
   variable curveexist
   variable eType
   variable curExpId
   variable axisscale0
   variable axisscale1
   variable axisscale2
   variable axisscale3
   variable axisscale4
   variable lowerlimit
   variable upperlimit
   variable GraphVar
   variable matStates

   #array set lowerlimit ""
   #array set upperlimit ""

   set axisscale0 "default"
   set axisscale1 "default"
   set axisscale2 "default"
   set axisscale3 "default"
   set axisscale4 "default"
   
   catch {unset curveexist }
   if {[catch {package require BLT} err]} {
      # We hit an error in BLT so leave
      return -code error $err
   }

   #Return if it is not a Function
   set fname [ CommandToFuncName $cF(HyperChoice) ]
   set fname [string trim $fname]
   set existKey [ ConstitutiveFunctionExists $matid $fname ]

   if { $existKey == 0 } {
      ans_senderror 2 "Invalid Case/Function Name for Fitting Function \n"
      return
   }

   set childsite [$parent component childsite]
   set allchildren [winfo children $childsite]

   if { [lsearch $allchildren "$childsite.funcdefmenuframe"] > -1 } {
        catch { grid remove $childsite.funcdefmenuframe }
   }

   if { [lsearch $allchildren "$childsite.nonlinearsettings"] > -1 } {
      catch { grid remove $childsite.nonlinearsettings }
   }

   if { [lsearch $allchildren "$childsite.funcdefframe"] > -1 } {
      catch { grid remove $childsite.funcdefframe }
   }

   if { [lsearch $allchildren "$childsite.funcparamframe"] > -1 } {
      catch { grid remove $childsite.funcparamframe }
   }

   if { [lsearch $allchildren "$childsite.nonlinearsettings"] > -1 } {
      catch { grid remove $childsite.nonlinearsettings }
   }

   if { [lsearch $allchildren "$childsite.expframe"] > -1 } {
        grid remove $childsite.expframe        
   }
   
   if { [lsearch $allchildren "$childsite.plotframe"] > -1 } {
      grid remove $childsite.plotframe        
      set plotparent $childsite.plotframe
   } else {
      set plotparent [::euidl::labeledframe $childsite.plotframe -text Plot ]
      $plotparent configure -text [msgcat::mc "Curve Fitting Plots"]
   }


   #plot the frame into which all graph go into
   grid $childsite.plotframe -row 0 -column 1 -sticky news
   grid columnconfigure $childsite 0 -weight 0
   grid columnconfigure $childsite 1 -weight 1
   grid columnconfigure $childsite 2 -weight 0
   grid columnconfigure $childsite 3 -weight 0
   grid columnconfigure $childsite 4 -weight 0
   grid columnconfigure $childsite 5 -weight 0
   grid rowconfigure $childsite 0 -weight 1
   grid rowconfigure $childsite 1 -weight 0
   set childsite [$plotparent component childsite]

   set detailedFuncName "CurveFitting Plot"
   set detailedExpName " "

   #Clean up old stuff
   if { [info exists numGraphObjects] } {
      for { set iIndex 1 } { $iIndex <= $numGraphObjects } { incr iIndex 1 } {
         catch { destroy $childsite.graphObject$iIndex }
      }
   }
         
   #Get the default back/foreground color
   euidl::entry  $childsite.junkentry
   set entryBGColor [ $childsite.junkentry cget -background ]
   set entryFGColor [ $childsite.junkentry cget -entryforeground ]
   destroy $childsite.junkentry
   set entryBGColor black
   
   # GRAPH AREA
   catch {package require BLT} err
   
   #check if such an experiment exists
   set numExperiments [ans_getvalue tbft,$matid,nexp]
   set expExistsKey 0
   if { [string equal -nocase $expid "all"] || $expid <= $numExperiments } {
      set expExistsKey 1
   }

   if { $expExistsKey == 0 } {
      ans_senderror 2 "Invalid Experiment Name. Cannot Plot \n"
      return
   }

   set expNameList [list]
   set expIDList [list]
   set numGraphObjects 0
   set maxColors 0
   set maxSymbols 0
   set idxNum -1

   foreach ci [::euidl::graphics::colorSettings::getColorData index] {
      foreach {r g b} $ci {
         set color([incr idxNum]) [format #%02x%02x%02x $r $g $b]
      }
   }
   set maxColors $idxNum
   array set symbol [list 0 circle 1 square 2 diamond 3 plus 4 cross \
         5 splus 6 scross 7 triangle]
 
   set data [fnametocolour $fname]
   # set symbolc [fnametosymbol $fname]
   set maxSymbols 8

   if { [string equal -nocase $expid "all"]  } {
      for { set iExpIndex 1 } { $iExpIndex <= $numExperiments } { incr iExpIndex 1 } {
         set eType [ans_getvalue tbft,$matid,expe,$iExpIndex,type]
         set eType [string trim $eType]
         set eType [string tolower $eType]
         set position [lsearch $expNameList $eType]
         
         set iSameType 0
         if { [info exists matStates(Visco)] } {
            if { $matStates(Visco) == 1 && 
                 (    [string equal -nocase -length 4 $eType "sdec"] 
                   || [string equal -nocase -length 4 $eType "bdec"] ) } {
               set iSameType 1
            }              
         }
         if { [info exists matStates(Creep)] } {
            if { $matStates(Creep) == 1 && [string equal -nocase -length 4 $eType "creep"] } {
               set iSameType 1
            }              
         }
         if { [info exists matStates(Hyper)] } {
            if { $matStates(Hyper) == 1 && 
                 (    [string equal -nocase -length 4 $eType "unia"] 
                   || [string equal -nocase -length 4 $eType "biax"]
                   || [string equal -nocase -length 4 $eType "sshe"]
                   || [string equal -nocase -length 4 $eType "shea"]
                   || [string equal -nocase -length 4 $eType "volu"]
                   || [string equal -nocase -length 4 $eType "funia"]
                   || [string equal -nocase -length 4 $eType "fbiax"]
                   || [string equal -nocase -length 4 $eType "fsshe"]
                   || [string equal -nocase -length 4 $eType "fshea"]
                   || [string equal -nocase -length 4 $eType "fvolu"]
                    ) } {
               set iSameType 1
            }              
         }
         if { [info exists matStates(Plast)] } {
            if { $matStates(Plast) == 1 && 
                 (    [string equal -nocase -length 4 $eType "unia"] 
                    ) } {
               set iSameType 1
            }              
         }
         
         if { $iSameType == 1 } {
            if { $position < 0 } {
   
               lappend expNameList $eType
               catch { destroy $childsite.graphObject$numGraphObjects }
               set graphObject [::blt::graph $childsite.graphObject$numGraphObjects -plotbackground white -width 1i -height 1i]
               $graphObject legend configure -font {Times 8 normal} -position plotarea -anchor ne
               catch {Blt_Crosshairs $graphObject} err
               ShowClosestBindCtlMiddleClick $graphObject
            
               bind $graphObject <Button-3> \
               [list [namespace code ShowGraphContextMenu] $graphObject %x %y $numGraphObjects $eType $fname $numGraphObjects $iExpIndex]
               $graphObject grid configure -color "black" -linewidth 2 -mapx x -mapy y
               $graphObject grid off
                               
               set iRow [expr int([expr $numGraphObjects/2])]
               set iCol [expr $numGraphObjects % 2]
               grid $graphObject -row $iRow -column $iCol -sticky news -columnspan 1 -rowspan 1
               grid columnconfigure $childsite $iCol -weight 1
               grid rowconfigure $childsite $iRow -weight 1
               incr numGraphObjects 1
            }
            lappend expIDList $iExpIndex
         }
      }
   } else {
      lappend expIDList [expr $expid]
      set numGraphObjects 1
      set eType [ans_getvalue tbft,$matid,expe,$expid,type]
      set eType [string trim $eType]
      set eType [string tolower $eType]
      lappend expNameList $eType
      catch { destroy $childsite.graphObject0 }
      set graphObject [::blt::graph $childsite.graphObject0 -plotbackground white]
      $graphObject legend configure -font {Times 8 normal} -position plotarea -anchor ne
      catch {Blt_Crosshairs $graphObject} err
      ShowClosestBindCtlMiddleClick $graphObject
      bind $graphObject <Button-3> \
       [list [namespace code ShowGraphContextMenu] $graphObject %x %y $numGraphObjects $eType $fname 0 $expid]

      $graphObject grid configure -color "black" -linewidth 2 -mapx x -mapy y
      $graphObject grid off

      grid $graphObject -row 0 -column 0 -sticky news
      grid columnconfigure $childsite 0 -weight 1
      grid rowconfigure $childsite 0 -weight 1
      grid columnconfigure $childsite 1 -weight 0
   }
      
   
   #Now Go through all experiments and plot
   set numPlotExps [llength $expIDList]
   grid columnconfigure $childsite 2 -weight 0
   set nextCol  [expr ($numPlotExps/2)+1]
   set nextCol [expr int($nextCol)]
   grid rowconfigure $childsite $nextCol -weight 0

   set iElemIndex 0
   for { set iIndex 0 } { $iIndex < $numPlotExps } { incr iIndex 1 } {
      #Get the type
      set curExpId [lindex $expIDList $iIndex]
      set eType [ans_getvalue tbft,$matid,expe,$curExpId,type]
      set eType [string trim $eType]
      set eType [string tolower $eType]

      #Get the object into which to be plotted      
      set curPlotObjIndex [lsearch $expNameList $eType]
      if { $curPlotObjIndex < 0 } {
           ans_senderror 2 "Developer Error while plotting \n"
           return      
      }

      ::apdl::noerr 1
      set iNumErrBef [ans_evalexpr erinqr(5)]
      catch {set fittedData [cft_getfitteddata $matid [expr $curExpId -1] $fname]}
      ::apdl::noerr 0
      set iNumErrAft [ans_evalexpr erinqr(5)]
      if { $iNumErrBef != $iNumErrAft } {
         ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
         return      
      }
   
      set detailedExpName [ExpNameToLabel $eType]
      set detailedFuncName [FuncNameToLabel $fname]
      set detailedGraphName [msgcat::mc "%s with %s" $detailedExpName $detailedFuncName]
      $childsite.graphObject$curPlotObjIndex configure -title $detailedGraphName
   
      set numData [llength $fittedData]
      for { set iCIndex 0 } { $iCIndex < $numData } { incr iCIndex 1 } {
         set axisData($iCIndex) [lindex $fittedData $iCIndex]
      }

      set testlen [llength $axisData(0)]
      set lowerlimit($iIndex) [lindex $axisData(0) 0]
      set upperlimit($iIndex) [lindex $axisData(0) [expr $testlen-1]]

      set curveName(1) "Exp Data $curExpId"
      set curveName(2) "$detailedFuncName"
      set curveName(3) "$detailedFuncName"
      set curveName(4) "$detailedFuncName"
      set curveName(5) "$detailedFuncName"
      set curveName(6) "$detailedFuncName"

      set temperature 0
      if { $eType == "sdec" || $eType == "bdec" } {
         $childsite.graphObject$curPlotObjIndex axis configure x -logscale yes
         set expIdMinusOne [expr $curExpId - 1]
         set numAttribs [ans_getvalue tbft,$matid,expe,$curExpId,attnum]
         for { set iAttIndex 0 } { $iAttIndex < $numAttribs} { incr iAttIndex 1 } {
            set attIndxPlus [expr $iAttIndex+1]
            set attName [ans_getvalue tbft,$matid,expe,$curExpId,attname,$attIndxPlus]
            set attValD [ans_getvalue tbft,$matid,expe,$curExpId,attvald,$attIndxPlus]
            if { [string equal -nocase -length 4 $attName "temp"] } {
               set temperature $attValD 
            }
         }
         set curveName(1) "Exp Data $curExpId, Temp = $temperature"
         set curveName(2) "$detailedFuncName $curExpId, Temp = $temperature"
         
         if { $numData == 5 } {
            set curveName(1) "Storage Mod $curExpId, Temp = $temperature"
            set curveName(2) "Loss Mod $curExpId, Temp = $temperature"
            set curveName(3) "$detailedFuncName St Mod $curExpId, Temp = $temperature"
            set curveName(4) "$detailedFuncName Loss Mod $curExpId, Temp = $temperature"
         }
      }


      if { [string equal -nocase -length 4 $eType "sshea"] } {
         set curveName(1) "Exp Data"
         if { $numData == 4 } {
            set curveName(2) "$detailedFuncName"
            set curveName(3) "Trans Stress Fitted Data"
         }
         if { $numData == 5 } {
            set curveName(2) "Trans Stress Exp Data"
            set curveName(3) "$detailedFuncName"
            set curveName(4) "Trans Stress Fitted Data"
         }
      }

      if { [string equal -nocase -length 6 $fname "hyfoam"] } {
          array set curveName [GetHyperFoamColumnNames $fname $eType]
      }
      
      #Configure Axis names
      set ename [string tolower $eType]
      InitializeValidAttribs
      if { [info exists validAttribList($ename,ncol)]} {
         set numCols $validAttribList($ename,ncol)
         if { $numCols >= 2 } {
            $childsite.graphObject$curPlotObjIndex axis configure x -title [msgcat::mc "%s" $validAttribList($ename,col,0)]
            $childsite.graphObject$curPlotObjIndex axis configure y -title [msgcat::mc "%s" $validAttribList($ename,col,[expr $numCols - 1])]
         }
      }

      if { $eType == "sdec" || $eType == "bdec" } {
         if { $numData == 5 } {
            $childsite.graphObject$curPlotObjIndex axis configure x -title [msgcat::mc "%s" "Freq" ]
            $childsite.graphObject$curPlotObjIndex axis configure y -title [msgcat::mc "%s" $validAttribList($ename,col,[expr $numCols - 1])]
         }
      }

      if { [string equal -nocase -length 4 $eType "creep"] } {

         array set curveme [GetColumnNames $matid $curExpId]
         set UserReqCols [list]
         for { set iColIndex 0 } { $iColIndex < 10 } { incr iColIndex 1 } {
            if { [info exists GraphVar($iColIndex)] } {
                if { $GraphVar($iColIndex) != "" } {
                    lappend UserReqCols $GraphVar($iColIndex)
                }
            } else {
               if { $iColIndex == 0 } {
                  set GraphVar(0) 0
               }
            }
         }
         set iXDataPos 0
         for {set iX 0} {$iX < $curveme(numcol)} {incr iX 1} {
            if { [info exists curveme(abbr,$iX)] } {
               if { [string equal -length 4 -nocase $GraphVar(0) $curveme(abbr,$iX)] } {
                  set iXDataPos $iX
               }
            }
         }
         
         for { set iCIndex 1 } { $iCIndex < $numData } { incr iCIndex 1 } {
         
            set combIndex [expr $iCIndex+($numExperiments*$curExpId)]
            set iRow [expr int([expr $combIndex/$numExperiments])]
            set iCol [expr $combIndex % $numExperiments]
            set iSymbolIndex [expr ($iElemIndex%$maxSymbols)]
            set iColorIndex [expr ($iElemIndex%$maxColors)]
            incr iElemIndex 1
            
            if {$iCIndex == 1} {
              $childsite.graphObject$curPlotObjIndex \
                     element create Curve($iCIndex,$fname,$curExpId,$eType)  -xdata $axisData($iXDataPos) -ydata $axisData($iCIndex) \
                     -symbol $symbol($iSymbolIndex) -color $color($iSymbolIndex) \
                     -scalesymbols true -label $curveName($iCIndex) -pixels 0.040i -linewidth 1

            } elseif { $iCIndex >1 } {
               set curveName(2) "$detailedFuncName-$curveme($iCIndex)"
               set curveName(3) "$detailedFuncName-$curveme($iCIndex)"
               set curveName(4) "$detailedFuncName-$curveme($iCIndex)"
               set curveName(5) "$detailedFuncName-$curveme($iCIndex)"
               set curveName(6) "$detailedFuncName-$curveme($iCIndex)" 
               $childsite.graphObject$curPlotObjIndex \
                      element create Curve($iCIndex,$fname,$curExpId,$eType)  -xdata $axisData($iXDataPos) -ydata $axisData($iCIndex) \
                         -symbol $symbol($iCIndex) -color $data \
                         -scalesymbols true -label $curveName($iCIndex) -pixels 0.040i -linewidth 1

               lappend curveexist Curve($iCIndex,$fname,$curExpId,$eType)
            }
            # $childsite.graphObject$curPlotObjIndex element bind Curve($iIndex,$iCIndex) <Button-3> \
            #[code ToggleGraphElement $childsite.graphObject$curPlotObjIndex Curve($iIndex,$iCIndex) ]
            $childsite.graphObject$curPlotObjIndex element bind Curve($iCIndex,$fname,$curExpId,$eType) <Button-2> \
            [list [namespace code  ShowElementContextMenu] \
            $childsite.graphObject$curPlotObjIndex Curve($iCIndex,$fname,$curExpId,$eType) %x %y ]
         }

         #Configure Axis names
         $childsite.graphObject$curPlotObjIndex axis \
              configure x -title [msgcat::mc $curveme($iXDataPos)]
         $childsite.graphObject$curPlotObjIndex axis \
              configure y -title [msgcat::mc $curveme(1)]

      } else {
         for { set iCIndex 1 } { $iCIndex < $numData } { incr iCIndex 1 } {

            set combIndex [expr $iCIndex+($numExperiments*$curExpId)]
            set iRow [expr int([expr $combIndex/$numExperiments])]
            set iCol [expr $combIndex % $numExperiments]
            set iSymbolIndex [expr ($iElemIndex%$maxSymbols)]
            set iColorIndex [expr ($iElemIndex%$maxColors)]
            incr iElemIndex 1

            if {$iCIndex == 1} {
                $childsite.graphObject$curPlotObjIndex \
                element create Curve($iCIndex,$fname,$curExpId,$eType) -xdata $axisData(0) -ydata $axisData($iCIndex) \
                -symbol $symbol($iSymbolIndex) -color $color($iSymbolIndex) \
                -scalesymbols true -label $curveName($iCIndex) -pixels 0.040i -linewidth 1

                $childsite.graphObject$curPlotObjIndex element bind Curve($iCIndex,$fname,$curExpId,$eType) <Button-2> \
                [list [namespace code  ShowElementContextMenu] \
                $childsite.graphObject$curPlotObjIndex Curve($iCIndex,$fname,$curExpId,$eType) %x %y ]
            } elseif { $iCIndex >1 } {
                $childsite.graphObject$curPlotObjIndex \
                element create Curve($iCIndex,$fname,$curExpId,$eType) -xdata $axisData(0) -ydata $axisData($iCIndex) \
                -symbol $symbol($iCIndex) -color $data \
                -scalesymbols true -label $curveName($iCIndex) -pixels 0.040i -linewidth 1
                lappend curveexist Curve($iCIndex,$fname,$curExpId,$eType)

                $childsite.graphObject$curPlotObjIndex element bind Curve($iCIndex,$fname,$curExpId,$eType) <Button-2> \
                [list [namespace code  ShowElementContextMenu] \
                $childsite.graphObject$curPlotObjIndex Curve($iCIndex,$fname,$curExpId,$eType) %x %y ]
            }

            #$childsite.graphObject$curPlotObjIndex element bind Curve($iIndex,$iCIndex) <Button-3> \
            # [code ToggleGraphElement $childsite.graphObject$curPlotObjIndex Curve($iIndex,$iCIndex) ]
            $childsite.graphObject$curPlotObjIndex element bind Curve($iCIndex,$fname,$curExpId,$eType) <Button-2> \
            [list [namespace code ShowElementContextMenu] \
            $childsite.graphObject$curPlotObjIndex Curve($iCIndex,$fname,$curExpId,$eType) %x %y  ]
         }
      }
   
   
      refresh
   }
   return
}

# --------------------------------------------------------------
#  Function Name: ExpandGraphToFillPage
#  Purpose:       Expand a graph to fill page
#  Arguments:     function name
#  Notes:        
#
# --------------------------------------------------------------
proc ExpandGraphToFillPage { graphObject } {
   variable numGraphObjects
   variable parent
   
   set childsite [$parent component childsite]
   set allchildren [winfo children $childsite]

   if { [lsearch $allchildren "$childsite.plotframe"] < 0 } {
      return
   }
   
   set plotparent $childsite.plotframe
   set childsite [$plotparent component childsite]
   
   #Clean up old stuff
   if { [info exists numGraphObjects] } {
      for { set iIndex 1 } { $iIndex <= $numGraphObjects } { incr iIndex 1 } {
         catch { grid remove $childsite.graphObject$iIndex }
      }
   }
   
   grid $graphObject -row 0 -column 0 -sticky news
   grid columnconfigure $childsite 0 -weight 1
   grid rowconfigure $childsite 0 -weight 1
   grid columnconfigure $childsite 1 -weight 0
   for { set iIndex 1 } { $iIndex < $numGraphObjects } { incr iIndex 1 } {
      grid rowconfigure $childsite $iIndex -weight 0
   }

   return
}

# --------------------------------------------------------------
#  Function Name: ToggleGraphElement
#  Purpose:       Turn on/off graph element
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc ToggleGraphElement { graphobject elementobject } {
   $graphobject element configure $elementobject -hide true 
}

# --------------------------------------------------------------
#  Function Name: HideLinesGraphElement
#  Purpose:       Turn on/off graph connecting lines
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc HideLinesGraphElement { graphobject elementobject } {
   $graphobject element configure $elementobject -linewidth 0
}

# --------------------------------------------------------------
#  Function Name: HideLinesGraphElement
#  Purpose:       Turn on/off graph connecting lines
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc ShowLinesGraphElement { graphobject elementobject } {
   $graphobject element configure $elementobject -linewidth 1
}


# --------------------------------------------------------------
#  Function Name: TraceTypeForGraphElement
#  Purpose:       Trace Type Flag
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc TraceTypeForGraphElement { graphobject elementobject iTrFlag} {
   if { $iTrFlag == 1 } {
       $graphobject element configure $elementobject -trace increasing
   } 
   if { $iTrFlag == 2 } {
       $graphobject element configure $elementobject -trace decreasing
   }
   if { $iTrFlag == 0 } {
       $graphobject element configure $elementobject -trace both
   }
}



# --------------------------------------------------------------
#  Function Name: ShowClosestBindCtlMiddleClick
#  Purpose:       Turn on/off graph element
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc ShowClosestBindCtlMiddleClick { graph {event "ButtonPress-1"} } {
    bind closest-point-$graph <$event>  {
       ::euidl::material::CurveFit::FindClosestPointInGraph %W %x %y
    }
    blt::AddBindTag $graph closest-point-$graph
}

# --------------------------------------------------------------
#  Function Name: ToggleGraphElement
#  Purpose:       Turn on/off graph element
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc FindClosestPointInGraph { graph x y } {

    if ![$graph element closest $x $y info -interpolate yes] {
       return
    }
    
    # --------------------------------------------------------------
    # find(name)        - element Id
    # find(index)        - index of closest point
    # find(x) find(y)        - coordinates of closest point
    #                  or closest point on line segment.
    # find(dist)        - distance from sample coordinate
    # --------------------------------------------------------------
    set markerName "CurveFitClosest"
    catch { $graph marker delete $markerName }
    
    $graph marker create text -coords { $info(x) $info(y) } \
    -name $markerName \
    -text "$info(x),$info(y)" \
    -font *lucida*-r-*-10-* \
    -anchor center -justify center \
    -yoffset 10 -bg {} 
}

# --------------------------------------------------------------
#  Function Name: GraphReplot
#  Purpose:       Shows Context Menu
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc GraphReplot { xtype } {
   variable GraphVar   
   set GraphVar(0) $xtype
   LaunchGraphUtility "all"
}

# --------------------------------------------------------------
#  Function Name: ShowGraphContextMenu
#  Purpose:       Shows Context Menu
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc ShowGraphContextMenu  { graph gX gY numGraphObjects eType fname gidx expid} {

   variable fuse
   variable curveexist
   variable axisscale0
   variable axisscale1
   variable axisscale2
   variable axisscale3
   variable axisscale4

      for { set index 0 } { $index < 50 } { incr index 1 } {
          variable xAxisLogToggleValue$index
          variable yAxisLogToggleValue$index
      }

   variable curExpId
   variable matid

   # Position of the pointer 
   set contextX [winfo pointerx .]
   set contextY [winfo pointery .]

   # The context menu will be rebuilt for the selected entities
   if [winfo exists ${graph}_contextmenu] {
      destroy ${graph}_contextmenu
      destroy ${graph}_contextmenu.legend
      destroy ${graph}_contextmenu.grid
      destroy ${graph}_contextmenu.axis
   }

   set menu 0
   set cmnu [menu ${graph}_contextmenu \
         -tearoff no \
         -borderwidth 1]

   $cmnu add command \
            -command [list [namespace code zoommode] $graph] \
            -underline 1 \
            -label [msgcat::mc "Zoom"]
   $cmnu add command \
            -command [list [namespace code zoomback] $graph] \
            -underline 1 \
            -label [msgcat::mc "Zoom Back"]
   $cmnu add command \
            -command [list [namespace code zoomfit] $graph] \
            -underline 1 \
            -label [msgcat::mc "Fit"]
   $cmnu add command \
            -command [list [namespace code ShowAllElements] $graph] \
            -label [msgcat::mc "Show All Curves"]
   $cmnu add command \
            -command [list [namespace code ExpandGraphToFillPage] $graph] \
            -label [msgcat::mc "Maximize"]
   $cmnu add command \
            -command [list [namespace code PlotGraphToFile] $graph] \
            -label [msgcat::mc "Plot to File"]

   set cmnu_legend [menu $cmnu.legend \
         -tearoff no \
         -borderwidth 1]

   $cmnu_legend add command \
            -command [list [namespace code ShowLegend] $graph] \
            -underline 1 \
            -label [msgcat::mc "Show"]
   $cmnu_legend add command \
            -command [list [namespace code HideLegend] $graph] \
            -underline 1 \
            -label [msgcat::mc "Hide"]

   $cmnu add cascade -label [msgcat::mc "Legend"] \
           -menu $cmnu.legend

   set cmnu_grid [menu $cmnu.grid \
         -tearoff no \
         -borderwidth 1]

   $cmnu_grid add command \
            -command [list [namespace code ShowGrid] $graph] \
            -underline 1 \
            -label [msgcat::mc "Show"]
   $cmnu_grid add command \
            -command [list [namespace code HideGrid] $graph] \
            -underline 1 \
            -label [msgcat::mc "Hide"]

   $cmnu add cascade -label [msgcat::mc "Grid"] \
           -menu $cmnu.grid


   set cmnu_axisctl [menu $cmnu.axiscontrols \
         -tearoff no \
         -borderwidth 1]

   set cmnu_axis [menu $cmnu_axisctl.axis \
         -tearoff no \
         -borderwidth 1]
         
   $cmnu_axis add checkbutton \
            -command [list [namespace code XAxisLogToggle ] $graph $gidx] \
            -underline 1 \
            -variable [scope xAxisLogToggleValue$gidx ] \
            -label [msgcat::mc "X Axis Log"]
   $cmnu_axis add check \
            -command [list [namespace code YAxisLogToggle] $graph $gidx] \
            -variable [scope yAxisLogToggleValue$gidx ] \
            -underline 1 \
            -label [msgcat::mc "Y Axis Log"]

   $cmnu add cascade -label [msgcat::mc "Axis Controls"] \
           -menu $cmnu.axiscontrols
   $cmnu_axisctl add cascade -label [msgcat::mc "Axis Scale"] \
           -menu $cmnu_axisctl.axis


   set cmnu_rmb [menu $cmnu.rmb \
         -tearoff no \
         -borderwidth 1]
  
   set nexp [ ans_getvalue tbft,$matid,nexp]

   for { set iIndex 1 } { $iIndex <= $nexp } { incr iIndex 1 } {
       set eType2 [ans_getvalue tbft,$matid,expe,$iIndex,type]
       set eType2 [string trim $eType2 ] 

       if {$eType2 == $eType} {
         
          set matnum 1
          set m [ans_getvalue tbft,,matnum,$matnum]
          set funcnum 1
          set maxFunc [ans_getvalue tbft,$m,nfun]
          set maxFunc [ans_evalexpr $maxFunc]

          while {$funcnum <= $maxFunc} {
           
              set f [ans_getvalue tbft,$m,func,$funcnum,fname]
              set f [string trim $f]
              if { [catch {set fittedData [cft_getfitteddata $matid [expr $iIndex-1] $f]} ] } {
                 ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
                 return      
              }
              set numData [llength $fittedData]

              set iSIndex 2
              if { [string equal -nocase -length 4 $eType "sshea"] && $numData == 5 } {
                  set iSIndex 3
              }
              
              for { set iCIndex $iSIndex } { $iCIndex < $numData } { incr iCIndex 1 } {
                  if { [string equal -nocase -length 4 $eType "creep"] } {

                     array set curveme [GetColumnNames $matid $curExpId]
                     #set fuse "[FuncNameToLabel $f]-$curveme($iCIndex)"
                     set fuse "[FuncNameToLabel $f]"
                  } else {
                     set fuse [FuncNameToLabel $f]
                     #Special Case for Simple Shear
                     if { [string equal -nocase -length 4 $eType "sshea"] } {
                        if { ($numData == 4 && $iCIndex == 3) || ($numData == 5 && $iCIndex == 4) } {
                            set fuse "$fuse Trans Stress Fitted Data"
                        }
                     }
                     if { [string equal -length 6 -nocase "hyfoam" $f] } {
                        array set HFNames [GetHyperFoamColumnNames $f $eType]
                        set fuse $HFNames($iCIndex)
                     }
                     #lappend fuse $iIndex
                  }

                  set scurvename [lsearch -exact $curveexist "Curve($iCIndex,$f,$iIndex,$eType)"]
                  set tb "tb_${funcnum}_${iIndex}_${iCIndex}"
               
                  if { $scurvename == "-1" } { 
   
                     $cmnu_rmb add checkbutton \
                            -label [msgcat::mc "$fuse"] \
                            -variable hfunc$tb \
                            -command [list [namespace code RMB_MatCurveFitFunc] $f $graph $numGraphObjects $iIndex $eType $iCIndex] 
                            set ::hfunc$tb 0
                  } else {
                      $cmnu_rmb add checkbutton \
                            -label [msgcat::mc "$fuse"] \
                            -variable hfunc$tb \
                            -command [list [namespace code RMB_MatCurveFitFunc] $f $graph $numGraphObjects $iIndex $eType $iCIndex] 
                            set ::hfunc$tb 1
                  }
              }
              incr funcnum
          }
      }
   }

   $cmnu add cascade -label [msgcat::mc "Available Fits"] \
   -menu $cmnu.rmb

   if { ![string equal -length 6 -nocase "hyfoam" $fname] } {
      set cmnu_scale [menu $cmnu.scale \
            -tearoff no \
            -borderwidth 1]

      $cmnu_scale add radio -label [msgcat::mc "Default"] -underline 1 -variable [scope axisscale$numGraphObjects] -value default \
           -command [list [namespace code AddFittedDataToGraph] $graph "default" $numGraphObjects $eType ]

      $cmnu_scale add radio -label [msgcat::mc "10"] -underline 1 -variable [scope axisscale$numGraphObjects] -value 10 \
           -command [list [namespace code AddFittedDataToGraph] $graph "10" $numGraphObjects $eType ]

      $cmnu_scale add radio -label [msgcat::mc "100"] -underline 1 -variable [scope axisscale$numGraphObjects] -value 100 \
           -command [list [namespace code AddFittedDataToGraph] $graph "100" $numGraphObjects $eType ]

      $cmnu_scale add radio -label [msgcat::mc "1000"] -underline 1 -variable [scope axisscale$numGraphObjects] -value 1000 \
           -command [list [namespace code AddFittedDataToGraph] $graph "1000" $numGraphObjects $eType ]

      $cmnu_scale add radio -label [msgcat::mc "10000"] -underline 1 -variable [scope axisscale$numGraphObjects] -value 10000 \
           -command [list [namespace code AddFittedDataToGraph] $graph "10000" $numGraphObjects $eType ]

      $cmnu_axisctl add cascade -label [msgcat::mc "Number of Points"] \
              -menu $cmnu.scale
   }

   $cmnu_axisctl add command \
            -command [list [namespace code limitsbox] $graph "lowerlimit" $numGraphObjects $eType] \
            -underline 1 \
            -label [msgcat::mc "X-Axis Minimum"]

   $cmnu_axisctl add command \
            -command [list [namespace code limitsbox] $graph "upperlimit" $numGraphObjects $eType]\
            -underline 1 \
            -label [msgcat::mc "X-Axis Maximum"]
            
   if { [string equal -length 4 -nocase $eType "creep"] } {                 
      set avlTypes [MAT_GetExpColTypes $expid]
   
      set cmnu_xaxisopt [menu $cmnu.xaxisopt \
            -tearoff no \
            -borderwidth 1]
      set iNumTypes [llength $avlTypes]
      for {set iIndex 0} { $iIndex < $iNumTypes} {incr iIndex 1} {
         set cType [lindex $avlTypes $iIndex]
         $cmnu_xaxisopt add radiobutton \
                 -underline 1 \
                 -label [msgcat::mc "$cType"] \
                 -command [list [namespace code GraphReplot] $cType]
      }
      $cmnu_axisctl add cascade -label [msgcat::mc "Change XAxis Data"] \
              -menu $cmnu.xaxisopt
   }

   tk_popup $cmnu [expr $contextX - 5] [expr $contextY - 5]
}

#---------------------------------------------------------------
#  Function Name: RMB_MatCurveFitFunc
#  Purpose:       Shows Context Menu
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc RMB_MatCurveFitFunc { fname graphObject numGraphObjects iIndex eType iCIndex} {
    variable matid
    variable cF
    variable matStates
    variable childsite

    set numExperiments [ans_getvalue tbft,$matid,nexp]
    set experid $numGraphObjects
    set cF(HyperChoice) [FuncNameToCommand $fname]
    AddCurveToGraph $graphObject $matid $fname $experid $iIndex $eType $iCIndex

}

#---------------------------------------------------------------
#  Function Name: GetCurveData
#  Purpose:       Getting fitted data 
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------

proc GetCurveData { materialId FunctionName ExperimentIndex } {
   

   set fittedData [cft_getfitteddata $materialId $ExperimentIndex $FunctionName]

   return $fittedData
}

#---------------------------------------------------------------
#  Function Name: AddCurveToGraph
#  Purpose:       Plotting new curves in existing graph depending upon the RMB Functionality
#  Arguments:     None
#  Notes:         Part of RMB Functionality
#
# --------------------------------------------------------------

proc AddCurveToGraph { graphObject materialId FunctionName ExperimentIndex iIndex eType iCIndex} {

   variable matid
   variable curveexist
   variable axisscale0
   variable axisscale1
   variable axisscale2
   variable axisscale3
   variable axisscale4
    
   if { [catch {set fittedData [GetCurveData $materialId $FunctionName [expr $iIndex-1]]}]} {
      ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
      return      
   }
   array set symbol [list 0 circle 1 square 2 diamond 3 plus 4 cross 5 splus 6 scross 7 triangle]
   set maxSymbols 8
   set iElemIndex 0
   set idxNum -1
   set numData [llength $fittedData]

   if {$ExperimentIndex == "0"} {set axisval $axisscale0
   } elseif {$ExperimentIndex == "1"} {set axisval $axisscale1
   } elseif {$ExperimentIndex == "2"} {set axisval $axisscale2
   } elseif {$ExperimentIndex == "3"} {set axisval $axisscale3
   } elseif {$ExperimentIndex == "4"} {set axisval $axisscale4
   } 
   
   for { set iCInd 0 } { $iCInd <= $numData } { incr iCInd 1 } {
       set axisData($iCInd) [lindex $fittedData $iCInd]
   }

   set axisData($iCIndex) [lindex $fittedData $iCIndex]
   set curExpId [ans_getvalue tbft,$matid,nexp]
   set data [fnametocolour $FunctionName]

   if { [string equal -nocase -length 4 $eType "creep"] } {
      array set curveme [GetColumnNames $matid $curExpId]
      set curveName(0) "[FuncNameToLabel $FunctionName]"
      set curveName(2) "[FuncNameToLabel $FunctionName]-$curveme($iCIndex)"
      set curveName(3) "[FuncNameToLabel $FunctionName]-$curveme($iCIndex)"
      set curveName(4) "[FuncNameToLabel $FunctionName]-$curveme($iCIndex)"
      set curveName(5) "[FuncNameToLabel $FunctionName]-$curveme($iCIndex)"
      set curveName(6) "[FuncNameToLabel $FunctionName]-$curveme($iCIndex)"
   } else {
      set curveName(2) "[FuncNameToLabel $FunctionName]"
      set curveName(3) "[FuncNameToLabel $FunctionName]"
      set curveName(4) "[FuncNameToLabel $FunctionName]"
      set curveName(5) "[FuncNameToLabel $FunctionName]"
      set curveName(6) "[FuncNameToLabel $FunctionName]"
   }

   #Simple Shear Specific Code
   if { ($numData == 4 && $iCIndex == 3) || ($numData == 5 && $iCIndex == 4) } {
      set curveName($iCIndex) "$curveName($iCIndex) Trans Stress Fitted Data"
   }
   
   if { [string equal -nocase -length 4 $FunctionName "hyfoam"] } {
       array set curveName [GetHyperFoamColumnNames $FunctionName $eType]      
   }

   if {[catch {$graphObject element create Curve($iCIndex,$FunctionName,$iIndex,$eType) -xdata $axisData(0) -ydata $axisData($iCIndex) \
                 -symbol $symbol($iCIndex) -color $data -scalesymbols true -label $curveName($iCIndex) -pixels 0.040i -linewidth 1 }] } {
      $graphObject element configure Curve($iCIndex,$FunctionName,$iIndex,$eType) -color "white"
      $graphObject element deactivate Curve($iCIndex,$FunctionName,$iIndex,$eType) 
      $graphObject element delete Curve($iCIndex,$FunctionName,$iIndex,$eType)

      set scurvename [lsearch -exact $curveexist "Curve($iCIndex,$FunctionName,$iIndex,$eType)"]
      set curveexist [lreplace $curveexist $scurvename $scurvename]
   } else {
      $graphObject element bind Curve($iCIndex,$FunctionName,$iIndex,$eType) <Button-2> \
      [list [namespace code  ShowElementContextMenu] \
      $graphObject Curve($iCIndex,$FunctionName,$iIndex,$eType) %x %y ]
      lappend curveexist Curve($iCIndex,$FunctionName,$iIndex,$eType)
      if {$axisval != "default"} {AddFittedDataToGraph $graphObject $axisval $ExperimentIndex $eType}
   }
}

proc PlotGraphToFile { gName } {
   variable parent
   set types {
      { {PNG Portable Network Graphics Format} {.png} }
      { {Encapsulate Postscript} {.eps} }
      { {JPEG File Interchange Format} {.jpg} }
      { {TIF Tagged Image File Format} {.tif} }
      { {Windows Bitmaps} {.bmp} }
   }

   set newfilename [::euidl::getSaveFile -parent $parent -filetypes $types]

   if [string match "" $newfilename] {
      return 
   }

   catch { destroy _curvefittingplot }
   image create photo _curvefittingplot
   $gName snap _curvefittingplot

   set filename $newfilename
   set fileDir [file dir $filename]
   set fileRoot [file root [file tail $filename]]
   set preFileExt [file ext $filename]
   regexp {\.(.*)} $preFileExt match fileExt
   
   if { ![info exists fileExt] } {
      tk_messageBox -parent $parent -title "Error" -icon error -message "Invalid Extension in File Name. Please type in complete filename with extension"
      return
   }

   if { $fileExt == "" } {
      tk_messageBox -parent $parent -title "Error" -icon error -message "Invalid Extension in File Name. Please type in complete filename with extension"
      return
   }

   # Provide options when saving to the different formats ???
   set format [string tolower $fileExt]
   switch -- $format {
      bmp {
         _curvefittingplot write $filename -format bmp
      }
      gif {
         _curvefittingplot write $filename -format gif
      }
      jpg -
      jpeg {
         _curvefittingplot write $filename -format jpeg
      }
      png {
         _curvefittingplot write $filename -format png
      }
      tif {
         _curvefittingplot write $filename -format tiff
      }
      eps {
         $gName postscript output $filename
      }
   }
}

proc ShowAllElements { gName } {
   set allElements [$gName element names]
   $gName element show $allElements
}

proc ShowLegend { gName } {
   $gName legend configure -hide false
}

proc HideLegend { gName } {
   $gName legend configure -hide true
}

proc ShowGrid { gName } {
   $gName grid configure -hide false
}

proc HideGrid { gName } {
   $gName grid configure -hide true
}

proc XAxisLogToggle { gName gidx} {
      for { set index 0 } { $index < 50 } { incr index 1 } {
          variable xAxisLogToggleValue$index
          variable yAxisLogToggleValue$index
      }
   if { $gidx == 0 } {
       $gName axis configure x -logscale $xAxisLogToggleValue0
   }
   if { $gidx == 1 } {
       $gName axis configure x -logscale $xAxisLogToggleValue1
   }
   if { $gidx == 2 } {
       $gName axis configure x -logscale $xAxisLogToggleValue2
   }
   if { $gidx == 3 } {
       $gName axis configure x -logscale $xAxisLogToggleValue3
   }
   if { $gidx == 4 } {
       $gName axis configure x -logscale $xAxisLogToggleValue4
   }
   if { $gidx == 5 } {
       $gName axis configure x -logscale $xAxisLogToggleValue5
   }
   if { $gidx == 6 } {
       $gName axis configure x -logscale $xAxisLogToggleValue6
   }
   if { $gidx == 7 } {
       $gName axis configure x -logscale $xAxisLogToggleValue7
   }
   if { $gidx == 8 } {
       $gName axis configure x -logscale $xAxisLogToggleValue8
   }
   if { $gidx == 9 } {
       $gName axis configure x -logscale $xAxisLogToggleValue9
   }
}

proc YAxisLogToggle { gName gidx} {
      for { set index 0 } { $index < 50 } { incr index 1 } {
          variable xAxisLogToggleValue$index
          variable yAxisLogToggleValue$index
      }
   if { $gidx == 0 } {
       $gName axis configure y -logscale $yAxisLogToggleValue0
   }
   if { $gidx == 1 } {
       $gName axis configure y -logscale $yAxisLogToggleValue1
   }
   if { $gidx == 2 } {
       $gName axis configure y -logscale $yAxisLogToggleValue2
   }
   if { $gidx == 3 } {
       $gName axis configure y -logscale $yAxisLogToggleValue3
   }
   if { $gidx == 4 } {
       $gName axis configure y -logscale $yAxisLogToggleValue4
   }
   if { $gidx == 5 } {
       $gName axis configure y -logscale $yAxisLogToggleValue5
   }
   if { $gidx == 6 } {
       $gName axis configure y -logscale $yAxisLogToggleValue6
   }
   if { $gidx == 7 } {
       $gName axis configure y -logscale $yAxisLogToggleValue7
   }
   if { $gidx == 8 } {
       $gName axis configure y -logscale $yAxisLogToggleValue8
   }
   if { $gidx == 9 } {
       $gName axis configure y -logscale $yAxisLogToggleValue9
   }
}

proc zoommode { gName } {
   global env
   global tcl_platform
   variable graphArray

   set graphArray($gName,cursor) [$gName cget -cursor]

#       blt::InitStack $gName
   if {[string match unix $tcl_platform(platform)]} { 
         $gName configure -cursor [list @[file join $env(EUIDL_DIR) gui \
               $::euidl::euidlArray(language) images magnify.xbm] \
                  [file join $env(EUIDL_DIR) gui \
                     $::euidl::euidlArray(language) images magnify.mask] \
                         #000000 #FFFFFF]
   } else {
         $gName configure -cursor @[file attributes [file join \
               $env(EUIDL_DIR) gui $::euidl::euidlArray(language) images \
                  magnify32x32.cur] -shortname]
   }
#       blt::ZoomStack $gName ButtonPress-1 Control-ButtonPress-3
   bind zoom-$gName <1> { 
      ::blt::SetZoomPoint %W %x %y 
   }

   bind zoom-$gName <ButtonRelease-1> \
         [list [namespace code zoomend] %W %x %y]

   ::blt::AddBindTag $gName zoom-$gName

}

proc zoomend { gName x y} {
   variable graphArray
    ::blt::SetZoomPoint $gName $x $y
    $gName configure -cursor $graphArray($gName,cursor)
    bind zoom-$gName <1> [list] 
    bind zoom-$gName <ButtonRelease-1> [list]
}

proc zoomfit { gName } {
   variable graphArray
    $gName axis configure x -min {} -max {}
    $gName axis configure y -min {} -max {}
    ::blt::InitStack $gName
}

proc zoomback { gName } {
   variable graphArray
    ::blt::ResetZoom $gName
}

# --------------------------------------------------------------
#  Function Name: ShowElementContextMenu
#  Purpose:       Shows Context Menu
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc ShowElementContextMenu  { graph element gX gY } {
      variable dataArr

      # Position of the pointer 
      set contextX [winfo pointerx .]
      set contextY [winfo pointery .]

      # The context menu will be rebuilt for the selected entities
      if [winfo exists ${graph}_${element}_contextmenu] {
         destroy ${graph}_${element}_contextmenu
      }

      set menu 0
      set cmnu [menu ${graph}_${element}_contextmenu \
            -tearoff no \
            -borderwidth 1]

      $cmnu add command \
               -command [list [namespace code ToggleGraphElement] $graph $element] \
               -underline 1 \
               -label [msgcat::mc "Hide"]

      $cmnu add command \
               -command [list [namespace code HideLinesGraphElement] $graph $element] \
               -underline 1 \
               -label [msgcat::mc "Markers Only"]

      $cmnu add command \
               -command [list [namespace code ShowLinesGraphElement] $graph $element] \
               -underline 1 \
               -label [msgcat::mc "Markers With Lines"]

      $cmnu add command \
               -command [list [namespace code TraceTypeForGraphElement ] $graph $element 1] \
               -underline 1 \
               -label [msgcat::mc "Trace Increasing Only Lines"]

      $cmnu add command \
               -command [list [namespace code TraceTypeForGraphElement ] $graph $element 2] \
               -underline 1 \
               -label [msgcat::mc "Trace Decreasing Only Lines"]

      $cmnu add command \
               -command [list [namespace code TraceTypeForGraphElement ] $graph $element 0] \
               -underline 1 \
               -label [msgcat::mc "Trace All Lines"]

      tk_popup $cmnu [expr $contextX - 5] [expr $contextY - 5]
}
   
# --------------------------------------------------------------
#  Function Name: GetHyperFoamColumnNames
#  Purpose:       Get the names of the Columns/columns
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc GetHyperFoamColumnNames { fname expname } {
    variable array ColumnNames

    set splitted [split $fname 'm']
    set forder [lindex $splitted 1]
    
    set ColumnNames(0) "Strain"
    set ColumnNames(1) "Lateral Strain"
    set ColumnNames(2) "Experimental Data"
    set ColumnNames(3) "Fitted Lateral Strain"
    set ColumnNames(4) "HyperFoam Order $forder"
    set ColumnNames(5) "HyperFoam Order $forder"
    set ColumnNames(6) "HyperFoam Order $forder"
    if { [string equal -nocase -length 4 $expname "biax"] || [string equal -nocase -length 4 $expname "shea"] } {
        set ColumnNames(1) "Lateral Strain"
        set ColumnNames(3) "Fitted Lateral Strain"
    }
    if { [string equal -nocase -length 4 $expname "volu"] } {
       set ColumnNames(0) "Vol Strain"
       set ColumnNames(1) "Experimental Data"
       set ColumnNames(2) "HyperFoam Order $forder"
    }
    if { [string equal -nocase -length 4 $expname "sshe"] } {
       set ColumnNames(0) "Strain"
       set ColumnNames(1) "Experimental Data Shear"
       set ColumnNames(2) "Experimental Data Trans"
       set ColumnNames(3) "HyperFoam Order $forder Shear"
       set ColumnNames(4) "HyperFoam Order $forder Trans"
    }
    return [array get ColumnNames]
}

# --------------------------------------------------------------
#  Function Name: GetColumnNames
#  Purpose:       Get the names of the Columns/columns
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc GetColumnNames { matId expId } {
    variable array ColumnNames

    set indexminus1 [expr $expId - 1]
    set numCols 7

    set ColumnNames(numcol) 7
    set ColumnNames(0) "Time "
    set ColumnNames(1) "Creep Strain Rate "
    set ColumnNames(2) "Temperature "
    set ColumnNames(3) "Fitted Data "
    set ColumnNames(4) "Fitted Data "
    set ColumnNames(5) "Fitted Data "
    set ColumnNames(6) "Fitted Data "

   #Load Experimental Data Attribs
   set numAtts [ans_getvalue tbft,$matId,expe,$expId,attnum]

   for { set iColIndex 0 } { $iColIndex < $numCols } { incr iColIndex 1 } {
       for { set iAttIndex 0 } { $iAttIndex < $numAtts } { incr iAttIndex 1 } {
          set attIndxPlus [expr $iAttIndex+1]
          set curAttName [ans_getvalue tbft,$matId,expe,$expId,attname,$attIndxPlus]
          if { $curAttName == [expr $iColIndex + 1] } {
              set attIndxPlus [expr $iAttIndex+1]
              set ColumnNames($iColIndex) [ans_getvalue tbft,$matId,expe,$expId,attvals,$attIndxPlus]
              set other [string trim $ColumnNames($iColIndex)]
              if { [string is space $other] } {
                  set ColumnNames($iColIndex) "FittedData"
              } else {
                    set ColumnNames($iColIndex) [ ExpandedCreepName $ColumnNames($iColIndex) ]
              }
              set ColumnNames(abbr,$iColIndex) $other
              set ColumnNames($iColIndex) "$ColumnNames($iColIndex) ID:$matId EXP:$expId"
          }
       }
    }

    return [array get ColumnNames]
}

# --------------------------------------------------------------
#  Function Name: ExpandedCreepName
#  Purpose:       Gives the Expanded Creep Name
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc ExpandedCreepName { givenName } {
    set givenName [string trim $givenName]

    set ExpCreepName(time) "Time"
    set ExpCreepName(dcre) "Creep Strain Rate"
    set ExpCreepName(dcreq) "Creep Strain Rate"
    set ExpCreepName(creq) "Creep Strain"
    set ExpCreepName(temp) "Temperature"
    set ExpCreepName(seqv) "Equivalent Stress"

    if  { [ info exists ExpCreepName($givenName)] } {
        return $ExpCreepName($givenName)
    } else {
        return "$givenName"
    }
}

# --------------------------------------------------------------
#  Function Name: PlotItemInLHSTree
#  Purpose:       Plot an item in the LHS Tree
#  Arguments:     None
#  Notes:         
#
# --------------------------------------------------------------
proc PlotItemInLHSTree {} {
   variable  DeleteCommandForLHSTree
   variable  DeleteParamsForLHSTree
   
   if { [string equal -nocase $DeleteCommandForLHSTree "return"] } {
      return
   }
   
   set params [split $DeleteParamsForLHSTree]
   set numParams [llength $DeleteParamsForLHSTree]
   if { $numParams != 2 } {
      return
   }
   
   if { [string equal -nocase $DeleteCommandForLHSTree "deletebyexpid"] } {
      LaunchGraphUtility [lindex $params 1]
   } else {
      if { [string equal -nocase $DeleteCommandForLHSTree "deletebyfuncid"] } {
         LaunchGraphUtility "all"
      }
   }

   #update tree
   #refreshL
   
   return
}


# --------------------------------------------------------------
#  Function Name: fnametocolour
#  Purpose:     return a colur depending upon functionname
#  Arguments:   fname is functionname, ......
#  Notes:       
#
# --------------------------------------------------------------

proc fnametocolour { fname } {

   set lcfname $fname
   set lcfname [string tolower $lcfname]

   #  hyogde1 orangered 
   #  hyogde2 red 
   #  hyogde3 blue 
   #  hymoon2 darkred 
   #  hymoon3 maroon 
   #  hymoon5 blueviolet 
   #  hymoon9 darkcyan 
   #  hyyeoh1 violet 
   #  hyyeoh2 brown 
   #  hyyeoh3 peru 
   #  hypoly1 purple 
   #  hypoly2 cadetblue 
   #  hypoly3 cornflowerblue 
   #  hyboyc  darkmagenta 
   #  hygent  goldenrod 
   #  hyneo   magenta 
   #  hyblat1 navy 
   #  hyblat  firebrick 
   #  hyfoam1 seagreen 
   #  hyfoam2 mediumvioletred 
   #  hyfoam3 indianred
   #  plchab1 violet
   #  plchab2 indigo
   #  plchab3 blue
   #  crshar  chocolate
   #  crthar  darkgoldenrod 
   #  crgexp  darkolivegreen 
   #  crggra  darkviolet
   #  crgbla  gold 
   #  crmsha  lightcoral 
   #  crmtha  red
   #  crgtha  maroon
   #  crggar  darkorchid 
   #  crexpo  darkblue
   #  crnort  forestgreen 
   #  crpsth  darkorange 
   #  crpsrt  mediumblue
   #  default red 

   set data #00008b
   switch -exact -- $lcfname {
      hyogde1 {set data   #450000 }
      hyogde2 {set data   #ff0000 }
      hyogde3 {set data   #0000ff }
      hymoon2 {set data   #8b0000 }
      hymoon3 {set data   #b03060 }
      hymoon5 {set data   #8a2bd2 }
      hymoon9 {set data   #00ffff }
      hyyeoh1 {set data   #ee82ee }
      hyyeoh2 {set data   #a52a2a }
      hyyeoh3 {set data   #cd853e }
      hypoly1 {set data   #a020f0 }
      hypoly2 {set data   #5f9ea0 }
      hypoly3 {set data   #6495ed }
      hyboyc  {set data   #8b008b }
      hygent  {set data   #daa520 }
      hyneo   {set data   #ff00ff }
      hyblat1 {set data   #000080 }
      hyblat  {set data   #b22222 }
      hyfoam1 {set data   #2e8b57 }
      hyfoam2 {set data   #c71585 }
      hyfoam3 {set data   #cd5c5c }
      crshar  {set data   #ff7f24 }
      crthar  {set data   #b8860b }
      crgexp  {set data   #556b2f }
      crggra  {set data   #9400d3 }
      crgbla  {set data   #ffd700 }
      crmsha  {set data   #f08080 }
      crmtha  {set data   #ff0000 }
      crgtha  {set data   #b03060 }
      crggar  {set data   #9932cc }
      crexpo  {set data   #00008b }
      crnort  {set data   #228b22 }
      crpsth  {set data   #ff8c00 }
      crpsrt  {set data   #0000cd }
      plchab1 {set data   #450000 }
      plchab2 {set data   #ff0000 }
      plchab3 {set data   #0000ff }
      plchab4 {set data   #8b0000 }
      plchab5 {set data   #b03060 }
      default {set data   #ff0000 }
   }            
   return $data
}

# --------------------------------------------------------------
#  Function Name: AddFittedDataToGraph
#  Purpose:  To convert the X-axis scale via RMB functionality and replotting the curves
#  Arguments:   graphObject is graph object name, numpoints is number of points to divide the given X-axis range in
#               ExperimentIndex is experiment number, eType is Experiment type (unia, biax .. )
#  Notes:       
#
# --------------------------------------------------------------


proc AddFittedDataToGraph {graphObject numpoints ExperimentIndex eType} {

  variable curveexist
  variable matid
  variable axisscale0
  variable axisscale1
  variable axisscale2
  variable axisscale3
  variable axisscale4
  variable lowerlimit
  variable upperlimit

  set iErrorFlag 1
  set axisscale$ExperimentIndex $numpoints
  set scurveread ""
  set numitems [llength $curveexist]
  
  if {$numitems == "0"} {
     ans_senderror 2 "Please Select/Display a curve"
     return  
  }
  for {set i 0} {$i < $numitems} {incr i 1} {
    set dataname [lindex $curveexist $i]
    set dataname [split $dataname ,]
    set dataname1 [lindex $dataname 3]
    set dataname1 [split $dataname1 )]
    set data [lindex $dataname1 0]

    if {$data == $eType} { lappend scurveread [lindex $curveexist $i] }
  }

  set FunctionName [lindex $dataname 1]
  set numitems [llength $scurveread]

  for {set i 0} {$i < $numitems} {incr i } {
    set scurvename [lsearch -exact $curveexist [lindex $scurveread $i]]
    set curveexist [lreplace $curveexist $scurvename $scurvename]
    $graphObject element configure [lindex $scurveread $i] -color "white"
    $graphObject element deactivate [lindex $scurveread $i] 
    $graphObject element delete [lindex $scurveread $i]
  }    

  for {set i 0} {$i < $numitems} {incr i } {

    set curveplot [lindex $scurveread $i]
    set curveplot [split $curveplot ,]
    set iExpId [lindex $curveplot 2]
    set fname [lindex $curveplot 1]
    set temp [lindex $curveplot 0]
    set temp [split $temp ( ]
    set iCIndex [lindex $temp 1] 
    set iIndex [lindex $curveplot 2]
    limitsdecide $numpoints $eType $fname $ExperimentIndex $iCIndex $iIndex $FunctionName
    set iFlag [GetFittedDataAtAnyRange $lowerlimit($ExperimentIndex) $upperlimit($ExperimentIndex) $numpoints $eType $fname $graphObject $iExpId $iCIndex $iIndex]
    if { $iFlag == 0 } {
        set iErrorFlag 0
    }
    lappend curveexist [lindex $scurveread $i]
  }

  if { $iErrorFlag == 0 } {
         ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
  }
  return
}

# --------------------------------------------------------------
#  Function Name: GetFittedDataAtAnyRange
#  Purpose:    Calculates points of curve for the given range as per selected in RMB functionality and plots the graph
#  Arguments: lowerlimit is lowerlimit of the curve, upperlimit is upperlimit of the curve, numpoints is number of points on the curve
#             eType is Experiment type (unia, biax .. ), fname is function name, 
#  Notes:       
#
# --------------------------------------------------------------

proc GetFittedDataAtAnyRange {lowerlimit upperlimit numpoints eType fname graphObject ExperimentIndex iCIndex iIndex} {

  variable matid
  variable myfittedata
  variable NLOpts
  variable iErrorFlag
    
  set iErrorFlag 1
  set axisdata(0) ""
  set axisdata(2) ""
  set xval ""
  set yval ""
  set data [fnametocolour $fname]
  array set symbol [list 0 circle 1 square 2 diamond 3 plus 4 cross 5 splus 6 scross 7 triangle]

  if { [string equal -nocase -length 4 $eType "creep"] } {
    array set curveme [GetColumnNames $matid $iIndex]
    set curveName(0) "[FuncNameToLabel $fname]"
    set curveName(2) "[FuncNameToLabel $fname]-$curveme($iCIndex)"
    set curveName(3) "[FuncNameToLabel $fname]-$curveme($iCIndex)"
    set curveName(4) "[FuncNameToLabel $fname]-$curveme($iCIndex)"
    set curveName(5) "[FuncNameToLabel $fname]-$curveme($iCIndex)"
    set curveName(6) "[FuncNameToLabel $fname]-$curveme($iCIndex)"
  } else {
    set curveName(2) "[FuncNameToLabel $fname]"
    set curveName(3) "[FuncNameToLabel $fname]"
    set curveName(4) "[FuncNameToLabel $fname]"
    set curveName(5) "[FuncNameToLabel $fname]"
    set curveName(6) "[FuncNameToLabel $fname]"
   }
   
   if { [string equal -nocase -length 4 $eType "sshea"] } {
       set curveName(3) "[FuncNameToLabel $fname] Trans Stress Fitted Data"
   }

   if {$numpoints != "default" } { set incrval [expr ($upperlimit-$lowerlimit)/($numpoints+0.0)] }
   set curvenew Curve($iCIndex,$fname,$iIndex,$eType)
   
   #Get Reference Temperature for this experiment
   #set isTempDepOn [ans_getvalue tbft,$matid,,$fname,tdep]
   if { $NLOpts(6) ==  1 } {
      set eTRef [GetTempOfExperiment $matid $ExperimentIndex]
      #Set TREF
      set commandName [FuncNameToCommand $fname]
      ans_sendcommand tbft,set,$matid,$commandName,tref,$eTRef
   }
   
   if {    $eType == "unia" || $eType == "biax" || $eType == "shea" || $eType == "sshe"  \
        || $eType == "volu" || $eType == "sdec" || $eType == "bdec" || $eType == "creep" } {
     if {$numpoints != "default" } {
           if { ![string equal -nocase -length 4 $eType "creep"] } {
               for {set i $lowerlimit} {$i <= $upperlimit} { set i [expr $i+$incrval] } {
               
                   # X Values
                   set xval $i
                   lappend axisdata(0) $xval

                   if { ! [string equal -nocase -length 4 $eType "sshe"] } {
                       #YValues
                       set yval 0.0
                       if { [catch { set yval [ans_getvalue TBFT,$matid,expe,$eType,func,$fname,$i] }] } {
                          set iErrorFlag 0
                       }
                       lappend axisdata(2) $yval
                   } else {
                       # iCIndex = 2 is the first set of data. = 3 refers to tranverse stress
                       if {  $iCIndex == 2 } {
                           # Simple Shear Case
                           #YValues
                           set yval 0.0
                           set etypesub "sshea-shear"
                           if { [catch { set yval [ans_getvalue TBFT,$matid,expe,$etypesub,func,$fname,$i] }] } {
                              set iErrorFlag 0
                           }
                           lappend axisdata(2) $yval
                       } else {
                           set yval 0.0
                           set etypesub "sshea-transverse"
                           if { [catch { set yval [ans_getvalue TBFT,$matid,expe,$etypesub,func,$fname,$i] }] } {
                              set iErrorFlag 0
                           }
                           lappend axisdata(2) $yval
                       }
                    }
                }
           } else {
                set ReturnList [GetCreepFittedDataPoints  $matid $fname $ExperimentIndex $lowerlimit $upperlimit $numpoints]
                set axisdata(0) [lindex $ReturnList 0]
                set iSize [llength $ReturnList]
                set axisdata(2) [lindex $ReturnList [expr $iSize-1]]
           }
     } else {
        if { [catch {set fittedData [GetCurveData $matid $fname [expr $iIndex-1]]}] } {
           ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
           return      
        }
        set axisdata(0) [lindex $fittedData 0]
        set axisdata(2) [lindex $fittedData $iCIndex]
     }
   
     $graphObject element create Curve($iCIndex,$fname,$iIndex,$eType) -xdata $axisdata(0) -ydata $axisdata(2) -symbol $symbol($iCIndex) -color $data \
         -scalesymbols true -label $curveName($iCIndex) -pixels 0.040i -linewidth 1 
   }

   return $iErrorFlag           
}


# --------------------------------------------------------------
#  Function Name:  limitsbox
#  Purpose:   To Display a dialog box with a entry widget in order to accept X-Axis Maximum/Minimum value depending upon requirement  
#  Arguments:  graph is graph object name, limit is value to be changed i.e lowerlimit or upperlimit
#               ExperimentIndex is experiment number, eType is Experiment type (unia, biax .. )
#  Notes:       
#
# --------------------------------------------------------------


proc limitsbox {graph limit ExperimentIndex eType} {

  variable graphParent
  variable parent
  variable currentlimit
  variable cuexpid
  variable lowerlimit
  variable upperlimit
  variable type
  variable ggraph   
  variable axisscale0
  variable axisscale1
  variable axisscale2
  variable axisscale3
  variable axisscale4
  variable axisval

  set currentlimit $limit
  set cuexpid $ExperimentIndex
  set type $eType
  set ggraph $graph

  if {$ExperimentIndex == "0"} {set axisval $axisscale0
  } elseif {$ExperimentIndex == "1"} {set axisval $axisscale1
  } elseif {$ExperimentIndex == "2"} {set axisval $axisscale2
  } elseif {$ExperimentIndex == "3"} {set axisval $axisscale3
  } elseif {$ExperimentIndex == "4"} {set axisval $axisscale4
  } 

  if {$limit == "lowerlimit"} {
     set limit1 "X-Axis Minimum Value" 
  } else {
     set limit1 "X-Axis Maximum Value" 
  }

  if {[winfo exists .dlglimits]} {
    destroy .dlglimits
  }

  iwidgets::dialog .dlglimits

  .dlglimits buttonconfigure OK -command {
  
     set limit ${::euidl::material::CurveFit::currentlimit}
     set ExperimentIndex ${::euidl::material::CurveFit::cuexpid}
     set eType ${::euidl::material::CurveFit::type}
     set graph ${::euidl::material::CurveFit::ggraph}
     set axisval ${::euidl::material::CurveFit::axisval}

     if {$limit == "lowerlimit"} {
     if {($eType == "unia" || $eType == "biax" || $eType == "shea" || $eType == "sshe") && $newlimit <= "-1"} {
        ans_senderror 2 "Minimum Value must be greater than -1"
        return        
     } elseif {($eType == "volu" || $eType == "sdec" || $eType == "bdec") && $newlimit < 0} {
        ans_senderror 2 "Minimum Value must be greater than 0"
        return       
     } elseif {$newlimit >= $::euidl::material::CurveFit::upperlimit($ExperimentIndex)} {
        ans_senderror 2 "Minimum Value must be less than Maximum Value"
        return
     } else {
                set ::euidl::material::CurveFit::lowerlimit($ExperimentIndex) $newlimit
         }
     } else {
         if {$eType == "volu" && $newlimit>1} {
             ans_senderror 2 "Maximum Value can't be greater than 1"
             return
         } elseif {$newlimit <= $::euidl::material::CurveFit::lowerlimit($ExperimentIndex)} {
             ans_senderror 2 "Maximum Value must be greater than Minimum Value"
             return
         } else {
             set ::euidl::material::CurveFit::upperlimit($ExperimentIndex) $newlimit
         }
     }
  
     .dlglimits deactivate 1

     if {$axisval == "default"} {
        set axisval 100
        set ::euidl::material::CurveFit::axisscale$ExperimentIndex 100
     }

     [namespace code ::euidl::material::CurveFit::AddFittedDataToGraph] $graph $axisval $ExperimentIndex $eType

     unset ::euidl::material::CurveFit::cuexpid
     unset ::euidl::material::CurveFit::currentlimit 
     unset ::euidl::material::CurveFit::type
     unset ::euidl::material::CurveFit::ggraph
     unset ::euidl::material::CurveFit::axisval
  }

  .dlglimits buttonconfigure Cancel -command {
     .dlglimits deactivate 0
  }

  .dlglimits hide Apply
  .dlglimits hide Help
  .dlglimits configure -title "Enter New Value"
  .dlglimits center $graph
  .dlglimits activate
  set win [.dlglimits childsite]
  label $win.ex -text "Enter new $limit1"
  entry $win.e1 -width 12 -textvariable newlimit
  pack $win.ex -side left -padx 4 -pady 4
  pack $win.e1 -side left -after $win.ex

}

# --------------------------------------------------------------
#  Function Name:  limitsdecide
#  Purpose:   To determine limits for each curve  
#  Arguments:  graph is graph object name, limit is value to be changed i.e lowerlimit or upperlimit
#               ExperimentIndex is experiment number, eType is Experiment type (unia, biax .. )
#  Notes:       
#
# --------------------------------------------------------------

proc limitsdecide {numpoints eType fname ExperimentIndex iCIndex iIndex FunctionName} {
 
  variable matid
  variable axisscale0
  variable axisscale1
  variable axisscale2
  variable axisscale3
  variable axisscale4
  variable lowerlimit
  variable upperlimit

  if {$numpoints == "default" } {
    if { [catch {set fittedData [GetCurveData $matid $FunctionName [expr $iIndex-1]] }] } {
       ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
       return      
    }
    set axisData [lindex $fittedData 0]
    set testlen [llength $axisData]
    set testlower [lindex $axisData 0]
    set testupper [lindex $axisData [expr $testlen-1]]
    set lowerlimit($ExperimentIndex) $testlower
    set upperlimit($ExperimentIndex) $testupper    
  }

  if {$numpoints != "default" } {

    if { [catch {set fittedData [GetCurveData $matid $FunctionName [expr $iIndex-1]]}]  } {
       ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
       return      
    }
    set axisData [lindex $fittedData 0]
    set testlen [llength $axisData]
    set testlower [lindex $axisData 0]
    set testupper [lindex $axisData [expr $testlen-1]]
    if {$eType == "unia" || $eType == "biax" || $eType == "shea" || $eType == "sshe" } {
       if {$lowerlimit($ExperimentIndex) == $testlower} {
          if {$testlower > "0" } {
             set lowerlimit($ExperimentIndex) 0
          }
       }

       if {$upperlimit($ExperimentIndex) == $testupper} {
          if {$testupper < "2" } {
             set upperlimit($ExperimentIndex) 2
          } 
       }
    }

    if {$eType == "volu"} {
       if {$lowerlimit($ExperimentIndex) == $testlower} {set lowerlimit($ExperimentIndex) 0.5}
       if {$upperlimit($ExperimentIndex) == $testupper} {set upperlimit($ExperimentIndex) 1}
    }

    if {$eType == "sdec" || $eType == "bdec" } {
       if {$lowerlimit($ExperimentIndex) == $testlower} {
          if {$testlower < "0" } {set lowerlimit($ExperimentIndex) $testlower} else {set lowerlimit($ExperimentIndex) 0}
       }

       if {$upperlimit($ExperimentIndex) == $testupper} {
          if {$testupper > "1000" } {set upperlimit($ExperimentIndex) $testupper} else {set upperlimit($ExperimentIndex) 1000}
       }
    }
  }
}

# --------------------------------------------------------------
#  Function Name:  GetCreepColumnNames
#  Purpose:    Get the column names and values for Creep Experiment
#  Arguments:  
#  Notes:       
#
# --------------------------------------------------------------
proc GetCreepColumnNames { MaterialId FunctionName ExperimentIndex } {
   variable ColumnNames
   set ColumnNames [list]

   #Get the Column Names
   set iNumAtts [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,attnum]
   set iNumCols [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,numcol,1]
   
   for { set iColIndex 0 } { $iColIndex < $iNumCols } { incr iColIndex 1 } {
       for { set iAttIndex 0 } { $iAttIndex < $iNumAtts } { incr iAttIndex 1 } {
          set attIndxPlus [expr $iAttIndex+1]
          set curAttName [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,attname,$attIndxPlus]
          set cLen [string length $curAttName]
          if { $cLen > 4 } {
              set curAttName [string range $curAttName 0 3]
          }
          set curAttName [string tolower $curAttName]
          set curAttVal "undef"
          set curAttVal  [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,attvals,$attIndxPlus]
          set cLen [string length $curAttVal]
          if { $cLen > 4 } {
              set curAttVal [string range $curAttVal 0 3]
          }
          set curAttVal [string tolower $curAttVal]
          if { $curAttName == [expr $iColIndex + 1] } {
            set curAttVal [string trimright $curAttVal]
            lappend ColumnNames $curAttVal
          }
       }
   }

   return $ColumnNames
}

# --------------------------------------------------------------
#  Function Name:  GetRequiredCreepColumns
#  Purpose:        Get the column names and values necessary for Creep Experiment Evaluation
#  Arguments:  
#  Notes:       
#
# --------------------------------------------------------------
proc GetRequiredCreepColumns { FunctionName } {
    variable ReqColNames
    set ColNames(crshar) [list creq dcreq time seqv temp]
    set ColNames(crthar) [list      dcreq time seqv temp]
    set ColNames(crgexp) [list      dcreq time seqv temp]
    set ColNames(crggra) [list      dcreq time seqv temp]
    set ColNames(crgbla) [list      dcreq time seqv     ]
    set ColNames(crmtha) [list creq       time seqv temp]
    set ColNames(crmsha) [list creq dcreq      seqv     ]
    set ColNames(crggar) [list      dcreq      seqv temp]
    set ColNames(crexpo) [list      dcreq      seqv temp]
    set ColNames(crnort) [list      dcreq      seqv temp]
    set ColNames(crpsth) [list creq       time seqv temp]
    set ColNames(crpsrp) [list      dcreq time seqv     ]
    set ColNames(crgtha) [list creq       time seqv temp]    
    
    set ReqColNames $ColNames($FunctionName)
    return $ReqColNames
}

# --------------------------------------------------------------
#  Function Name:  GetCreepFittedDataPoints
#  Purpose:        Get the Creep Data Fitted Points
#  Arguments:  
#  Notes:       
#
# --------------------------------------------------------------
proc GetCreepFittedDataPoints { MaterialId FunctionName ExperimentIndex MinVal MaxVal NumValues} {
    variable TotalList
    set iErrorStatus 1
    set ReqColNames [GetRequiredCreepColumns $FunctionName]
    
    set SuppliedColNames [GetCreepColumnNames $MaterialId $FunctionName $ExperimentIndex]
    set iNumSuppliedCols [llength $SuppliedColNames]
    
    set XColName [lindex $SuppliedColNames 0]
    set XColName [string trim $XColName]
    set iNumReqCols [llength $ReqColNames]
    
    set AttValList [list]
    for { set iColIndex 0 } { $iColIndex < $iNumReqCols } { incr iColIndex 1 } {
        set CurColName [lindex $ReqColNames $iColIndex]
        set CurColPos [lsearch $SuppliedColNames "$CurColName    "]
        set CurColVal 0
        if { $CurColPos > -1 } {
            #Get the Value in Row 0
            set CurColVal [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,data,1,[expr $CurColPos+1]]
        } else {
            #Get the Attribute
            set iNumAttribs [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,attnum]
            for { set iAttIndex 0 } { $iAttIndex < $iNumAttribs} { incr iAttIndex 1 } {
                set attIPlus [expr $iAttIndex+1]
                set attName [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,attname,$attIPlus]
                if { [string equal -nocase -length 4 $attName $CurColName] } {
                   set CurColVal [ans_getvalue tbft,$MaterialId,expe,$ExperimentIndex,attvald,$attIPlus]
                }
            }        
        }
        lappend AttValList $CurColVal
    }
    
    set iSeqvPos [lsearch $ReqColNames "seqv"]
    set iCreqPos [lsearch $ReqColNames "creq"]
    set iTimePos [lsearch $ReqColNames "time"]
    set iTempPos [lsearch $ReqColNames "temp"]
    
    set TotalList [list]
    set XValList [list]    
    set YValList [list]
    for { set iPtIndex 0 } { $iPtIndex < $NumValues } { incr iPtIndex 1 } {
        
        #Calculate X Value
        set dXValue 0
        set dXValue [expr $MinVal+(($MaxVal-$MinVal)*$iPtIndex/$NumValues)]
        lappend XValList $dXValue
        
        #Initialize
        set ParVal(seqv) 0
        set ParVal(creq) 0
        set ParVal(time) 0  
        set ParVal(temp) 0
        
        #Estimate Necessary Input
        if { $iSeqvPos > -1 } {
            set ParVal(seqv) [lindex $AttValList $iSeqvPos]
        }
        if { $iCreqPos > -1 } {
            set ParVal(creq) [lindex $AttValList $iCreqPos]
        }
        if { $iTimePos > -1 } {
            set ParVal(time) [lindex $AttValList $iTimePos]   
        }
        if { $iTempPos > -1 } {
            set ParVal(temp) [lindex $AttValList $iTempPos]     
        }        
        set ParVal($XColName) $dXValue
        
        #Calculate Y Value
        set dYValue 0
        if { [catch { set dYValue [ans_getvalue tbft,$MaterialId,expe,creep,func,$FunctionName,$ParVal(time),$ParVal(seqv),$ParVal(temp),$ParVal(creq)]}] } {
            set iErrorStatus 0
        }
        lappend YValList $dYValue
    }
    lappend TotalList $XValList
    
    for { set iColIndex 1 } { $iColIndex < $iNumReqCols } { incr iColIndex 1 } {
        set CurList [list]
        for { set iPtIndex 0 } { $iPtIndex < $NumValues } { incr iPtIndex 1 } {
            set CurColName [lindex $ReqColNames $iColIndex]
            set CurColVal 0.0
            set CurColVal [lindex AttValList $iColIndex]
            lappend CurList $CurColVal
        }
        lappend TotalList $CurList
    }
    
    if { $iErrorStatus == 0 } {
         ans_senderror 2 "Error while extracting curvefitting data necessary for plot \n"
    }
    lappend TotalList $YValList
    return $TotalList
}

}



