
proc DefaultStartValues { } {
 global GiDProjectDir
 global GiDProjectName

 set GiDProjectDir ""
 set GiDProjectName "" 
  
 global taskName 
 set taskName [GiD_AccessValue get genData TaskName]
 resetProblemDataVariables   

}

proc resetProblemDataVariables { } {
  GiD_AccessValue set gendata "UniqueVolumeList" "#N# 1 -1"
  GiD_AccessValue set gendata "UniqueSurfaceList" "#N# 1 -1"
  GiD_AccessValue set gendata "Draw_Each_Iteration" "#N# 1 -1"
  GiD_AccessValue set gendata "VolumeList" "#N# 1 -1"
  GiD_AccessValue set gendata "SurfaceList" "#N# 1 -1"
  GiD_AccessValue set gendata "AttributeList" "#N# 1 -1"
  GiD_AccessValue set gendata "MinMaxList" "#N# 1 -1"
  GiD_AccessValue set gendata "Item_At" "#N# 1 -1"
  GiD_AccessValue set gendata "CheckName" "#N# 1 -1"
  GiD_AccessValue set gendata "MonitorName" "#N# 1 -1"
  GiD_AccessValue set gendata "UniqueMonitorName" "#N# 1 -1"
  GiD_AccessValue set gendata "UniqueContactName" "#N# 1 Contact"
  GiD_AccessValue set gendata "UniqueSelectionName" "#N# 1 none"
  GiD_AccessValue set gendata "LineNumForLineForce" "#N# 1 0"
} 

 proc Prenes_do_bas { x } {
# zjisti u elementu jestli je quadratickej a prenese to do promenne v *.bas !!!
# *Set var aaa=tcl(ZjistiQuadratic *ElemsNum)

set cond [GiD_Info conditions "Non_Quadratic_Surface" mesh $x]
if [ string match -nocase "*1*" $cond ] {
return [expr {1}]
} else {
return [expr {0}]
}
  }
  

proc MyZapisElementGroupInactiveReset { } {
 array unset ::ElementGroupInactiveVypsano
}

proc MyZapisElementGroupInactiveMaterialNumberReset { } {
 array unset ::ElementGroupInactiveMaterialNumber
}   

proc MyZapisElementGroupMaterialNumber { material_name  material_number } {
  set ::ElementGroupInactiveMaterialNumber($material_name) $material_number
  #WarnWinText "Save $material_name $material_number"
  return ""
}

proc MyZapisElementGroupMaterialNumberGetNumber { material_name } {
  set result ""
  #WarnWinText "//MyZapisElementGroupMaterialNumberGetNumber = $material_name  =  $::ElementGroupInactiveMaterialNumber($material_name)"
  #WarnWinText "$::ElementGroupInactiveMaterialNumber($material_name)"
  #set array b ::ElementGroupInactiveMaterialNumber
  
  #set a [::ElementGroupInactiveMaterialNumber($material_name)]
  #WarnWinText "//$material_name = ::ElementGroupInactiveMaterialNumber($material_name) - $a "
  if { [info exists ::ElementGroupInactiveMaterialNumber($material_name)] } {
     #set a ::ElementGroupInactiveMaterialNumber($material_name)
     #append result "// return exists $material_name,$::ElementGroupInactiveMaterialNumber($material_name)"
     return $::ElementGroupInactiveMaterialNumber($material_name)
  }
  return $result
}

proc ZJ_vypis_intervaly { } {
     set n_intv [lindex [GiD_Info IntvData NUM] 1]
     WarnWinText "Summary of Material Activities in intervals ($n_intv)" 
     WarnWinText "===================================="     
     for { set i 1 } { $i <= $n_intv } { set i [expr $i + 1] } {
 	     GiD_IntervalData set $i
       set active [GiD_AccessValue get IntvData $i Interval_Is_Active]
       set zap [GiD_AccessValue get IntvData $i Show_Material_Activity]
       if {$active==1} {
       WarnWinText "Interval $i (active)"
       #WarnWinText "-------------------"
       } else {
       WarnWinText "Interval $i (not active)"
       #WarnWinText "-------------------------"
       } 

       #WarnWinText "Interval_Is_Active = $active "
       #WarnWinText "Material_Activity = $zap " 
       if {$zap==1} {
           set values [lrange [GiD_AccessValue get intvdata Material_Activity_Step] 2 end]
           #WarnWinText "//values = $values "
           foreach {old_material_name2 new_material_name2 reset2 before_step2} $values {
           
          set idealisation_old [GiD_AccessValue get materials $old_material_name2 "Idealisation"]
          set idealisation_new [GiD_AccessValue get materials $new_material_name2 "Idealisation"]
          #WarnWinText "idealisation_old = $idealisation_old"
          #WarnWinText "idealisation_new = $idealisation_new"
           WarnWinText "    $old_material_name2 ($idealisation_old) -> $new_material_name2 ($idealisation_new)"

          if {$idealisation_old == $idealisation_new} { } else {
            WarnWinText "When replacing materials it is important that same element and geometry type is used in both materials."
            #WarnWinText "Warning: Interval number: $interval_number, Old material: $old_material_name (idealisation $idealisation_old), New material: $new_material_name2 (idealisation $idealisation_new)"
          } 
       
           }
       } else {
         WarnWinText "Material_Activity_Step not used." 
       }
       
       WarnWinText "------------------------------------"
     } 
     WarnWinText "====================================" 

}
    
proc TK_Material_Activity_Show_All { event args } {
 switch $event {
 INIT {
 #WarnWinText "init "
  # do nothing here
  return ""
 }
 DEPEND {
 #WarnWinText "depend "
  # do nothing here
  return ""
 } 
 CLOSE {
 #WarnWinText "close "
  # do nothing here
  return ""
 }  
 SYNC {
 #WarnWinText "sync "
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
  
       set vypis [DWLocalGetValue $GDN $STRUCT Report_Summary_of_Material_Activities_In_Intervals]
       if { $vypis == 1 } {
       ZJ_vypis_intervaly
       set on [DWLocalSetValue $GDN $STRUCT Report_Summary_of_Material_Activities_In_Intervals 0]
       }    
    }
  }
}         

proc MyZapisElementGroupInactiveCheck { } {
     
     set n_intv [lindex [GiD_Info IntvData NUM] 1]


# foreach elemtype [lrange [GiD_Info Mesh] 1 end] {
#     foreach elem [GiD_Info mesh Elements $elemtype -sublist] {
#         set matnumused [lindex $elem end]
#         if { $matnumused > 0 } {
#           incr matnumused -1
#           set usetmatnum($matnumused) 1
#           WarnWinText "matnumused = $matnumused "
#         }
#     }
#  }
  
  
 foreach idvol [GiD_Geometry list volume 1:end] {
                set txt [GiD_Info list_entities volumes $idvol]
                regexp {material: ([0-9]+)\n} $txt dummy matnumused
                 if { $matnumused > 0 } {
                   #incr matnumused -1
                   set usetmatnum($matnumused) 1
                   #WarnWinText "matnumused = $matnumused "
                 }
    }
    
  foreach idsur [GiD_Geometry list surface 1:end] {
                set txt [GiD_Info list_entities -more surface $idsur]
                regexp {material: ([0-9]+)\n} $txt dummy matnumused
                 if { $matnumused > 0 } {
                   #incr matnumused -1
                   set usetmatnum($matnumused) 1
                   #WarnWinText "matnumused = $matnumused "
                 }
    }  
  
  
  
  
  


  
     for { set i 1 } { $i <= $n_intv } { set i [expr $i + 1] } {
 	     GiD_IntervalData set $i
       set zap [GiD_AccessValue get IntvData $i Show_Material_Activity]
       if {$zap==1} {
           set values [lrange [GiD_AccessValue get intvdata Material_Activity_Step] 2 end]
#           //WarnWinText "//values = $values "
           foreach {old_material_name2 new_material_name2 reset2 before_step2} $values {
           
           #WarnWinText "**$old_material_name2** -> **$new_material_name2**"
           
              set old_material_used 0
              set mat_id [expr [lsearch [GiD_Info materials] $old_material_name2]+1]
             foreach matnum [lsort -integer [array names usetmatnum]] {
                   if {$mat_id==$matnum} { 
                   set old_material_used 1  
                   #WarnWinText "// old_material_name2=matnum=$matnum" 
                   } else { 
                   #WarnWinText "// mat_id=$mat_id old_material_name2=$old_material_name2 matnum=$matnum" 
                   }
                
                }
            if {$old_material_used==0} {
            WarnWinText "Interval: $i, Material_Activity_Step, $old_material_name2 ($matnum) is not the original one"
            }
           
               if {$old_material_name2!=""} {
                   set mat_id [expr [lsearch [GiD_Info materials] $old_material_name2]+1]
                   #WarnWinText "//mat $old_material_name2 -> mat_id = $mat_id "
                   if {$mat_id==0} {
                      WarnWinText "Interval: $i, Material_Activity_Step, material $old_material_name2 does not exist"
                      }           
               }
     
               if {$new_material_name2!=""} {
                   set mat_id [expr [lsearch [GiD_Info materials] $new_material_name2]+1]
                   #WarnWinText "//mat $new_material_name2 -> mat_id = $mat_id "
                   if {$mat_id==0} {
                      WarnWinText "Interval: $i, Material_Activity_Step, material $new_material_name2 does not exist"
                      }               
               }             
           }
       }
     }


}
  
proc MyZapisElementGroupInactive { interval_number  old_material_name  group_id interval_step_id} {
    set result ""
    GiD_IntervalData set $interval_number
    set values [lrange [GiD_AccessValue get intvdata Material_Activity_Step] 2 end]
    foreach {old_material_name2 new_material_name2 reset2 before_step2} $values {
      if {$before_step2 == $interval_step_id} {
      
      #append result "projizdim radek $old_material_name2 $new_material_name2 $group_id $interval_step_id\n"
      if {$old_material_name==$old_material_name2} {
        if { [info exists ::ElementGroupInactiveVypsano($interval_number,$old_material_name,$group_id,$interval_step_id)] } {
        #append result "// return exists $interval_number,$old_material_name,$group_id,$interval_step_id "
        return $result 
        
        #$result
        } else {
          
          set prototype [GiD_AccessValue get materials $old_material_name "Material_Prototype"]
          set ovyztuz1 [string equal $prototype "CC1DElastIsotropic"]
          set ovyztuz2 [string equal $prototype "CCReinforcement"]
          set ovyztuz3 [string equal $prototype "CCCyclingReinforcement"]
          set ovyztuz4 [string equal $prototype "CCReinforcementWithTempDepProperties"]
          set ovyztuz5 [string equal $prototype "CCSteelDRC"]
          
          if {$ovyztuz1 == 1 || $ovyztuz2 == 1 || $ovyztuz3 == 1 || $ovyztuz4 == 1 || $ovyztuz5 == 1} {
            #tk_messageBox -icon error -message "Error: function Material Activity for interval do not work for Reinforcement Materials. Please use Condition Reinforcement_Inactivity_for_Line" -icon warning -type ok
            Atena_MessageBoxOk "ATENA-GiD Warning" "Error: function Material Activity for interval do not work for Reinforcement Materials. Please use Condition Reinforcement_Inactivity_for_Line" error 
          }
        
          append result "\nELEMENT GROUP ID $group_id INACTIVE ; // $old_material_name -> $new_material_name2 before step $interval_step_id"
          set ::ElementGroupInactiveVypsano($interval_number,$old_material_name,$group_id,$interval_step_id) 1
          if {$new_material_name2!=""} {
          if {$reset2==1} {
            append result "\n   DELETE MATERIAL_POINTS GROUP $group_id ;"
          }
          
          set num_material_name2_num [MyZapisElementGroupMaterialNumberGetNumber $new_material_name2 ]
          #set num_material_name2_num [TK_FindMaterialNumber $new_material_name2 $new_material_name2]
          append result "\n   ELEMENT GROUP ID $group_id MATERIAL $num_material_name2_num;"
          
          set idealisation_old [GiD_AccessValue get materials $old_material_name "Idealisation"]
          set idealisation_new [GiD_AccessValue get materials $new_material_name2 "Idealisation"]
          #WarnWinText "idealisation_old = $idealisation_old"
          #WarnWinText "idealisation_new = $idealisation_new"
          if {$idealisation_old == $idealisation_new} { } else {
            WarnWinText "When replacing materials it is important that same element and geometry type is used in both materials."
            WarnWinText "Warning: Interval number: $interval_number, Old material: $old_material_name (idealisation $idealisation_old), New material: $new_material_name2 (idealisation $idealisation_new)"
          }
          
          
          set prototype [GiD_AccessValue get materials $old_material_name "Material_Prototype"]
          set oCCShellMaterial [string equal $prototype "CCShellMaterial"]
          #append result "// prototype = $prototype, oCCShellMaterial=$oCCShellMaterial \n"
          if {$oCCShellMaterial == 1} {
            append result "\n   ELEMENT GROUP ID $group_id GEOMETRY $num_material_name2_num;"
          }
          append result "\n   ELEMENT GROUP ID $group_id ACTIVE ; \n"
          }
          return $result        
        }      
      } 
    }
    }
}  
  
proc Splash { dir } {
 if { [GidUtils::IsTkDisabled] } {
    #e.g. batch mode without windows
    return 1
 }
 global GIDDEFAULT
 global keepsplash VersionNumber
# set VersionNumber " Template Build 1945 & Atena 4.0.0b"
#source "Problemtypes\\Atena\\include.src.bas\\Ver_number.tcl"

# WarnWinText "dir= [pwd]; $dir"
 if { [.gid.central.s disable windows] } { return }

 if { [ winfo exist .splash]} {
  destroy .splash
  update
 }
 toplevel .splash

 set im [image create photo -file [file join $dir .. images LogoNuselak04a.png]]
# set x [expr [image width $im]*1/5]
# set y [expr [image height $im]*4/5]
 set x [expr [winfo screenwidth .splash]/2-[image width $im]/2]
 set y [expr [winfo screenheight .splash]/2-[image height $im]/2]

 wm geom .splash +$x+$y
 wm transient .splash .gid
 wm overrideredirect .splash 1
 pack [label .splash.l -image $im -relief ridge -bd 2]

 label .splash.lv -text $VersionNumber -foreground white -relief raised -bd 3 \
   -background green4 -font "times 10"
 place .splash.lv -x 11 -y 185
 bind .splash <1> "destroy .splash"
 bind .splash <KeyPress> "destroy .splash"
 raise .splash .gid
 grab .splash
 focus .splash
 update

 after 4000 "if { (!$keepsplash) && [ winfo exist .splash] } {
  destroy .splash
 }"
}


proc TK_Trick_To_Set_Entry_Width { event args } {
    switch $event {
 "INIT" {
     set PARENT [lindex $args 0] 
     upvar [lindex $args 1] ROW
     #WarnWinText "args: $args"
     #WarnWinText "$PARENT.e$ROW configure -width 40"
     $PARENT.e$ROW configure -width 40
     #WarnWinText "up: $UP"

     set ROW [expr $ROW-1]

 }
    }
    return ""
}

proc ZJ_InitUpdateCheckProcess {} {
  global problem_dir
  set A3Post $problem_dir
  append A3Post "\\..\\UpdateCheck.bat"
  # WarnWinText $A3Post
  exec $A3Post &
  return ""
}

proc ZJ_ExecuteConMix { param } {
  global problem_dir
  global GiDProjectDir GiDProjectName taskName
  
  set A3Post $problem_dir
  append A3Post "\\..\\Execute\\ConMix.bat"
  # WarnWinText $A3Post
  set par $GiDProjectDir 
  #append par "/AtenaCalculation\/"
  if { $GiDProjectDir == ""} {
    WarnWinText "Please save your project first. ConMix needs a project directory to be able to start."
    return ""
  }
  append par "\/"
  append par $param
  
  set disk [string range $par 0 1]
  #set par $param
  set batfile $par
  append batfile ".bat"
  
  #WarnWinText $A3Post
  #WarnWinText $par
  regsub -all "/" $par "\\" par 
  #WarnWinText $par
  # ConMix.exe -f <filename> -u N,mm,C,second,kg
  set jednotky [GidGetUnitStr force]
  append jednotky ","
  append jednotky [GidGetUnitStr length]
  append jednotky ","
  append jednotky [GidGetUnitStr unit_temperature]
  append jednotky ","
  
  set jedn_cas [GidGetUnitStr time] 
  if { $jedn_cas == "sec"} {
    append jednotky "second"
  } elseif { $jedn_cas == "min"} {
    append jednotky "minute"
  } else {
    append jednotky $jedn_cas
  }
  append jednotky ","
  set jedn_mass [GidGetUnitStr mass] 
  if { $jedn_mass == "kton"} {
    append jednotky "kTon"
  } elseif { $jedn_mass == "lb"} {
    append jednotky "Lb"
  } else {
    append jednotky $jedn_mass
  }  
  #WarnWinText $jednotky
  
                   # second minute
#set Atena_Version [GiD_AccessValue get gendata Atena_Version]
 # if { $Atena_Version == "ATENA_2024"} {
    set data "$disk
    cd $GiDProjectDir
    md AtenaCalculation
    cd AtenaCalculation
    %ConMix2024% -f \"$param\" -u $jednotky"
  #} else {
   # set data "$disk
   # cd $GiDProjectDir
   # md AtenaCalculation
   # cd AtenaCalculation
   # %ConMix% -f \"$param\" -u $jednotky"
  #}
  set fileId [open $batfile "w"]
  puts -nonewline $fileId $data
  close $fileId  
   
  exec $batfile >& NUL:
  if { [file exists $batfile] == 1} {
    file delete $batfile
  }
  #GiD_Process escape escape escape Files WriteForBAS "$problem_dir/../Execute/ConMix_bat.bas" "$batfile"
  #exec $A3Post >& NUL:
  return ""
}


proc TK_RunConMix { event args } {
 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
  
  set lines [split $STRUCT ","]
  set MAT [lindex $lines 1]
  
   
    set RunConMix [DWLocalGetValue $GDN $STRUCT Run_ConMix_for_CERHYD]
    #set Name [DWLocalGetValue $GDN $STRUCT Run_ConMix_for_CERHYD]
    
     if { $RunConMix == "1" } {
     set on [DWLocalSetValue $GDN $STRUCT Run_ConMix_for_CERHYD No]
     ZJ_ExecuteConMix $MAT
      } 
    
    }
  }
}

proc ZJ_WriteTime { txt } {
    set systemTime [clock seconds]
    set a "************************************************   WriteTime: $txt ="
    append a [clock format $systemTime -format {%H_%M_%S}]
    WarnWinText $a    
}
        

proc ZJ_CheckAndDeleteBinaryFiles { step } {
    global problem_dir
    global GIDDEFAULT
    cd $GIDDEFAULT
    global GiDProjectDir GiDProjectName taskName     
    
    set VersionRequired "11.0.0"
    set comp -1
    catch {
       set comp [GiDVersionCmp $VersionRequired]
    }
    
   
   set existujeStarsi 0
   set soubor "$GiDProjectDir\\AtenaCalculation\\$taskName."
   #WarnWin $soubor 
   incr step
   
    for {set i $step} {$i < 10000} {incr i} {
        set cislo [getStepNumber $i]
        set Batka $soubor
        append Batka $cislo 
        #WarnWinText $Batka
        if { [file exists $Batka] == 1} {  
            #WarnWinText $Batka             
            set existujeStarsi 1
            break
        }
    }

    if { $existujeStarsi == 1} {               

    set zpusob [GiD_AccessValue get genData Delete_old_results_at_analysis_start]
    
    switch -- $zpusob {
            Delete {  
              set answer yes
            }
            Ask {
                if { [info exists ::Atena_AskToTransform] && $::Atena_AskToTransform == 0 } {
                   set answer yes
                } else {
                  #set answer [tk_messageBox -message "There are some binary result files with numbers bigger then the first step to be calculated now. Do you want to delete them?\n\nYes - all the old results from later steps will be deleted. Results from steps up to (FirstStepToBeCalculatedNow-1) will stay untouched.\n\nNo - no results files are deleted now. The results from previous analysis runs stay on the disk and will be overwritten if results from the same step are stored. This may lead to a confusing mix of old and new results in the directory, especially if fewer steps are being calculated now (e.g., up to step 100 while previously 150 steps were calculated) or if fewer results are being stored (e.g., every 10th step while previously, every 5th step was stored). You can save your answer in Problem Data/Restart_Calculation_from_Calculated_step/Delete_old_results_at_analysis_start. " -type yesno -icon question]
                  set answer [Atena_MessageBoxOptionsButtons "ATENA-GiD" "There are some binary result files with numbers bigger then the first step to be calculated now. Do you want to delete them?\n\nYes - all the old results from later steps will be deleted. Results from steps up to (FirstStepToBeCalculatedNow-1) will stay untouched.\n\nNo - no results files are deleted now. The results from previous analysis runs stay on the disk and will be overwritten if results from the same step are stored. This may lead to a confusing mix of old and new results in the directory, especially if fewer steps are being calculated now (e.g., up to step 100 while previously 150 steps were calculated) or if fewer results are being stored (e.g., every 10th step while previously, every 5th step was stored). You can save your answer in Problem Data/Restart_Calculation_from_Calculated_step/Delete_old_results_at_analysis_start. " "" [list yes no] [list [_ "Yes"] [_ "No"]] question]
                }      
            }
            Keep {
              set answer no
            }
        }
    
    
    switch -- $answer {
        yes {
            for {set i $step} {$i < 10000} {incr i} {
            set cislo [getStepNumber $i]
            set Batka $soubor
            append Batka $cislo 
            #WarnWinText $Batka
            if { [file exists $Batka] == 1} {  
              file delete $Batka
            }
            }
            

                
            set input [GiD_Set UseMoreWindows]
            if { $input == 1 } {
                #set ChangeVarInfo(Usemorewindows) normal
                    if { $comp < 0 } {
                      #WarnWin "Verze 10"
                    } else {
                       #WarnWin "Verze 11"
                       #puts stdout "Old binary files were deleted" #vyhozeno, hazi chyby
                    }
                #.gid.central.s OutPutPrintedMessages 
            } elseif { $input == 2 } {
            #tk_messageBox -message "Old binary files were deleted" -type ok
            Atena_MessageBoxOk "Info" "Old binary files were deleted" info 
                #set ChangeVarInfo(Usemorewindows) beginner
            } else {
                #set ChangeVarInfo(Usemorewindows) normal
            }
        
        
        
        }
        no {
                set input [GiD_Set UseMoreWindows]
                if { $input == 1 } {
                    #set ChangeVarInfo(Usemorewindows) normal
                    if { $comp < 0 } {
                       #WarnWin "Verze 10"
                    } else {
                       #WarnWin "Verze 11"
                       #puts stdout "Old binary files were not deleted"  #vyhozeno, hazi chyby
                    }                    
                    #.gid.central.s OutPutPrintedMessages                     
                } elseif { $input == 2 } {
                #tk_messageBox -message "Old binary files were not deleted"  -type ok
                Atena_MessageBoxOk "Info" "Old binary files were not deleted" info
                    #set ChangeVarInfo(Usemorewindows) beginner
                } else {
                    #set ChangeVarInfo(Usemorewindows) normal
                }
        }
        }
    
    }

    
    if { $step > 0} {
        set soubor "$GiDProjectDir\\AtenaCalculation\\$GiDProjectName"
        set soubornew $soubor
        set systemTime [clock seconds]
        append soubornew [clock format $systemTime -format {_backup_%y_%m_%d_%H_%M_%S}]
        #WarnWinText $soubornew
        
        set Out $soubor
        append Out ".out" 
        set Outnew $soubornew
        append Outnew ".out" 

        set Msg $soubor
        append Msg ".msg" 
        set Msgnew $soubornew
        append Msgnew ".msg" 
        
        set Err $soubor
        append Err ".err" 
        set Errnew $soubornew
        append Errnew ".err"         

        #WarnWinText $Out
        #WarnWinText $Outnew
        
        if { [file exists $Out] == 1 && [file exists $Outnew] == 0} {  
            file rename $Out $Outnew              
         } 
        if { [file exists $Msg] == 1 && [file exists $Msgnew] == 0} {  
            file rename $Msg $Msgnew              
         } 
        if { [file exists $Err] == 1 && [file exists $Errnew] == 0} {  
            file rename $Err $Errnew              
         }                   
    }    
 
     return ""
}

proc OutputParser { name } {

  if { $name == "STRESS_R1" } { return "STRESS_(R1)" }
  if { $name == "STRESS_R2" } { return "STRESS_(R2)" }
  if { $name == "STRESS_R3" } { return "STRESS_(R3)" }
  if { $name == "STRESS_R4" } { return "STRESS_(R4)" }
  
  if { $name == "STRAIN_R1" } { return "STRAIN_(R1)" }
  if { $name == "STRAIN_R2" } { return "STRAIN_(R2)" }
  if { $name == "STRAIN_R3" } { return "STRAIN_(R3)" }
  if { $name == "STRAIN_R4" } { return "STRAIN_(R4)" }
  
  if { $name == "STRESS_S1" } { return "STRESS_(S1)" }
  if { $name == "STRESS_S2" } { return "STRESS_(S2)" }
  if { $name == "STRESS_S3" } { return "STRESS_(S3)" }
  if { $name == "STRESS_S4" } { return "STRESS_(S4)" }
  if { $name == "STRESS_S5" } { return "STRESS_(S5)" }
  if { $name == "STRESS_S6" } { return "STRESS_(S6)" }

  if { $name == "STRAIN_S1" } { return "STRAIN_(S1)" }
  if { $name == "STRAIN_S2" } { return "STRAIN_(S2)" }
  if { $name == "STRAIN_S3" } { return "STRAIN_(S3)" }
  if { $name == "STRAIN_S4" } { return "STRAIN_(S4)" }
  if { $name == "STRAIN_S5" } { return "STRAIN_(S5)" }
  if { $name == "STRAIN_S6" } { return "STRAIN_(S6)" }
  
  return $name
}

proc InitGIDPostProcess {} {
#  AtenaExportResults2GiD
#  JN_InitGIDPostProcess
  return ""
}

proc getGiDProjectName {} {
  global GiDProjectName
  return $GiDProjectName
}

proc InitA2G {} {
  AtenaExportResults2GiD
  JN_InitGIDPostProcess
  return ""
}

proc EndGiDPostprocess {} {
  global toolbardir
  WarnWin $toolbardir
  InitGIDProject $toolbardir
  return ""
}

 

proc TK_Atena3DPostCall {} {
  global problem_dir
  global GiDProjectDir
  global GiDProjectName  

# WarnWinText $task5dir
#  cd $task5dir
# WarnWinText [pwd]
  cd $GiDProjectDir
  set A3Post $problem_dir

#  if { [GidUtils::GetProblemDataValue "Procesor_Type#CB#(32bit,64bit)"] == "64bit" } {
  append A3Post "/Atena3DPost64.bat"
#  } else {
#     append A3Post "/Atena3DPost.bat"
#  } 

  #WarnWinText "$GiDProjectDir/AtenaCalculation/$GiDProjectName.ccs"
  set soubor "$GiDProjectDir/AtenaCalculation/$GiDProjectName.ccs"
  #exec $A3Post &
  exec $A3Post >post.txt "$soubor" & 
  #exec $A3Post >post.txt "$soubor" >& NUL:
  #exec $A3Post >post.txt >& NUL:
  
}

proc TK_symbolsEditors { } {
	SymbolsEditor.tcl
}

proc OptionPost {} {
 GiD_Process escape escape escape Preprocess Yes
 GidOpenProblemData Post_data
# GiD_Process Postprocess
}
 

proc ReadResults {} {
  global GiDProjectDir
  global GiDProjectName

  if { $GiDProjectName == "UNNAMED" } {
    GiD_Process escape escape escape escape Files Read
    return ""
  }
  GiD_Process mescape Files Read "$GiDProjectDir\\AtenaCalculation\\AtenaResults.flavia.res"    
}


proc ImportEPWFile { event args } {
 global GiDProjectDir
 global GiDProjectName
 
 #WarnWinText $event
 switch $event {
 DEPEND {


# set answer [GiD_Info intvdata -interval 1]
# WarnWinText $answer
  
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]

  set st [DWLocalGetValue $GDN $STRUCT Import_function_from_EPW_file]
  #WarnWinText $st
  #WarnWinText $args
  
      #if [ string match -nocase "*RESTORE*" $args] {
                    if {$st==1} {
                    #WarnWinText "otviram"
                    
                    set From_Month [DWLocalGetValue $GDN $STRUCT From_Month]
                    set From_Day [DWLocalGetValue $GDN $STRUCT From_Day]
                    set From_Hour [DWLocalGetValue $GDN $STRUCT From_Hour]
                    set To_Month [DWLocalGetValue $GDN $STRUCT To_Month]
                    set To_Day [DWLocalGetValue $GDN $STRUCT To_Day]
                    set To_Hour [DWLocalGetValue $GDN $STRUCT To_Hour]
                    
                    set From_String "2000/$From_Month/$From_Day $From_Hour:00:00" 
                    set From_Time [clock scan $From_String -format "%Y/%m/%d %T"]
                    set To_String "2000/$To_Month/$To_Day $To_Hour:00:00" 
                    set To_Time [clock scan $To_String -format "%Y/%m/%d %T"]
                    
                    set What_to_import [DWLocalGetValue $GDN $STRUCT What_to_import]
                    #QUESTION: #CB#(irradiance,temperature,humidity)
                    
                                        
                    #WarnWinText "$From_String"
                    #WarnWinText "$From_Time"
                    
                    set types { 
                              {{All Files} {.*} }
                              {{EPW Files} {.epw} }
                              } 
                    
                    set filename [tk_getOpenFile -filetypes $types -initialdir $GiDProjectDir -initialfile $GiDProjectName.epw] 
                    # DWLocalSetValue $GDN $STRUCT Import_function_from_EPW_file $filename   
                        set a [open $filename]
                        set lines [split [read $a] "\n"]
                        close $a;                          # Saves a few bytes :-)
                        set lineNumber 0
                        set function_string ""
                        set function_string_step 0
                        foreach line $lines {
                            
                            # do something with each line...
                            incr lineNumber
                            #WarnWinText $lineNumber
                            
                            if {$lineNumber == 1} {
                                                        set lin [split $line ","]
                            set latitude [lindex $lin 6]
                            set latitudeRad [expr $latitude*2*3.14/360.0]
                            WarnWinText "$latitude latitude"
                            #WarnWinText "$latitudeRad latitudeRad"
                            }
                            
                            
                            if { $lineNumber < 9} continue
                            
                            #WarnWinText $line
                            set lin [split $line ","]
                            set mesic [lindex $lin 1]
                            set den [lindex $lin 2]
                            set hodina [lindex $lin 3]
                            
                            #WarnWinText $mesic
                            if {$mesic >= 1 && $mesic <= 12} { 
                            } else {
                            break
                            }
                            
                            set Now_String "2000/$mesic/$den $hodina:00:00" 
                            set Now_Time [clock scan $Now_String -format "%Y/%m/%d %T"]
                            


                            if {$Now_Time < $From_Time} continue
                            if {$Now_Time > $To_Time} continue

                            set gbn [lindex $lin 14]
                            set gdh [lindex $lin 15]
                            set temp [lindex $lin 6]
                            set humi [lindex $lin 8]
                            set humi [expr $humi/100.0]
                            set humi [format %10.6g $humi]
                            #WarnWinText [lindex $lin 4]                            
                            #WarnWinText "$mesic $den $hodina $gbn $gdh $temp"
                            if {$What_to_import == "irradiance"} {
                               set alpha [expr 2.0 * 3.14 / 365.0 * (($den+30*($mesic-1))-81)]
                               set declination [expr 0.40928 * sin($alpha)]
                               set time_angle [expr ($hodina-12)/24.0*2.0*3.14 ]
                               if {$time_angle > 3.135} {set time_angle 3.135}
                               
                               #WarnWinText "$mesic $den $hodina => $temp | gbn=$gbn  gdh=$gdh "
                               #WarnWinText "decl $declination | timeangle $time_angle"
                               
                               #=ARCSIN(SIN($C$2)*SIN(G5)+COS($C$2)*COS(G5)*COS(H5))
                               set se1 [expr sin($latitudeRad) * sin($declination)]
                               set se2 [expr cos($latitudeRad) * cos($declination) * cos($time_angle)] 
                               set s_e [expr $se1 + $se2 ]
                               set sun_elevation [expr asin($s_e)]
                               #WarnWinText "sun_elevation = $sun_elevation"

                               set sa1 [expr sin($declination) * cos($latitudeRad)]
                               set sa2 [expr cos($declination) * sin($latitudeRad) * cos($time_angle)] 
                               set s_a [expr ($sa1 - $sa2) / cos($sun_elevation) ]
                               if {$s_a < -1} {
                                    set s_a -1
                               }
                               #WarnWinText "acos $s_a"
                               set sun_azimuth [expr acos($s_a)]
                               #=IF(C5<12;
                               if {$hodina < 12} {
                               #ARCCOS(  (SIN(G5)*COS($C$2)-COS(G5)*SIN($C$2)*COS(H5)) / COS(K5)  );
                               } else {
                               #MAX(-1;MIN(  1;   2*3.14 - ARCCOS((SIN(G5)*COS($C$2)-COS(G5)*SIN($C$2)*COS(H5))/COS(K5))))
                               set sun_azimuth [expr (2.0 * 3.14) - $sun_azimuth]
                               }
                               #WarnWinText "sun_azimuth = $sun_azimuth"
                               
                               set EPW_Surface_Azimuth [DWLocalGetValue $GDN $STRUCT EPW_Surface_Azimuth]
                               set EPW_Surface_Inclination [DWLocalGetValue $GDN $STRUCT EPW_Surface_Inclination]                               
                               set EPW_Surface_AzimuthRad [expr $EPW_Surface_Azimuth*2*3.14/360.0]
                               set EPW_Surface_InclinationRad [expr $EPW_Surface_Inclination*2*3.14/360.0]
                               
                               #=SIN(K5)*COS($G$1)   +   COS(K5)*SIN($G$1)*COS(L5-$G$2)
                               set cos_gamma1 [expr sin($sun_elevation) * cos($EPW_Surface_InclinationRad)]
                               set cos_gamma2 [expr cos($sun_elevation) * sin($EPW_Surface_InclinationRad) * cos($sun_azimuth-$EPW_Surface_AzimuthRad)]
                               set cos_gamma [expr $cos_gamma1 + $cos_gamma2]
                               #WarnWinText "cos_gamma = $cos_gamma"
                               
                               #=IF(M8<0;0;M8)*D8
                               if { $cos_gamma < 0 } {
                               set GBgamma 0
                               } else {
                               set GBgamma [expr $cos_gamma * $gbn]
                               }
                               
                               
                               
                               #=(1+COS($G$1))  /2*E13
                               if {$gdh == 0 } {
                               set Gdalpha 0
                               } else {
                               set Gdalpha [expr (1+cos($EPW_Surface_InclinationRad) ) / 2 * $gdh]
                               }
                               
                               set Gtotal [expr $GBgamma + $Gdalpha]
                               
                               set GBgamma [format %10.6g $GBgamma]
                               set Gdalpha [format %10.6g $Gdalpha]
                               set Gtotal [format %10.6g $Gtotal]
                               
                               WarnWinText "$mesic $den $hodina => GBgamma = $GBgamma ||  Gdalpha = $Gdalpha  || Gtotal = $Gtotal"
                               
                               incr function_string_step
                               append function_string " $function_string_step $Gtotal"
                               
                            }
                            
                            if {$What_to_import == "temperature"} {
                               #WarnWinText "$mesic $den $hodina => $temp"
                               #WarnWinText "$function_string"
                               incr function_string_step
                               append function_string " $function_string_step $temp"
                               
                            }
                            if {$What_to_import == "humidity"} {
                               #WarnWinText "$mesic $den $hodina => $humi"
                               incr function_string_step
                               append function_string " $function_string_step $humi"
                            }                            
                            #if { $lineNumber > 200} break
                        }
                        
                    set fnc_number [expr $function_string_step * 2]
                    #WarnWinText "$fnc_number"
                    set Function "#N# $fnc_number $function_string"
                    #WarnWinText "$Function"
                    set on [DWLocalSetValue $GDN $STRUCT Function $Function]                            

                    WarnWinText "Done, function imported"    
                    #DWLocalSetValue $GDN $STRUCT Import_function_from_EPW_file 0
                    DWLocalSetValue $GDN $STRUCT Type_of_input "USER"
                    DWLocalSetValue $GDN $STRUCT Import_function_from_EPW 0
                                                                
                    }
      #}
      #if [ string match -nocase "*HIDE*" $args] {
      #}
      return ""
    }
  }

}

proc OpenImportFile { event args } {
 global GiDProjectDir
 global GiDProjectName
 
 switch $event {
 DEPEND {


# set answer [GiD_Info intvdata -interval 1]
# WarnWinText $answer
  
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]

  set st [DWLocalGetValue $GDN $STRUCT Import_function_from_file]
  
      if [ string match -nocase "*RESTORE*" $args] {
                    if {$st==""} {
                    # WarnWinText Spust
                    set types { 
                              {{All Files} {.*} }
                              {{CSV Files} {.csv} }
                              {{Text Files} {.txt} }
                              } 
                              
                      if { $GiDProjectName == "" } {
                      #tk_messageBox -title "Save" -message "Please save your project first." -icon info -type ok
                      Atena_MessageBoxOk "Info" "Please save your project first." info
                      return ""
                      }
                     #WarnWinText $GiDProjectDir
                     #WarnWinText $GiDProjectName                              
                    
                    set filename [tk_getOpenFile -filetypes $types -initialdir $GiDProjectDir -initialfile $GiDProjectName.ccf] 
                    if {$filename==""} {
                    DWLocalSetValue $GDN $STRUCT Ground_Accelerogram 0
                    }
                    DWLocalSetValue $GDN $STRUCT Import_function_from_file $filename   
                       
                    }
      }
      if [ string match -nocase "*HIDE*" $args] {
      DWLocalSetValue $GDN $STRUCT Import_function_from_file ""
      }
      return ""
    }
  }

}

proc OpenImportFile2 { event args } {
 global GiDProjectDir
 global GiDProjectName
 
 switch $event {
 DEPEND {


# set answer [GiD_Info intvdata -interval 1]
# WarnWinText $answer
  
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]

  set st [DWLocalGetValue $GDN $STRUCT Import_function_from_file2]
  
      if [ string match -nocase "*RESTORE*" $args] {
                    if {$st==""} {
                    # WarnWinText Spust
                    set types { 
                              {{All Files} {.*} }
                              {{CSV Files} {.csv} }
                              {{Text Files} {.txt} }
                              } 
                              
                      if { $GiDProjectName == "" } {
                      #tk_messageBox -title "Save" -message "Please save your project first." -icon info -type ok
                      Atena_MessageBoxOk "Info" "Please save your project first." info
                      return ""
                      }
                     #WarnWinText $GiDProjectDir
                     #WarnWinText $GiDProjectName                              
                    
                    set filename [tk_getOpenFile -filetypes $types -initialdir $GiDProjectDir -initialfile $GiDProjectName.ccf] 
                    if {$filename==""} {
                    DWLocalSetValue $GDN $STRUCT Ground_Accelerogram2 0
                    }
                    DWLocalSetValue $GDN $STRUCT Import_function_from_file2 $filename   
                       
                    }
      }
      if [ string match -nocase "*HIDE*" $args] {
      DWLocalSetValue $GDN $STRUCT Import_function_from_file2 ""
      }
      return ""
    }
  }

}

proc OpenImportFile3 { event args } {
 global GiDProjectDir
 global GiDProjectName
 
 switch $event {
 DEPEND {


# set answer [GiD_Info intvdata -interval 1]
# WarnWinText $answer
  
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]

  set st [DWLocalGetValue $GDN $STRUCT Import_function_from_file3]
  
      if [ string match -nocase "*RESTORE*" $args] {
                    if {$st==""} {
                    # WarnWinText Spust
                    set types { 
                              {{All Files} {.*} }
                              {{CSV Files} {.csv} }
                              {{Text Files} {.txt} }
                              } 
                              
                      if { $GiDProjectName == "" } {
                      #tk_messageBox -title "Save" -message "Please save your project first." -icon info -type ok
                      Atena_MessageBoxOk "Info" "Please save your project first." info
                      return ""
                      }
                     #WarnWinText $GiDProjectDir
                     #WarnWinText $GiDProjectName                              
                    
                    set filename [tk_getOpenFile -filetypes $types -initialdir $GiDProjectDir -initialfile $GiDProjectName.ccf] 
                    if {$filename==""} {
                    DWLocalSetValue $GDN $STRUCT Ground_Accelerogram3 0
                    }
                    DWLocalSetValue $GDN $STRUCT Import_function_from_file3 $filename   
                       
                    }
      }
      if [ string match -nocase "*HIDE*" $args] {
      DWLocalSetValue $GDN $STRUCT Import_function_from_file3 ""
      }
      return ""
    }
  }

}

proc Spust {} {

     set fp [open "C:/text.txt" r]
     set data [read $fp]
     close $fp

       set re {(?x)
      	\s+ ([[:graph:]]+)      # first number
      	\s+ ([[:graph:]]+)      # second number
       }
       
      set vypisX ""
      set vypisY "" 
  
      set data [split $data "\n"]
      foreach line $data {

      set line " $line "
      set line [string map { \; " " } $line]
      set b [regexp $re $line match matchX matchY]

      if {$b==1} {
      set vypisX "$vypisX $matchX"
      set vypisY "$vypisY $matchY"
      #tk_messageBox -message "x=$matchX y=$matchY polozka b= $b" -icon warning -type ok
      Atena_MessageBoxOk "Info" "x=$matchX y=$matchY polozka b= $b" warning
      }
         
     }
    #tk_messageBox -message "vypisX=$vypisX" -icon warning -type ok
    #tk_messageBox -message "vypisY=$vypisY" -icon warning -type ok
    Atena_MessageBoxOk "Info" "vypisX=$vypisX" warning
    Atena_MessageBoxOk "Info" "vypisY=$vypisY" warning 
     return "line"
}

proc TK_replaceLomitka { name } {
   set name2 [string map { "//" "/" } $name]
   return $name2
}

proc TK_VypisMessageBox { aa bb } {
#tk_messageBox -icon error -message "You don't have assigned Material $aa at Element $bb For first number of unassigned element see *.dat file" -icon warning -type ok
Atena_MessageBoxOk "Info" "You don't have assigned Material $aa at Element $bb For first number of unassigned element see *.dat file" warning 
return ""
}
          
proc TK_WarnWinText { msg } {
  WarnWinText $msg
return ""
}

proc TK_TK_WarnWinTextTK_CTRLv { } {
  global ctrlvalue
  TK_WarnWinText $ctrlvalue
return ""
}


proc TK_CTRLclear { } {
global ctrlvalue
set ctrlvalue ""
return ""
}
  
proc TK_CTRLc { msg1 {msg2 ""} {msg3 ""} {msg4 ""} {msg5 ""} } {
global ctrlvalue
set ctrlvalue $msg1$msg2$msg3$msg4$msg5
return ""
}

proc TK_CTRLv { } {
global ctrlvalue
return $ctrlvalue
}


proc ZapisAktualniScriptPriSpusteni {} {
 global GiDProjectName
 
 if { $GiDProjectName == "UNNAMED" } {
global VersionNumberOnly VersionNumber
#source "Problemtypes\\Atena\\include.src.bas\\Ver_number.tcl"

set answer [GiD_Info gendata]
# WarnWinText "$answer"
if [ string match -nocase "*Script_Version*" $answer ] {
# WarnWinText "ano"
  GiD_Process MEscape Data ProblemData "-SingleField-" Script_version $VersionNumberOnly
}
 }
}

proc GetNodeCoordinates { oNumNode } {

  set node [GiD_Mesh get node $oNumNode]
  set txt [lindex $node 1]
  lappend txt [lindex $node 2]
  lappend txt [lindex $node 3]

   return $txt
}


proc GetDistanceValueForSelectionNameAbs { oSelectionName } {
  set distance [GetDistanceValueForSelectionName $oSelectionName]
  return [Abs_Val $distance]
}             


proc GetDistanceValueForSelectionName { oSelectionName } {
  set value [GiD_AccessValue get genData Master_Slave_Distance_Manual]
  set max [lindex $value 1]
  #set array "#N# 0"
  for {set i 1 } { $i <= $max } { set i [expr $i + 2] } {
#	  set stepindex [lindex $value $i]
	  set name [lindex $value [expr $i+1]]
	  set distance [lindex $value [expr $i+2]]
	  
	  #WarnWinText "porovnavam"
	  #WarnWinText $name
	  #WarnWinText $oSelectionName
	  
    if [ string match -nocase $oSelectionName $name ] {	  

      #WarnWinText "manual"
      return $distance
    }
	  #WarnWinText multiplier
  }
  set distance [GiD_AccessValue get genData Master_Slave_Distance]
  set n [GidConvertValueUnit $distance]
  set n [ParserNumberUnit $n distance unit]
    
  #WarnWinText "default"
   return $distance
}


proc GetSearchRadiusValueForSelectionName { oSelectionName } {
  set value [GiD_AccessValue get genData Master_Slave_SR_AOE_Manual]
  set max [lindex $value 1]
  #set array "#N# 0"
  for {set i 1 } { $i <= $max } { set i [expr $i + 3] } {
#	  set stepindex [lindex $value $i]
	  set name [lindex $value [expr $i+1]]
	  set radius [lindex $value [expr $i+2]]
      set accept_outside [lindex $value [expr $i+3]]
	  
	  #WarnWinText "porovnavam"
	  #WarnWinText $name
	  #WarnWinText $oSelectionName
    if [ string match -nocase $oSelectionName $name ] {	  
      #WarnWinText "manual"
        return $radius
    }
  }
  set radius [GiD_AccessValue get genData Master_Slave_Search_Radius]
  set n [GidConvertValueUnit $radius]
  set n [ParserNumberUnit $n radius unit]
  #WarnWinText "default"
   return $radius
}

proc GetAcceptOutsideElementValueForSelectionName { oSelectionName } {
  set value [GiD_AccessValue get genData Master_Slave_SR_AOE_Manual]
  set max [lindex $value 1]
  #set array "#N# 0"
  for {set i 1 } { $i <= $max } { set i [expr $i + 3] } {
#	  set stepindex [lindex $value $i]
	  set name [lindex $value [expr $i+1]]
	  set radius [lindex $value [expr $i+2]]
      set accept_outside [lindex $value [expr $i+3]]
	  
	  #WarnWinText "porovnavam"
	  #WarnWinText $name
	  #WarnWinText $oSelectionName
    if [ string match -nocase $oSelectionName $name ] {	  
      #WarnWinText "manual"
        if {$accept_outside == 0} {
          return ""
        } else {
          set accept_outside [format %s%g "ACCEPT_OUTSIDE_ELEMENT " $accept_outside]
          return $accept_outside
        }
        
    }
  }
  set accept_outside [GiD_AccessValue get genData Master_Slave_Accept_Outside_Element]
  set n [GidConvertValueUnit $accept_outside]
  set n [ParserNumberUnit $n accept_outside unit]
  #WarnWinText "default"
        if {$accept_outside == 0} {
          return ""
        } else {
          set accept_outside [format %s%g "ACCEPT_OUTSIDE_ELEMENT " $accept_outside]
          return $accept_outside
        }
}

proc AtenaExportResults2GiD {} {
 global GIDDEFAULT
 global GiDProjectDir GiDProjectName taskName

 set GiDProblemTypeDir [GetDirectoryProblemType]
 set ProblemDirectory $GiDProblemTypeDir
 

 if { ![file isdirectory $ProblemDirectory] } {
  set ProblemDirectory [file join $GIDDEFAULT problemtypes $ProblemType.gid]
 }
 #WarnWinText "ProblemDirectory2 = $ProblemDirectory"
 if { ![file isdirectory $ProblemDirectory] } {
  return ""
 }
# WarnWinText "proje5ct name= $Proj5ectName"
#WarnWinText "ProblemDirectory3 = $ProblemDirectory" 
 if { $GiDProjectName == "UNNAMED" } {
  return ""
 }
 #WarnWinText "ProblemDirectory4 = $ProblemDirectory"
 #WarnWinText "tas5kdir=$task5dir "
 #WarnWinText "ProblemType=$ProblemType"
 #WarnWinText "ProblemDirectory=$ProblemDirectory"

 #WarnWinText [pwd]


 

#1: C:/Program Files/GiD/GiD 8.2.0b/problemtypes/Atena/Static.gid/../Execute/CreateAtenaFlaviaInp.bas
#  C:/Program Files/GiD/GiD 8.2.0b/problemtypes/Atena/Static.gid/../Execute/CreateAtenaFlaviaInp.bas
#GiD_Process escape escape escape escape Preprocess OK Files WriteForBAS "$ProblemDirectory/../Execute/CreateAtenaFlaviaInp.bas" "$tas5kdir\\AtenaResults.inp" \
   
 GiD_Process escape escape escape Preprocess Yes

  set ImportYesNo [GiD_AccessValue get genData Import_Only_These_Steps]
  #WarnWinText "$ImportYesNo"
  
 if { $ImportYesNo == "1" } {


  set value [GiD_AccessValue get genData Steps_To_Import]
  
  set max [lindex $value 1]
  set array "#N# 0"
  for {set i 1 } { $i <= $max } { set i [expr $i + 1] } {
#	  set stepindex [lindex $value $i]
	  set multiplier [lindex $value [expr $i+1]]
 
    set multtext [getStepNumber $multiplier]
	  #WarnWinText "multiplier= $multiplier, multtext= $multtext"
	  GiD_AccessValue set gendata Import_Only_This_Step "$taskName.$multtext"
	  
    GiD_Process escape escape escape Files WriteForBAS "$ProblemDirectory/../Include.src.bas/WriteResultsOnlySomeStepsInp.bas" "$GiDProjectDir\\$taskName.$multtext.inp"
    GiD_Process escape escape escape Files WriteForBAS "$ProblemDirectory/../Include.src.bas/WriteResultsOnlySomeStepsBat.bas" "$GiDProjectDir\\$taskName.$multtext.bat"
    GiD_Process escape escape escape Files WriteForBAS "$ProblemDirectory/../Include.src.bas/WriteResultsOnlySomeStepsMainBat.bas" "$GiDProjectDir\\getResults.bat"
    
   }
 } else {
  GiD_Process escape escape escape Files WriteForBAS "$ProblemDirectory/../Include.src.bas/write_run_import_results.bas" "$GiDProjectDir\\run_import.bat"
  GiD_Process escape escape escape Files WriteForBAS "$ProblemDirectory/../Execute/CreateAtenaFlaviaInp.bas" "$GiDProjectDir\\AtenaResults.inp"
 }  

 GiD_Process escape escape escape escape Files WriteMesh "$GiDProjectDir\\AtenaResults.gidflavia.msh"
 GiD_Process escape escape escape escape Postprocess
 return ""
}
 
proc getStepNumber { StepIndex } {

if { $StepIndex < 10 } {
 return "000$StepIndex"
 }

if { $StepIndex < 100 } {
 return "00$StepIndex"
 }
 
if { $StepIndex < 1000 } {
 return "0$StepIndex"
 }
 
 return "$StepIndex"
}

proc TK_Check_Interval_Times { event args } {

 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  set st [DWLocalGetValue $GDN $STRUCT INTERVAL_STARTING_TIME]
  set n [GidConvertValueUnit $st]
  set n [ParserNumberUnit $n st unit]

  set et [DWLocalGetValue $GDN $STRUCT INTERVAL_END_TIME]
  set n [GidConvertValueUnit $et]
  set n [ParserNumberUnit $n et unit]
  if { $st >= $et } {
         WarnWinText "Starting time have to be less then End time!"
         #set text "Starting time have to be less then End time!"
         #tk_messageBox -icon info -title [_ "Info:"] -type ok \
         #              -message "$text"
  }
  set oProblemtype [GiD_AccessValue get gendata "Calculation_Analysis"]
  set ostat3d [string equal $oProblemtype "Static"]
  set otransp3d [string equal $oProblemtype "Transport"]

#	  if { $ostat3d == 0 && $otransp3d == 0  } {
#	  set Stoptime [GiD_AccessValue get gendata "Stop_Time"]
#	  set n [GidConvertValueUnit $Stoptime ]
#	  set n [ParserNumberUnit $n Stoptime unit]
#	  if { $et > $Stoptime } {
#	          WarnWinText "INTERVAL_END_TIME=$et have to be less then Stop_Time=$Stoptime of ProblemData!"
		  #set text "INTERVAL_END_TIME=$et have to be less then Stop_Time=$Stoptime of ProblemData!"
		  #tk_messageBox -icon info -title [_ "Info:"] -type ok \
		  #		 -message "$text"
#	  }
#		  set currtime [GiD_AccessValue get gendata "CURRENT_TRANSIENT_TIME"]
#		  set n [GidConvertValueUnit $currtime ]
#		  set n [ParserNumberUnit $n currtime unit]
#		  if { $st < $currtime } {
#		    set text "INTERVAL_STARTING_TIME=$st have to be great then CURRENT_TRANSIENT_TIME=$currtime of ProblemData!"
#			  tk_messageBox -icon info -title [_ "Info:"] -type ok \
#					 -message "$text"
#		  }
#	  }
  # DWLocalSetValue $GDN $STRUCT $QUESTION $value
  return ""
 }
 CLOSE {
  # do nothing here
  return ""
 }
 }
 return ""
}

proc TK_Check_CS { oCS ooflagProjection } {
   # WarnWinText "1:ocs=$oCS"
   # prohozeni klicoveho slova kvuli oznaceni v GIDu
  if [string equal $oCS "GLOBAL_CONSTANT"] {
		set oCS "GLOBAL"
   # WarnWinText "2:ocs=$oCS"
	} 
	if { $ooflagProjection==0 } { 
		return $oCS 
	} 
}

proc TK_ElementNum { oflagElmIDMerge oElemsNum } { 
	if { $oflagElmIDMerge!=0 } {
		return "/* ELEMENT $oElemsNum */" 
	} else { 
		return "ELEMENT $oElemsNum" 
	} 
}

proc TK_BoundaryMerge { oflagElmIDMerge } { 
	if { $oflagElmIDMerge==0 } { 
		return "NO_ELEM_OUTPUT MULTIPLE YES" 
	} else { 
		return "MERGE MULTIPLE YES" 
	} 
}

proc TK_QUADRATIC_SETTING { event args } {
 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  set quadratic [GiD_Info Project Quadratic]
  DWLocalSetValue $GDN $STRUCT $QUESTION $quadratic
  return ""
  # $quadratic
 }
 CLOSE {
  # do nothing here
  return ""
 }
 }
 return ""
}

proc TK_Automatic_Beam_THICKNESS_Calculation { event args } {

 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  # WarnWinText "TK_Info G S Q"
  # WarnWinText $GDN
  # WarnWinText $STRUCT
  # WarnWinText $QUESTION

  set on [DWLocalGetValue $GDN $STRUCT "Automatic_THICKNESS_Calculation"]
  if { $on == 0 } {
  return ""
  }

  set RefThick [DWLocalGetValue $GDN $STRUCT "Beam_Ref_Size_t"]
  set RefHeight [DWLocalGetValue $GDN $STRUCT "Beam_Ref_Size_s"]

  set n1 [GidConvertValueUnit $RefThick]
  set n1 [ParserNumberUnit $n1 thickness unit]

  set n2 [GidConvertValueUnit $RefHeight]
  set n2 [ParserNumberUnit $n2 width unit]

  if {[string is double $thickness]} {
   set pomerVkuS [format %g [expr double($thickness*$width*1)/double(2*$width+2*$thickness)]]
   set on [DWLocalSetValue $GDN $STRUCT "THICKNESS" $pomerVkuS]
   if { $on < 0 } {
     WarnWin "THICKNESS is not changed by TK_WIDGET in proc TK_Automatic_Beam_THICKNESS_Calculation in TK_Utils.tcl"
   }
  } else {
  WarnWinText "Could not sync $QUESTION because Solid_Ref_Thick is not a real value"
  }
  return ""
 }
 CLOSE {
  # do nothing here
  return ""
 }
 }
 return ""
}

proc TK_Automatic_THICKNESS_Calculation { event args } {

 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  # WarnWinText "TK_Info G S Q"
  # WarnWinText $GDN
  # WarnWinText $STRUCT
  # WarnWinText $QUESTION

  set on [DWLocalGetValue $GDN $STRUCT "Automatic_THICKNESS_Calculation"]
  if { $on == 0 } {
  return ""
  }

  set RefThick [DWLocalGetValue $GDN $STRUCT "Solid_Ref_Thick"]

  set n [GidConvertValueUnit $RefThick]
  set n [ParserNumberUnit $n thickness unit]

  if {[string is double $thickness]} {
   # set pomerVkuS [format %g [expr double($thickness*1*1)/double(4*$thickness*1+2*1*1)]]
   set pomerVkuS [format %g [expr double($thickness*1*1)/double(2*1*1)]]
   set on [DWLocalSetValue $GDN $STRUCT "THICKNESS" $pomerVkuS]
   if { $on < 0 } {
     WarnWin "THICKNESS is not changed by TK_WIDGET in proc TK_Automatic_THICKNESS_Calculation in TK_Utils.tcl"
   }
  } else {
  WarnWinText "Could not sync $QUESTION because Solid_Ref_Thick is not a real value"
  }
  return ""
 }
 CLOSE {
  # do nothing here
  return ""
 }
 }
 return ""
}

proc TK_set_Minimum_Embedded_Reinforcement { event args } {

 switch $event {
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  # WarnWinText "TK_Info G S Q"
  # WarnWinText $GDN
  # WarnWinText $STRUCT
  # WarnWinText $QUESTION

  set Geom [DWLocalGetValue $GDN $STRUCT "Geom_Type"]
  set Mini [DWLocalGetValue $GDN $STRUCT "Minimum"]
  
  #WarnWinText $Geom
  #WarnWinText $Mini
  
  set n [GidConvertValueUnit $Mini]
  set n [ParserNumberUnit $n thickness unit]
  
  #WarnWinText $thickness
  #WarnWinText $unit
  
  if { $Geom == "NORMAL" || $Geom == "BAR_WITH_BOND" || $Geom == "BAR_WITH_MEMORY_BOND" || $Geom == "INTERNAL_CABLE" } {
     if { $thickness > 100 } {
       WarnWin "The minimum bar segment length is set to $Mini, which is extremely large for GeomType = $Geom. Please check/correct. The recommended minimum is a length comparable to the volume elements' size or smaller. \n The default value is 0.001m."
     }
  }  
  return ""
  return ""
  }
  }
}

proc TK_Signal { elemsnum } {
  GiD_Process Mescape utilities SignalEntities Elements $elemsnum
  return ""
}

proc TK_Check_Chlorides_time_function { event args } {
 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

    set Calculation_Analysis [GiD_AccessValue get gendata Calculation_Analysis]
    set Activate_Total_Function [DWLocalGetValue $GDN $STRUCT Activate_Total_Function]
    #WarnWinText "Calculation_Analysis=$Calculation_Analysis"
    #WarnWinText "Activate_Total_Function=$Activate_Total_Function"
    
    if { [string equal $Calculation_Analysis "Dynamic"] || [string equal $Calculation_Analysis "Creep"] } {
       if { [string equal $Activate_Total_Function "NO"] } {
           } else {
              WarnWinText "For Problemtype $Calculation_Analysis is not allowed to use time function"
           } 
    }
    if { [string equal $Calculation_Analysis "Static"] } {
       if { [string equal $Activate_Total_Function "NO"] } {
              WarnWinText "For Problemtype $Calculation_Analysis you have to use time function"
           } 
    }    
       return ""
  }
 CLOSE {
  # do nothing here
  return ""
 }
 }
 return ""
}

proc TK_UpdateNumberFromNonlinearMultipleSteps { event args } {
 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

#  WarnWinText "TK_Info G S Q"
#  WarnWinText $GDN
#  WarnWinText $STRUCT
#  WarnWinText $QUESTION

  #set current [GiD_IntervalData set]
  #set onls [GiD_AccessValue get IntvData $current Define_Loading_History]
  set onls [DWLocalGetValue $GDN $STRUCT Define_Loading_History]

  if { $onls == 0 } { 
  	return "" 
  }
  #set value [GiD_AccessValue get IntvData $current Incremental_Multiplicators]
  set value [DWLocalGetValue $GDN $STRUCT Incremental_Multiplicators]
  # WarnWinText $value

  if { $onls == 1 } {
    set on [GiD_AccessValue get gendata Calculation_Analysis]
    # if [string equal $on "Static"] || [string equal $on "Transport"] 
    # elseif [string equal $on "Creep"]  || [string equal $on "Dynamic"]
       set on [expr [lindex $value 1]/2 -1]
       #WarnWinText "1:on=$on"
       # set on [GiD_AccessValue set IntvData $current $QUESTION $on]
       # WarnWinText "2:on=$on"
       set on [DWLocalSetValue $GDN $STRUCT $QUESTION $on]
       #WarnWinText "3:on=$on"
  }
  return ""
 }
 CLOSE {
  # do nothing here
  return ""
 }
 }
 return ""
}


proc TK_UpdateStepMultiplier { event args } {
 switch $event {
   SYNC {
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
  
    set Activate_Step_multiplier [DWLocalGetValue $GDN $STRUCT Activate_Step_multiplier]
    if { $Activate_Step_multiplier == 0 } { 
    	return "" 
    }
  
    set Step_Multiplier [DWLocalGetValue $GDN $STRUCT Step_Multiplier]
    set Number_of_Load_Steps [DWLocalGetValue $GDN $STRUCT Number_of_Load_Steps]
    set Interval_Multiplier [DWLocalGetValue $GDN $STRUCT Interval_Multiplier]
    # WarnWinText $value
  
    if { $Activate_Step_multiplier == 1 } {
      set intervalmultip [expr $Step_Multiplier * $Number_of_Load_Steps]
      set on [DWLocalSetValue $GDN $STRUCT Interval_Multiplier $intervalmultip]
         #WarnWinText "3:on=$on"
    }
    return ""
   }
 }
 return ""
}

proc TK_UpdateStepMultiplier_for_FIXED { event args } {
 switch $event {
   SYNC {
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
  
    set Activate_Step_multiplier [DWLocalGetValue $GDN $STRUCT Activate_Step_multiplier_for_FIXED]
    if { $Activate_Step_multiplier == 0 } { 
    	return "" 
    }
  
    set Step_Multiplier [DWLocalGetValue $GDN $STRUCT Step_Multiplier_for_FIXED]
    set Number_of_Load_Steps [DWLocalGetValue $GDN $STRUCT Number_of_Load_Steps]
    set Interval_Multiplier [DWLocalGetValue $GDN $STRUCT Interval_Multiplier_for_FIXED]
    # WarnWinText $value
  
    if { $Activate_Step_multiplier == 1 } {
      set intervalmultip [expr $Step_Multiplier * $Number_of_Load_Steps]
      set on [DWLocalSetValue $GDN $STRUCT Interval_Multiplier_for_FIXED $intervalmultip]
         #WarnWinText "3:on=$on"
    }
    return ""
   }
 }
 return ""
}

proc TK_UpdateStepMultiplier_for_INCREMENT { event args } {
 switch $event {
   SYNC {
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
  
    set Activate_Step_multiplier [DWLocalGetValue $GDN $STRUCT Activate_Step_multiplier_for_INCREMENT]
    if { $Activate_Step_multiplier == 0 } { 
    	return "" 
    }
  
    set Step_Multiplier [DWLocalGetValue $GDN $STRUCT Step_Multiplier_for_INCREMENT]
    set Number_of_Load_Steps [DWLocalGetValue $GDN $STRUCT Number_of_Load_Steps]
    set Interval_Multiplier [DWLocalGetValue $GDN $STRUCT Interval_Multiplier_for_INCREMENT]
    # WarnWinText $value
  
    if { $Activate_Step_multiplier == 1 } {
      set intervalmultip [expr $Step_Multiplier * $Number_of_Load_Steps]
      set on [DWLocalSetValue $GDN $STRUCT Interval_Multiplier_for_INCREMENT $intervalmultip]
         #WarnWinText "3:on=$on"
    }
    return ""
   }
 }
 return ""
}

proc GoToPostProcessor { event args } {

 switch $event {
 DEPEND {
  return ""
 }
 INIT {
  return ""
 }
 CLOSE {
GiD_Process mescape Postprocess
  return ""
  }
 }
 }


proc Update_StepIndex_of_Incremental_Multiplicators { event args } {

 switch $event {
 DEPEND {
  return ""
 }
 INIT {
  return ""
 }
 CLOSE {
  #WarnWinText "close"
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  #set current [GiD_IntervalData set]
  set onls [DWLocalGetValue $GDN $STRUCT Define_Loading_History]
  if { $onls == 0 } { 
  	            return "" 
                    }
  #set value [GiD_AccessValue get IntvData $current Incremental_Multiplicators]
  set value [DWLocalGetValue $GDN $STRUCT Incremental_Multiplicators]
  set on [lindex $value 1]
  set array "#N# 0"
	for {set i 2 } { $i <= $on } { set i [expr $i + 2] } {
	  set stepindex [lindex $value $i]
	  set multiplier [lindex $value [expr $i+1]]
	  set array [AddItem2Array $array [expr $i/2 -1]]
	  set array [AddItem2Array $array $multiplier ]
	  }
  set on [DWLocalSetValue $GDN $STRUCT Incremental_Multiplicators $array]

  return ""
 }















 SYNC {

 set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

   #WarnWinText "TK_Info_close G S Q"
   #WarnWinText $GDN
   #WarnWinText $STRUCT
   #WarnWinText $QUESTION

  #set current [GiD_IntervalData set]
  #WarnWinText "current:$current"
  set onls [DWLocalGetValue $GDN $STRUCT Define_Loading_History]
  # set onls [GiD_AccessValue get IntvData $current Define_Loading_History]
  #WarnWinText "onls:$onls"
  if { $onls == 0 } { 
  	return "" 
  }

  #set value2 [DWLocalGetValue $GDN $STRUCT $QUESTION]
  set value [DWLocalGetValue $GDN $STRUCT Incremental_Multiplicators]
  #set value [GiD_AccessValue get IntvData $current Incremental_Multiplicators]
  #set value [DWLocalGetValue $GDN $STRUCT Incremental_Multiplicators]
  #set value2 [GiD_AccessValue get IntvData $current Incremental_Multiplicators]
  #WarnWinText "1:$value"
  #WarnWinText "2:$value2"
  #return ""

  set on [lindex $value 1]
  set array "#N# 0"

  set startvalueunit [DWLocalGetValue $GDN $STRUCT INTERVAL_STARTING_TIME]
  set n1 [GidConvertValueUnit $startvalueunit]
  set n1 [ParserNumberUnit $n1 value1 unit1]

  set endvalueunit [DWLocalGetValue $GDN $STRUCT INTERVAL_END_TIME]
  set n2 [GidConvertValueUnit $endvalueunit]
  set n2 [ParserNumberUnit $n2 value2 unit2]
  
  set zpusob [DWLocalGetValue $GDN $STRUCT Type_of_Definition]  
  if { $zpusob == "Automatic" } {
    	set sinamplituda [DWLocalGetValue $GDN $STRUCT Amplitude_SIN_Main]
	set sinstepu  [DWLocalGetValue $GDN $STRUCT Number_of_Intervals_per_Wave]
	set sinnumberofwave [DWLocalGetValue $GDN $STRUCT Number_of_Waves_SIN_Main]
	set sinstart [DWLocalGetValue $GDN $STRUCT Start_<0-1>*2Pi_SIN_Main]
	set sinutlumfactor [DWLocalGetValue $GDN $STRUCT Logarithmic_Damping_Factor_SIN_Main]

	set sinfrek [DWLocalGetValue $GDN $STRUCT Frequency_SIN_Main]
  		set n1 [GidConvertValueUnit $sinfrek]
		set n1 [ParserNumberUnit $n1 sinfrek unit4]

	set sin2 [DWLocalGetValue $GDN $STRUCT Add_SIN2_Increment]
	set sinamplituda2 [DWLocalGetValue $GDN $STRUCT Amplitude_SIN2]
	set sinstart2 [DWLocalGetValue $GDN $STRUCT Start_<0-1>*2Pi_SIN2]
	set sinutlumfactor2 [DWLocalGetValue $GDN $STRUCT Logarithmic_Damping_Factor_SIN2]
	set sinfrek2 [DWLocalGetValue $GDN $STRUCT Frequency_SIN2]
  		set n5 [GidConvertValueUnit $sinfrek2]
		set n5 [ParserNumberUnit $n5 sinfrek2 unit5]

	set lineutlumfactor [DWLocalGetValue $GDN $STRUCT Logarithmic_Damping_Factor_LINE]
  		set n5 [GidConvertValueUnit $lineutlumfactor]
		set n5 [ParserNumberUnit $n5 lineutlumfactor unit5]

	set sinutlumkoeficient [expr log($sinutlumfactor)/double(360)]
	   #WarnWinText "utlumkoeficient : $utlumkoeficient "
  	set sinutlumkoeficient2 [expr log($sinutlumfactor2)/double(360)]
	   #WarnWinText "utlumkoeficient : $utlumkoeficient "   
  	set lineutlumkoeficient [expr log($lineutlumfactor)/double(1)]
	   #WarnWinText "lineutlumkoeficient : $lineutlumkoeficient " 

  if { $sinstepu <= 4 } {
  	                set sinstepu 4
                        }

   set nasobekfrekvenci [expr double($sinfrek2)/double($sinfrek)]
     #WarnWinText "nasobek frekvenci: $nasobekfrekvenci"

   if {$sin2==0} {set nasobekfrekvenci 1}
   if {$sinfrek2==0} {WarnWinText "Frequency have not to be zero !"
		      set nasobekfrekvenci 1
	 	     } 
   set uhelkrok  [expr double(360)/double($sinstepu*$nasobekfrekvenci)]
   set uhelstart [expr double(360*$sinstart)]
   set uhelstart2 [expr double(360*$sinstart2)]

   set uhelrozdil [expr $uhelstart2-$uhelstart]
     #WarnWinText "uhelstart2:$uhelstart2, uhelrozdil:$uhelrozdil"

   set multiplier_old 0



   for {set i 0 } { $i <= $sinstepu*$sinnumberofwave*2*$nasobekfrekvenci +1 } { set i [expr $i + 2] } {
	  set stepindex [lindex $value $i]
	  #set multiplier [lindex $value [expr $i+1]]

	  set uhel [expr double(($i)/2*$uhelkrok+$uhelstart)]
	  #set uhel [expr double(($i-2)/2*$uhelkrok+$uhelstart)]
	  set uhel2 [expr ($nasobekfrekvenci*($uhel-$uhelstart)+$uhelstart2)]
   	    #WarnWinText "($nasobekfrekvenci*($uhel-$uhelstart)+$uhelstart2) = $uhel2 ,  sin2= $sin2	  "

	  set multiplier [expr exp($sinutlumkoeficient*$uhel)*double($sinamplituda * sin($uhel*3.1415926535897932384/180))]
    	  set multipliersin2 [expr exp($sinutlumkoeficient2*$uhel2)*double($sinamplituda2 * sin($uhel2*3.1415926535897932384/180))]


	  if {$multiplier*$multiplier <= 0.0000001 } {set multiplier 0}
  	  set multiplier [format %g $multiplier]
	  #set multiplier $uhel	 

	  if {$multipliersin2*$multipliersin2 <= 0.0000001 } {set multipliersin2 0}
  	  set multipliersin2 [format %g $multipliersin2]

	  if {$sin2==1} {
			set multiplier [expr double($multiplier+$multipliersin2)]
			#set multiplier "sin2: $multiplier, sin2_mulitp:$multipliersin2"
			}

	  # *** pridani LINE
  	  set pridatline [DWLocalGetValue $GDN $STRUCT Add_Line_Increment]
	  if {$pridatline==1} {
	    set line_nasobitel [expr (($i/2)) * double($value2-$value1)/double($sinstepu*$sinnumberofwave*$nasobekfrekvenci)]

   	    set line_prirustek [DWLocalGetValue $GDN $STRUCT Inclination_<%_/_time>_LINE]
  		set n2 [GidConvertValueUnit $line_prirustek]
  		set n2 [ParserNumberUnit $n2 line_prirustek unit2]
  	    set line_konstanta [DWLocalGetValue $GDN $STRUCT Initial_value_<%>_LINE]

	    set line_pricist [expr exp($lineutlumkoeficient*$line_nasobitel)*($line_nasobitel*$line_prirustek + $line_konstanta)]
            #WarnWinText "line_nasobitel:$line_nasobitel, line_prirustek:$line_prirustek, line_konstanta:$line_konstanta, =: $line_pricist"

	  set multiplier [expr $multiplier + $line_pricist/100]
	  }
   


	  #vypocet incrementu
	  set multiplier2 [expr $multiplier - $multiplier_old]
  	  set multiplier2 [format %g $multiplier2]
	  set multiplier_old $multiplier
	  set multiplier [format %g $multiplier]
	  #set multiplier "$multiplier2 //total coeff = $multiplier"
	  set multiplier $multiplier2

	  set array [AddItem2Array $array [expr $i/2]]
	  #set array [AddItem2Array $array $uhel]
	  set array [AddItem2Array $array $multiplier ]
   }

    set numberofloadsteps [expr ($i/2)-3]
    set on [DWLocalSetValue $GDN $STRUCT Number_of_Intervals_per_Wave $sinstepu]
    set on [DWLocalSetValue $GDN $STRUCT Number_of_Load_Steps $numberofloadsteps]

    set on [DWLocalSetValue $GDN $STRUCT Incremental_Multiplicators $array]
    } else {
	# presunuto do CLOSE
	#  for {set i 2 } { $i <= $on } { set i [expr $i + 2] } {
	#  set stepindex [lindex $value $i]
	#  set multiplier [lindex $value [expr $i+1]]
	#  set array [AddItem2Array $array [expr $i/2 -1]]
	#  set array [AddItem2Array $array $multiplier ]
 	#  set on [DWLocalSetValue $GDN $STRUCT Incremental_Multiplicators $array]
	#  }
    }

  #WarnWinText "3:$array"




  # hodnoty casu nacitam nazacatku
  set sinnumberofwave [DWLocalGetValue $GDN $STRUCT Number_of_Waves_SIN_Main]
  set value [expr double($sinnumberofwave)/double($value2-$value1)]
  set value2 [expr 1/$value]
  #set valueunit [format %g $value]
  set valueunit [format %g%s $value "Hz"]
  set valueunit2 [format %g%s $value2 $unit1]

  set zmena_time [DWLocalGetValue $GDN $STRUCT Change_Interval_End_Time_By]

  if {$zmena_time=="Frequency"} {

  set chtena_hodnota [DWLocalGetValue $GDN $STRUCT Frequency_SIN_Main]
  set n2 [GidConvertValueUnit $chtena_hodnota]
  set n2 [ParserNumberUnit $n2 chtena_hodnota unit7]
  set chteny_end [expr (double($sinnumberofwave) / double($chtena_hodnota)) + $value1 ]
  #WarnWinText "provadim zmenu od wave pozadovany konec $chteny_end, hodnota: $chtena_hodnota, sin:$sinnumberofwave"
  set chteny_endunit [format %g%s $chteny_end $unit1]
  if {[string is double $chteny_end]} {
     if {$chteny_end>0} {set n [DWLocalSetValue $GDN $STRUCT INTERVAL_END_TIME $chteny_endunit]}
     } else {
     WarnWinText "Could not sync $QUESTION because INTERVAL_END_TIME is not a real value"
     }
   set n [DWLocalSetValue $GDN $STRUCT Wave-Length_SIN_Main $valueunit2]

  } elseif {$zmena_time=="Wave-Length"} {

  set chtena_hodnota [DWLocalGetValue $GDN $STRUCT Wave-Length_SIN_Main]
  set n2 [GidConvertValueUnit $chtena_hodnota]
  set n2 [ParserNumberUnit $n2 chtena_hodnota unit7]
  set chteny_end [expr double($sinnumberofwave) * double($chtena_hodnota) + $value1 ]
  #WarnWinText "provadim zmenu od wave pozadovany konec $chteny_end, hodnota: $chtena_hodnota, sin:$sinnumberofwave"
  set chteny_endunit [format %g%s $chteny_end $unit7]
  if {[string is double $chteny_end]} {
     if {$chteny_end>0} {set n [DWLocalSetValue $GDN $STRUCT INTERVAL_END_TIME $chteny_endunit]}
     } else {
     WarnWinText "Could not sync $QUESTION because INTERVAL_END_TIME is not a real value"
     }
  #WarnWinText "chteny_end:$chteny_end, value2:$value2, porovnani:$porovnani"
  #if {[string equal $chteny_end $value2]} { set n [DWLocalSetValue $GDN $STRUCT Change_Interval_End_Time_By "None"]}
   set n [DWLocalSetValue $GDN $STRUCT Frequency_SIN_Main $valueunit]

  } else {

  if {[string is double $value]} {
   set n [DWLocalSetValue $GDN $STRUCT Frequency_SIN_Main $valueunit]
   set n [DWLocalSetValue $GDN $STRUCT Wave-Length_SIN_Main $valueunit2]
     } else {
  WarnWinText "Could not sync $QUESTION because Frequency_SIN_Main is not a real value"
     }
  }

#konec ukladani Frequency_SIN_Main


  return ""
 }
 }
 return ""
}




























proc TK_Info { event args } {
# WarnWinText $args
# return ""

 switch $event {
 INIT {
  # do nothing here
  return ""
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  WarnWinText "TK_Info G S Q"
  WarnWinText $GDN
  WarnWinText $STRUCT
  WarnWinText $QUESTION

  set value [DWLocalGetValue $GDN $STRUCT $QUESTION]
  WarnWinText $value

  return ""
 }
 CLOSE {
  # do nothing here
  return ""
 }
 }
 return ""
}

proc AboutAtenaProblemType { } {
 global aptsplash
 global keepsplash
 set keepsplash 1
 Splash $aptsplash
 set keepsplash 0
}

proc Export3D_IXT {} {
 global problem_dir GiDProjectDir GiDProjectName
   GiD_Process escape escape escape escape Files WriteForBAS "$problem_dir/../include.src.bas/Export_3D_IXT.bas" 
#   \    exp_3D.ixt
}

proc ExportToPre {} {
 global problem_dir GiDProjectDir GiDProjectName
   GiD_Process escape escape escape escape Files WriteForBAS "$problem_dir/../include.src.bas/ExportToPre.bas" "$GiDProjectDir\\gid2pre.xml"
}
                                 

proc Atena_Menu { dir } {      
    GiDMenu::Create ATENA PRE -1        
    set labels [list [= "ATENA Analysis"] [= "Create .inp only"] "---" [= "Save and transform to latest scripts"] [= "Reinforcement Detection"] \
                                    [= "Export IXT file for ATENA 3D"] [= "Export to ATENA PRE beta"] "---" [= "GiD Post-processing"] [= "ATENA Studio Post-processing"]  "---" \
                                    [= "ATENA-GiD Manual"] [= "ATENA Science Manuals"] "---" [= "Check for Update of ATENA"] \
                                    [= "Visit www.cervenka.cz"] [= "About Problem type Version"]]
    set commands { {GiD_Process Escape Escape Escape Utilities Calculate} {VP_Create_Inp_Only } {} {DoTransform} {JN_BeforeMeshGeneration} \
                                       {Export3D_IXT} {ExportToPre} {} {TogglePrePost} {TK_Atena3DPostCall}  {} {spust_manual_gid} \
                                       {spust_manual} {} {ZJ_InitUpdateCheckProcess} \
                                       {VisitWeb "http://www.cervenka.cz"} {AboutAtenaProblemType} }
    set icons { menu_calc_stat16.gif menu_inp16.gif "" menu_script.gif menu_reinf16.gif menu_IXT_pc.gif menu_studio-logo.gif "" \
                                    menu_prepost16x16.gif menu_studio-logo.gif "" menu_help.gif menu_open16x16.gif "" menu_help.gif \
                                    menu_home.gif menu_file.gif }
    set pos 0
    foreach label $labels command $commands  icon $icons {
                set full_icon [file normalize [file join $dir .. Images $icon]]
                GiDMenu::InsertOption ATENA [list $label] $pos PRE $command "" $full_icon
                incr pos
    }
    GiDMenu::UpdateMenus
}


proc Atena_Menu2 { dir } {

 global NumMenus MenuNames MenuEntries MenuCommands MenuAcceler MenuIcons
 global MenuNamesP MenuEntriesP MenuCommandsP
 global VersionNumber ProgramName ProblemTypePriv
 global problem_dir
 global GidPriv
 

 if { [ lsearch $MenuNames ATENA] != -1} {
  return}
 set ihelp [ lsearch $MenuNames [_ "Help"]]

 if { $ihelp != -1} {
  set nuevomenu [ lrange $MenuNames 0 [expr $ihelp - 1]]
  set nuevomenu "$nuevomenu ATENA Help"
  set MenuNames $nuevomenu

  set nuevoHelpIDX [expr $ihelp + 1]
  set MenuEntries($nuevoHelpIDX) $MenuEntries($ihelp)
  set MenuCommands($nuevoHelpIDX) $MenuCommands($ihelp)
  set MenuAcceler($nuevoHelpIDX) $MenuAcceler($ihelp)

  set MenuEntries($ihelp) {  "ATENA Analysis 2" "Create .inp only" "---" "Save and transform to latest scripts" "Reinforcement Detection" "Export IXT file for ATENA 3D" "---" "GiD Post-processing" "ATENA Studio Post-processing"    "---" "ATENA-GiD Manual" "ATENA Science Manuals" "---" "Check for Update of ATENA" "Visit www.cervenka.cz" "About Problem type Version"}
  set MenuCommands($ihelp) { {-np- escape escape escape Utilities Calculate} {-np- VP_Create_Inp_Only } {} {-np- DoTransform} {-np- JN_BeforeMeshGeneration } {-np- Export3D_IXT} {} {-np- TogglePrePost} {-np- TK_Atena3DPostCall}  {} {-np- spust_manual_gid} {-np- spust_manual} {} {-np- ZJ_InitUpdateCheckProcess} {-np- VisitWeb "http://www.cervenka.cz"} {-np- AboutAtenaProblemType} }
  set MenuAcceler($ihelp) { "" }
 # set MenuIcons($ihelp) { "../Problemtypes/Atena/Images/menu_calc_stat16.gif" "../Problemtypes/Atena/Images/menu_inp16.gif" "" "../Problemtypes/Atena/Images/menu_script.gif" "../Problemtypes/Atena/Images/menu_reinf16.gif" "../Problemtypes/Atena/Images/menu_IXT_pc.gif" "" "../Problemtypes/Atena/Images/menu_prepost16x16.gif" "../Problemtypes/Atena/Images/menu_3d-logo.gif" "" "../Problemtypes/Atena/Images/menu_help.gif" "../Problemtypes/Atena/Images/menu_open16x16.gif" "" "../Problemtypes/Atena/Images/menu_help.gif" "../Problemtypes/Atena/Images/menu_home.gif"  "../Problemtypes/Atena/Images/menu_file.gif"}
  set MenuIcons($ihelp) ""
foreach filename {menu_calc_stat16.gif menu_inp16.gif "" menu_script.gif menu_line.gif menu_reinf16.gif menu_IXT_pc.gif "" menu_prepost16x16.gif menu_studio-logo.gif "" menu_help.gif menu_open16x16.gif "" menu_help.gif menu_home.gif menu_file.gif} {
  if { $filename == "" } {
      lappend MenuIcons($ihelp) ""
  } else {
      lappend MenuIcons($ihelp) [file join $dir .. Images $filename]
  }
}
  
  CreateTopMenus
 } else {
  WarnWin [= "Couldn't find place to insert ATENA menu!"]
  return
 }
}

# {-np- VisitWeb "%AtenaSciDocPath%\\\\Atena-GID Users Manual.pdf"}
# {-np- VisitWeb "problemtypes/Atena/Help/spust.bat"}
proc spust_manual { } {
 eval exec [auto_execok start] "explorer %AtenaSciDocPath%" 
}

proc spust_manual_gid { } {
 #eval exec [auto_execok start] "%AtenaSciDocPath%\\\\Atena-GID Users Manual.pdf"
 eval exec [auto_execok start] \"\" "%AtenaGidManual%" 
}


proc DoTransform {} {
  global GIDDEFAULT
  cd $GIDDEFAULT
  set aa [GiD_Info Project]
  set ProblemType [lindex $aa 0]
  set ProblemType [string map {"\\" "\/"} $ProblemType]
  # WarnWinText $ProblemType
  
   GiD_Process escape escape escape Files Save

  global VersionNumberOnly VersionNumber
  #source "Problemtypes\\Atena\\include.src.bas\\Ver_number.tcl"
  set answer [GiD_Info gendata]
  # WarnWinText "$answer"
  if [ string match -nocase "*Script_Version*" $answer ] {
    # WarnWinText "ano"
    set Exampleversion [GiD_AccessValue get gendata "Script_Version"]
  } else {
    # WarnWinText "ne"
    set Exampleversion 0
  }
  #GiD_Process Mescape Files Save 
  GiD_Process Mescape Data Defaults TransfProblem "$ProblemType"
  #GiD_Process Mescape Files Save
  Kontrolanovinek $Exampleversion $VersionNumberOnly
}

proc JN_AfterTransformProblemType { file oldproblemtype newproblemtype } {

#WarnWinText $oldproblemtype 
#WarnWinText $newproblemtype 

 set ostat [string equal $oldproblemtype "Atena_2025/Static"]
 set ocreep [string equal $oldproblemtype "Atena_2025/Creep"]
 set otemp [string equal $oldproblemtype "Atena_2025/Transport"]
 set odyn [string equal $oldproblemtype "Atena_2025/Dynamic"]


 set nstat [string equal $newproblemtype "Atena_2025/Static"]
 set ncreep [string equal $newproblemtype "Atena_2025/Creep"]
 set ntemp [string equal $newproblemtype "Atena_2025/Transport"]
 set ndyn [string equal $newproblemtype "Atena_2025/Dynamic"]
 
#  WarnWinText "After"
#  WarnWinText [GiD_Info unitssystems prbsys]
  set ::UnitSystemAfterMesh [GiD_Info unitssystems prbsys]
  
#  WarnWinText "before 2"
#  WarnWinText $::UnitSystemBeforeMesh
#  WarnWinText "After 2"
#  WarnWinText $::UnitSystemAfterMesh
  
if {[info exists ::UnitSystemAfterMesh]} {
	#WarnWinText "UnitSystemAfterMesh existuje" 
  if {[info exists ::UnitSystemBeforeMesh]} {

    if { $::UnitSystemBeforeMesh == $::UnitSystemAfterMesh } {
    #WarnWinText "stejne"
    } else {
    set ::ModUnitWin::CurSysName $::UnitSystemBeforeMesh
    updmdlunits
    }  
  
    set ::UnitSystemAfterMesh2 [GiD_Info unitssystems prbsys]
  
    if { $::UnitSystemBeforeMesh == $::UnitSystemAfterMesh2 } {
    #WarnWinText "stejne"
    } else {
      WarnWinText "WARNING ! -> During transformation, your base unit system has been changed to $::UnitSystemAfterMesh2. Please set it manually back to $::UnitSystemBeforeMesh"
    }
#	WarnWinText "UnitSystemBeforeMesh existuje" 
  } else {
#	WarnWinText "UnitSystemBeforeMesh neexistuje" 
  }
} else {
	#WarnWinText "UnitSystemAfterMesh neexistuje" 
}



  
  
#                set value LENGTH
#                set magnitudes [GiD_Info magnitudes 1]
#                if { [lsearch $magnitudes $value] == -1 } {
#                    error "valid magnitudes are: $magnitudes"
#                }
#                lassign [MenuUnits::GetListsUnitsDataFroMenu $value] UnitsList UInfoList
#                set result [MenuUnits::GetListUnits $UnitsList]  
#  
#  WarnWinText $result
#  
#  #set length_units [GiD_Units get magnitude_units LENGTH]
#  set pos [lsearch $result $value]
#  if { $pos == -1 } {
#     error "valid units are: $length_units"
#  }
#
#  lassign [MenuUnits::GetListsUnitsDataFroMenu LENGTH] UnitsList UInfoList
#  set ::ModUnitWin::LengthInfo [lindex $UInfoList $pos]
#  updmdlunits  
  
  
  #WarnWinText [GiD_Info unitssystems prbsys]


  if { $ncreep==1 && $ostat==1 } {
    WarnWin [= "All condition with ApplyInSubIncrement=1 was lost!!! \n Usually it is Displacement_for_, Constraints_for_ and Fixed_Contact_for_. \n Please set this Boundary Condition again!"]
  } elseif { $nstat==1 && $ocreep==1 } {
    WarnWin [= "All condition with ApplyInSubIncrement=1 was lost!!! \n Usually it is Displacement_for_, Constraints_for_ and Fixed_Contact_for_. \n Please set this Boundary Condition again!"]
  }
  
  
  #oprava prehozeni  Material_Activity na Material_Activity_Step
  set n_intv [lindex [GiD_Info IntvData NUM] 1]
  for { set i 1 } { $i <= $n_intv } { set i [expr $i + 1] } {
    GiD_IntervalData set $i
    
    set oldtablemax [lindex [GiD_AccessValue get intvdata Material_Activity] 1]
    set newtablemax [lindex [GiD_AccessValue get intvdata Material_Activity_Step] 1]
    #WarnWinText "interval=$i, oldtablemax=$oldtablemax,newtablemax=$newtablemax "
    
    if { $oldtablemax > 0 && $newtablemax == 0} {
      set oldtable [lrange [GiD_AccessValue get intvdata Material_Activity] 2 end]
      set newtable [lrange [GiD_AccessValue get intvdata Material_Activity_Step] 2 end]
      #WarnWinText "oldtable = $oldtable"
      #WarnWinText "newtable = $newtable"
      set ret ""
      set NumCells 0
      foreach {old_material_name2 new_material_name2 reset2} $oldtable {
         lappend ret $old_material_name2
         lappend ret $new_material_name2
         lappend ret $reset2
         lappend ret "1"
         set NumCells [expr $NumCells+4]
      }
      set array "#N# $NumCells $ret"
      #WarnWinText $array
      GiD_AccessValue set intvdata Material_Activity_Step $array
      GiD_AccessValue set intvdata Material_Activity "#N# 0"
      } 
      #set oldtable [lrange [GiD_AccessValue get intvdata Material_Activity] 2 end]
      #set newtable [lrange [GiD_AccessValue get intvdata Material_Activity_Step] 2 end]
      #WarnWinText "oldtable = $oldtable"
      #WarnWinText "newtable = $newtable"      
    }
    
    
    #projiti materialu beam a kontrola jeho Element_Type
    foreach matname [GiD_Info materials] {
    #WarnWinText "---------"
    #WarnWinText "$matname"
      set prototype [GiD_AccessValue get materials $matname "Material_Prototype"]
         if { $prototype == "CCBeam3DMaterial" } {
             #WarnWinText "prototype = $prototype"
             set elementtype [GiD_AccessValue get materials $matname "Element_Type"]
             #WarnWinText "elementtype = $elementtype"
             if { $elementtype != "CCIsoBeamBrick12_3D" } {
                 set elementtype [GiD_AccessValue get materials $matname "Element_Type"]
                 GiD_AccessValue set material $matname "Element_Type" "CCIsoBeamBrick12_3D"
                 #WarnWinText "menim elementtype = CCIsoBeamBrick12_3D"
             }                   
         }
   }
    
  GiD_IntervalData set 1
  return ""
}

proc SwapSurfaceNormalsOppositeTo { requirednormal } {
  set ids ""
  foreach id [ GiD_Geometry list surface 1:] {
    set normal [GiD_Info Parametric Surface $id Normal 0.5 0.5]
    if { [MathUtils::VectorDotProd $normal $requirednormal] < 0.0 } {
      lappend ids $id
    }
  }
  if { $ids != "" } {
    GiD_Process MEscape Utilities SwapNormals Surfaces Select {*}$ids Escape
  }
}

proc GetLinesWithMaterialNoMesh { } {
   set ids_warning [list]
   foreach id [GiD_Geometry list line 1:end] {
       set data [GiD_Info list_entities lines $id]
       if { [regexp {material: ([0-9]+)} $data dummy material] && $material } {
           if { [regexp {HigherEntity: ([0-9]+)} $data dummy higherentity] && $higherentity } {
               if { ![regexp {Meshing=Yes} $data dummy] } {
                   lappend ids_warning $id
               }
           }
       }
   }
   return $ids_warning
} 

proc PreExportPoints { } {
   set ids_warning ""
   foreach id [GiD_Geometry list point 1:end] {
       set data [GiD_Info list_entities point $id]
       set b [regexp {([+-]?([0-9]*[.])?[0-9]+) ([+-]?([0-9]*[.])?[0-9]+) ([+-]?([0-9]*[.])?[0-9]+)} $data dummy coord_x coord_y coord_z]
       #append ids_warning $data
       #if { [regexp {STLINE} $data dummy]} {
         append ids_warning "POINT $id $dummy \n"
        # append ids_warning "POINT $id $coord_x $coord_y $coord_z \n"
       #} else {
       #  append ids_warning "??  $id $pointA $pointB \n"
       #}
   }
   return $ids_warning
} 

proc PreExportLines { } {
   set ids_warning ""
   foreach id [GiD_Geometry list line 1:end] {
       set data [GiD_Info list_entities line $id]
       set b [regexp {Points: ([0-9]+) ([0-9]+)} $data dummy pointA pointB]
       if { [regexp {STLINE} $data dummy]} {
         append ids_warning "STLINE $id $pointA $pointB \n"
       } else {
         append ids_warning "??  $id $pointA $pointB \n"
       }
   }
   return $ids_warning
} 

proc PreExportMaterials { } {
   set txt ""
   foreach mat_name [GiD_Info materials] {
       set mat_id [TK_FindMaterialNumber $mat_name "PreExportMaterials"]
       set data [GiD_Info materials $mat_name]
       
       append txt "\n\nMATERIAL $mat_id $mat_name\n"
       set values [lrange $data 1 end]
       foreach {key value} $values {
       append txt "$key = $value \n"
       }
       append txt "\n"
       #append txt $data
       #append txt "\n\n otherfields \n "
       #set data [GiD_Info materials $mat_name otherfields]
       #append txt $data
   }
   return $txt
} 

proc GetSurfacesWithMaterialNoMesh { } {
   set ids_warning [list]
   foreach id [GiD_Geometry list surface 1:end] {
       set data [GiD_Info list_entities surfaces $id]
       if { [regexp {material: ([0-9]+)} $data dummy material] && $material } {
           if { [regexp {HigherEntity: ([0-9]+)} $data dummy higherentity] && $higherentity } {
               if { ![regexp {Meshing=Yes} $data dummy] } {
                   lappend ids_warning $id
               }
           }
       }
   }
   return $ids_warning
} 

proc JN_BeforeMeshGeneration { } {
  BeforeMeshGeneration 1.0
}

proc SaveGIDProject { filespd } {
  loadGlobals $filespd 
}
 
proc MyCalculateNdime { } {
    set ndime 3
    lassign [lindex [GiD_Info layers -bbox] 0] x1 y1 z1 x2 y2 z2
    set tolerance 1e-7
    if { abs($z1) <= $tolerance && abs($z2) <= $tolerance } {
        set ndime 2
        #WarnWinText "$z1 $z2"
    }
    #set a [GiD_Info layers -bbox]
    #WarnWinText "$a"
    return $ndime
}

proc BeforeMeshGeneration { elementsize } {
#check units
  #WarnWinText [GiD_Info unitssystems modunit]
  set unit_set [GiD_Info unitssystems prbsys]
  lassign [GiD_Info unitssystems modunit] magnitude_name unit_index set_index
  set model_length_unit [lindex [GiD_Info magnitudes $set_index $magnitude_name $unit_index] 1]
  #WarnWinText $model_length_unit
  #WarnWinText $unit_set
  #WarnWinText [GiD_Info unitssystems magused LENGTH]        
  set units_length_unit [GidGetUnitStr length] 
  if {$model_length_unit != $units_length_unit} {
  WarnWinText "Warning: Model Unit (  $model_length_unit  ) is different than length unit in base system(  $units_length_unit  ). Please check it in Data ->Data units"
  }
#check units


 set QuickMesher [GiD_AccessValue get gendata "QuickMesher"]
 if {$QuickMesher==1} {
  return
 }
 set CalculationAnalysis [GiD_AccessValue get gendata "Calculation_Analysis"]
 set AutomaticAssignationLinesReinf [GiD_AccessValue get gendata "Automatic_Reinforcement_Identification"]

#  WarnWinText "BeforeMeshGeneration ... $CalculationAnalysis"

 set ostat3d [string equal $CalculationAnalysis "Static"]
 set ocree3d [string equal $CalculationAnalysis "Creep"]
 set odyna3d [string equal $CalculationAnalysis "Dynamic"]
 set otransp3d [string equal $CalculationAnalysis "Transport"]
 

  set maxvolumes [GiD_Info Geometry NumVolumes]
#   WarnWin "maxvolumes = $maxvolumes"

set nDim [MyCalculateNdime] 
#WarnWin "nDim = $nDim"
 if {$nDim==2 && $maxvolumes==0 } {    
     SwapSurfaceNormalsOppositeTo {0 0 1}
}

# set nlines [GiD_Info Geometry NumLines]
# if { $nlines > 1000 } {
#   return ""
# }

# WarnWinText "$ostat3d $odyna3d $ocree3d $otransp3d"
 if { $AutomaticAssignationLinesReinf==1 } {
   if {$ostat3d==1 || $ocree3d==1 || $odyna3d==1 } {
     set val 0
     set sel "1:end"
     set cond Reinforcement_Elems_Identification
     set n_intv [lindex [GiD_Info IntvData NUM] 1]

     set varovani [GetLinesWithMaterialNoMesh ]
     if { $varovani!="" } {
     WarnWinText "Error!: These lines have a material assigned, but no mesh is generated for them: $varovani \n ... Please assign Mesh -> Mesh Criteria -> Mesh -> Lines."
     }
     
     set varovani [GetSurfacesWithMaterialNoMesh ]
     if { $varovani!="" } {
     WarnWinText "Error!: These surfaces have a material assigned, but no mesh is generated for them: $varovani \n ... Please assign Mesh -> Mesh Criteria -> Mesh -> Surfaces."
     }     
      
#      WarnWinText "GiD_Info IntvData NUM = $n_intv "
     
     for { set i 1 } { $i <= $n_intv } { set i [expr $i + 1] } {
 	     GiD_IntervalData set $i
       
            if { [GidUtils::VersionCmp 13.1.6d] >= 0 } {
            GiD_UnAssignData condition $cond Lines 1:end
            GiD_AssignData condition $cond Lines $val [GiD_Geometry list -higherentity 0 line]
            } else {
            GiD_Process Mescape data cond assign $cond deleteAll yes escape
            GiD_Process Mescape Data Conditions AssignCond $cond Change $val Filter:HIGHERENTITY=0 $sel escape escape
                }
       
#       GiD_Process Mescape data cond assign $cond deleteAll yes escape
#	     GiD_Process Mescape Data Conditions AssignCond $cond Change $val Filter:HIGHERENTITY=0
#	     GiD_Process $sel escape escape
     }

#    set nassigned [eval GiD_AssignData condition $cond lines $val $sel ]
#    if { $nassigned <= 0 } {
#       WarnWinText "WARNING: condition $cond val=$val can not be assigned for lines $sel"  }

     set cond Reinforcement_Nodes_Identification
     for { set i 1 } { $i <= $n_intv } { set i [expr $i + 1] } {     
 	     GiD_IntervalData set $i
#	     GiD_Process Mescape data cond assign $cond deleteAll yes escape

              if { [GidUtils::VersionCmp 13.1.6d] >= 0 } {
              GiD_UnAssignData condition $cond Lines 1:end
              GiD_AssignData condition $cond Lines $val [GiD_Geometry list -higherentity 0 line]
              } else {
              GiD_Process Mescape data cond assign $cond deleteAll yes escape
              GiD_Process Mescape Data Conditions AssignCond $cond Change $val Filter:HIGHERENTITY=0 $sel escape escape
                  }
#       GiD_Process Mescape Data Conditions AssignCond $cond Change $val Filter:HIGHERENTITY=0
#	     GiD_Process $sel escape escape
       
     }
     
#    set nassigned [eval GiD_AssignData condition $cond lines $val $sel ]
#    if { $nassigned <= 0 } {
#       WarnWinText "WARNING: condition $cond val=$val can not be assigned for lines $sel" }
   }
 }
 
 
 
zj_test_check_contact_material
#enrique_test_check_contact_material // only version >15
#enrique_test_check_contact_material_v14     // only version >14
 
MyZapisElementGroupInactiveCheck

} 
 


proc zj_test_check_contact_material { } { 

#    foreach mat_name [GiD_Info materials] {
#       set mat_id [TK_FindMaterialNumber $mat_name "TK_FindMaterialNameById"]
#        WarnWinText "MatList $mat_id $mat_name"
#       }

#set t_start [clock milliseconds]
# kontrola jestli contact volume nema prirazenou neco jineho nez interface material 
foreach idvol [GiD_Geometry list volume 1:end] {
                set txt [GiD_Info list_entities volumes $idvol]
                #WarnWinText "-------"
                #WarnWinText $txt 
                #regexp {Num: ([0-9]+)\n} $txt dummy volumenum
                regexp {NumSurfaces: ([0-9]+)\n} $txt dummy surfacenum
                
                if { $surfacenum == 2 } {
                    regexp {material: ([0-9]+)\n} $txt dummy matnum                
                    set prototype [TK_FindMaterialPrototypeNum $matnum ]
                    #WarnWinText $idvol
                    #WarnWinText $matnum     
                    #WarnWinText $surfacenum
                    #WarnWinText $prototype
                    #WarnWinText $prototype2
                    #WarnWinText $mat2N 
                    if { $surfacenum == 2 && $prototype!="CC3DInterface"} {
                        set matname [TK_FindMaterialNameById $matnum]
                        #tk_messageBox -title "Colision in material prototype" \
                        #-message "Volume $idvol is contact volume and has different material prototype ($prototype) than CC3DInterface"
                        WarnWinText "ERROR: Volume $idvol is contact volume and has different material ($matname) prototype ($prototype) than CC3DInterface (matnum=$matnum, surfacenum=$surfacenum)" 
                    }
                }
    }
    
foreach idsur [GiD_Geometry list surface 1:end] {
                set txt [GiD_Info list_entities -more surface $idsur]
                set surfArea "nic"
                #set surfArea2 "nic"
                #WarnWinText "-------"
                #WarnWinText $txt 
                #regexp {Num: ([0-9]+)\n} $txt dummy volumenum
                regexp {NumLines: ([0-9]+)\n} $txt dummy linesnum
                          
                if { $linesnum == 2 } {      
                regexp {material: ([0-9]+)\n} $txt dummy matnum
                #regexp {Area=([0-9]*\.?[0-9]*)\n} $txt dummy surfArea
                regexp {Area=([0-9]*\.?[0-9]*(e-*[0-9]*)*)\n} $txt dummy surfArea                                    
                set prototype [TK_FindMaterialPrototypeNum $matnum ]
                #WarnWinText $idsur
                #WarnWinText $matnum
                #WarnWinText $surfArea 
                #WarnWinText $surfArea2     
                #WarnWinText $linesnum
                #WarnWinText $prototype
                #WarnWinText "**************"
                if { $linesnum == 2 && $surfArea<0.000000001 && $prototype!="CC2DInterface"} {
                    set matname [TK_FindMaterialNameById $matnum]
                    #tk_messageBox -title "Colision in material prototype" \
                    #-message "Volume $idvol is contact volume and has different material prototype ($prototype) than CC3DInterface"
                    WarnWinText "ERROR: Surface $idsur is probably contact surface and has different material ($matname) prototype ($prototype) than CC2DInterface" 
                    }
                }
              }   

#my_test_check_contact_material
    
#set t_end [clock milliseconds]    
#set t [expr $t_end - $t_start]
#WarnWinText $t
    
   
 
 # WarnWinText "... finished"
    }



proc enrique_test_check_contact_material { } { 
    set contact_volumes_without_material [list] 
    set contact_volumes_bad_prototype_field_value [list]
    foreach idvol [GiD_Geometry list -entity_type [list CONTACTVOLUME] volume] {
        set txt [GiD_Info list_entities volumes $idvol]      
        regexp {material: ([0-9]+)\n} $txt dummy matnum
        if { $matnum == 0 } {
            lappend contact_volumes_without_material $idvol                       
        } else {
            set prototype_field_value [GiD_AccessValue -index get materials $matnum Material_Prototype]
            if { $prototype_field_value!="CC3DInterface" } {           
                lappend contact_volumes_bad_prototype_field_value $idvol
            }
        }
    }
    if { [llength $contact_volumes_without_material] } {
        W [= "ERROR: %s contact volumes without material. Volume ids: %s" [llength $contact_volumes_without_material] $contact_volumes_without_material]       
    }
    if { [llength $contact_volumes_bad_prototype_field_value] } {
        W [= "ERROR: %s contact volumes with wrong material prototype field. Volume ids: %s" [llength $contact_volumes_bad_prototype_field_value] $contact_volumes_bad_prototype_field_value]
    }   
}

proc enrique_test_check_contact_material_v14 { } { 
    set contact_volumes_without_material [list] 
    set contact_volumes_bad_prototype_field_value [list]
    foreach idvol [GiD_Geometry list volume] {
        set volume_data [GiD_Geometry -v2 get volume $idvol]
        if { [lindex $volume_data 0] == "contactvolume" } {       
            set txt [GiD_Info list_entities volumes $idvol]      
            regexp {material: ([0-9]+)\n} $txt dummy matnum
            if { $matnum == 0 } {
                lappend contact_volumes_without_material $idvol                      
            } else {           
                #set material_index [expr $matnum-1] ;#matnum starts from 1, list index from 0
                #set matname [lindex [GiD_Info materials] $material_index]           
                #set prototype_field_value [GiD_AccessValue get materials $matname Material_Prototype]           
               set prototype_field_value [GiD_AccessValue -index get materials $matnum Material_Prototype]
                if { $prototype_field_value!="CC3DInterface" } {           
                    lappend contact_volumes_bad_prototype_field_value $idvol
                }
            }
        }
    }
    if { [llength $contact_volumes_without_material] } {
        W [= "ERROR: %s contact volumes without material. Volume ids: %s" [llength $contact_volumes_without_material] $contact_volumes_without_material]       
    }
    if { [llength $contact_volumes_bad_prototype_field_value] } {
        W [= "ERROR: %s contact volumes with wrong material prototype field. Volume ids: %s" [llength $contact_volumes_bad_prototype_field_value] $contact_volumes_bad_prototype_field_value]
    }   
}

proc positionWindow { w } {
 wm geometry $w +300+300
}

proc Abs_Dir { direction } {
  if { $direction == "+X" } {
    return "X"
  } elseif { $direction == "+Y" } {
    return "Y"
  } elseif {$direction == "+Z" } {
    return "Z"
  } elseif {$direction == "-X" } {
    return "X"
  } elseif {$direction == "-Y" } {
    return "Y"
  } elseif {$direction == "-Z" } {
    return "Z"
  }
  return ""
}

proc Signed_Val { direction values } {

  if {$direction == "-X" } {
    return [expr $values*-1]
  } elseif {$direction == "-Y" } {
    return [expr $values*-1]
  } elseif {$direction == "-Z" } {
    return [expr $values*-1]
  }
  return $values
}

proc Abs_Val { value } {

  if {$value <0 } {
    return [expr $value*-1.0]
  } 
  return $value
}

proc ClearLineNumForLineForce { } {
  GiD_AccessValue set gendata LineNumForLineForce "#N# 1 0"
  return ""
}

proc SetLineNumForLineForce { linenum } {
  set array [GiD_AccessValue get gendata LineNumForLineForce]
  set array [AddItem2Array $array $linenum]
  GiD_AccessValue set gendata LineNumForLineForce $array
  return ""
}

proc SortLineNumForLineForce { } {
  set array [GiD_AccessValue get gendata LineNumForLineForce]
  set ret ""
  set NumCells [lindex $array 1]
  for {set j 3} {$j <= [expr $NumCells+1]} {set j [expr $j+1]} {
    lappend ret [lindex $array $j]
  }

  set array [lsort -integer -unique $ret]
  set NumCells [llength $array]

  set array "#N# $NumCells $array"

  GiD_AccessValue set gendata LineNumForLineForce $array
  return ""
  # $array
}

proc JN4Strcat { strjedna strdva strtri strctiri } {
  set otemp "$strjedna$strdva$strtri$strctiri"
  GiD_AccessValue set gendata "temp" "$otemp"
  return "$otemp"
}

proc ZJ_Vymaz_temp { Value } {
  set otemp ""
  GiD_AccessValue set gendata "temp" "$otemp"
  return ""
}

proc ZJ_Uloz_temp { Value } {
  set otemp "$Value"
  GiD_AccessValue set gendata "temp" "$otemp"
  return ""
}

proc ZJ_Obsahuje_temp { Value } {
  set obsah [GiD_AccessValue get gendata "temp"]
  if [ string match -nocase $value $obsah ] {
    # WarnWinText "ano"
    return 1
  } else {
    # WarnWinText "ne"
    return 0
  }
}


proc Dialog_MyAssignSizesFunc { } {

 set w .cAssignment
 catch {destroy $w}
 toplevel $w
 wm title $w [= "Specify Element Size for Automatic Line Division"]
 positionWindow $w

 frame $w.principal
 label $w.principal.lElement_Size -text "Element_Size:" -width 10 -anchor w
 entry $w.principal.eElement_Size -width 10 -borderwidth 1 -insertborderwidth 1 -textvariable 1.0

 label $w.principal.lLayer_Name -text "Layer_Name:" -width 10 -anchor w
 entry $w.principal.eLayer_Name -width 10 -borderwidth 1 -insertborderwidth 1 -textvariable Layer0

 frame $w.buttons
 pack  $w.buttons -side bottom -fill x -pady 3m
 button $w.buttons.dismiss -text [= "Close"] -command "destroy $w"

 proc MyJN_AssignSizesFunc { w } {
  set elem_size [$w.principal.eElement_Size get]
  set layer_name [$w.principal.eLayer_Name get]
  if { $layer_name == "" } {
    MyAssignSizesFunc_EE $elem_size
  } else {
    MyAssignSizesFunc_JN $elem_size $layer_name
  }
 }

 button $w.buttons.code -text [= "Apply"] -command "MyJN_AssignSizesFunc $w"

 pack  $w.buttons.code $w.buttons.dismiss -side left -expand 1
 pack  $w.principal.lElement_Size $w.principal.eElement_Size \
    $w.principal.lLayer_Name  $w.principal.eLayer_Name -side left
 pack  $w.principal -side top -fill x

 focus $w.principal.eElement_Size
 bind $w <Return> "MyJN_AssignSizesFunc $w"
 bind $w <Escape> "destroy $w"
}

proc MyAssignSizesFunc_EE { elementsize } {
 foreach num [GiD_Geometry list line 1:] {
  set info [GiD_Info list_entities -more line $num]
  regexp {Length=(\S+)} $info dummy length
  set inum [format %d $num]
  set ndiv [expr {int($length/double($elementsize))}]
  if { $ndiv < 1 } {
   set ndiv 1
  }
  GiD_Process escape escape escape escape Meshing Structured Lines $ndiv $inum escape escape
 }
}

proc MyAssignSizesFunc_JN { elementsize layer_name } {
# foreach num [GiD_Geometry list line 1: layer:$layer_name]
 foreach num [GiD_Geometry list line 1: layer:$layer_name] {
  set info [GiD_Info list_entities -more line $num]
  regexp {Length=(\S+)} $info dummy length
  set inum [format %d $num]
  # set inum [expr int($num)]
  set ndiv [expr {int($length/double($elementsize))}]
  if { $ndiv < 1 } {
   set ndiv 1
  }
  GiD_Process escape escape escape escape Meshing Structured Lines $ndiv $inum escape escape
 }
}

proc VP_Create_Inp_Only { } {

 loadGlobals { "" }
 
 global problem_dir GiDProjectDir GiDProjectName
 set CalculationAnalysis [GiD_AccessValue get gendata "Calculation_Analysis"]

 set nstat3d [string equal $CalculationAnalysis "Static"]
 set ncreep3d [string equal $CalculationAnalysis "Creep"]
 set ntemp3d [string equal $CalculationAnalysis "Transport"]
 set ndyn3d [string equal $CalculationAnalysis "Dynamic"]


  file mkdir $GiDProjectDir/AtenaCalculation
  
  if { $nstat3d==1 } {
    GiD_Process escape escape escape escape Files WriteForBAS "$problem_dir/../Static.gid/Static.bas" "$GiDProjectDir/AtenaCalculation/$GiDProjectName.inp" \
  } elseif { $ncreep3d==1 } {
    GiD_Process escape escape escape escape Files WriteForBAS "$problem_dir/../Creep.gid/Creep.bas" "$GiDProjectDir/AtenaCalculation/$GiDProjectName.inp" \
  } elseif { $ntemp3d==1 } {
    GiD_Process escape escape escape escape Files WriteForBAS "$problem_dir/../Transport.gid/Transport.bas" "$GiDProjectDir/AtenaCalculation/$GiDProjectName.inp" \
  } elseif { $ndyn3d==1 } {
    GiD_Process escape escape escape escape Files WriteForBAS "$problem_dir/../Dynamic.gid/Dynamic.bas" "$GiDProjectDir/AtenaCalculation/$GiDProjectName.inp" \
  } else {
    WarnWin [= " Unknown problematype...:-) "]
  }
  
  GiD_Process escape escape escape Files WriteForBAS "$problem_dir\\..\\Execute\\template_run.bat" "$GiDProjectDir\\copy_inp.bat"
  GiD_Process escape escape escape Files WriteForBAS "$problem_dir\\..\\Execute\\template_run2console.bat" "$GiDProjectDir\\run_inp_in_AtenaConsole.bat"
  GiD_Process escape escape escape Files WriteForBAS "$problem_dir\\..\\Execute\\template_batchRun.bat" "$GiDProjectDir\\batchRun.bat"
  #GiD_Process escape escape escape Files WriteForBAS "$problem_dir\\..\\Execute\\template_run2win.bat" "$GiDProjectDir\\run_inp_in_AtenaWin.bat"
  GiD_Process escape escape escape Files WriteForBAS "$problem_dir\\..\\Execute\\template_run2studio.bat" "$GiDProjectDir\\run_inp_in_AtenaStudio.bat"
  
  return ""
}

proc Reinf_Area_of_Profile { args p_calcflag p_profile p_numberprofiles } {

 set pi 3.14159265358979323846

 set GDN  [lindex $args 0]
 set STRUCT [lindex $args 1]
 set QUESTION [lindex $args 2]

 set value [DWLocalGetValue $GDN $STRUCT $p_calcflag]
 if { $value == 1} {
   # TK_Info $event $args

   set profileunit [DWLocalGetValue $GDN $STRUCT $p_profile]
   # set profile [lindex $profileunit 1]
   # set unit [lindex $profileunit 2]

    set n [GidConvertValueUnit $profileunit]
   set n [ParserNumberUnit $n profile unit]

   set count [DWLocalGetValue $GDN $STRUCT $p_numberprofiles]
   set area [expr $count*$pi*($profile*$profile)/4.0]
   set area $area$unit^2

   set calcflag [DWLocalSetValue $GDN $STRUCT $QUESTION $area]
   # DWLocalSetValue $GDN $STRUCT $p_calcflag 0
  return 1
 } else {
  return 0
 }
}

proc TK_Calculation_cover_and_radius { coverunit profileunit } {
  set n1 [GidConvertValueUnit $coverunit]
 set n1 [ParserNumberUnit $n1 cover unit]

  set n2 [GidConvertValueUnit $profileunit]
 set n2 [ParserNumberUnit $n2 profile unit]

 return [expr $profile*0.5 + $cover]
}

proc TK_DEPEND_Reinf_X_Activate_CCSteelDRC_parameters { event args number} {
   switch $event {
	 DEPEND {
	  #WarnWinText "DEPEND"
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]   

     #WarnWinText "$number"

     set Reinf_01_Activate_CCSteelDRC_parameters [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_Activate_CCSteelDRC_parameters" $number]]
     set Reinf_01_Type_of_definition [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_Type_of_definition" $number]]    
     
     #WarnWinText "Reinf_01_Activate_CCSteelDRC_parameters = $Reinf_01_Activate_CCSteelDRC_parameters"
     #WarnWinText "Reinf_01_Type_of_definition = $Reinf_01_Type_of_definition"
     
    if { $Reinf_01_Activate_CCSteelDRC_parameters == 1 } {
        if { $Reinf_01_Type_of_definition == "PSH" } {
          #WarnWinText "view PSH"
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_PSH" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_PSH" $number]] "normal"]
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_ESH1" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_ESH1" $number]] "hidden"]
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_FSH1" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_FSH1" $number]] "hidden"]
          } elseif { $Reinf_01_Type_of_definition == "ESH1-FSH1" } {
          #WarnWinText "view ESH1-FSH1"
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_PSH" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_PSH" $number]] "hidden"]
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_ESH1" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_ESH1" $number]] "normal"]
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_FSH1" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_FSH1" $number]] "normal"]          
          }
       } else {
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_PSH" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_PSH" $number]] "hidden"]
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_ESH1" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_ESH1" $number]] "hidden"]
          set on [DWLocalSetValue $GDN $STRUCT [format "Reinf_0%s_FSH1" $number] [DWLocalGetValue $GDN $STRUCT [format "Reinf_0%s_FSH1" $number]] "hidden"]         
       }
    return ""
	 }
   }
   return ""
}


proc TK_DEPEND_BarWithBond { event args} {
   switch $event {
	 DEPEND {
	  #WarnWinText "DEPEND"
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]   

     #WarnWinText "$number"

     set Generate_parameter_automaticaly [DWLocalGetValue $GDN $STRUCT "Generate_parameter_automaticaly"]
     
    if { $Generate_parameter_automaticaly == 1 } {
          set on [DWLocalSetValue $GDN $STRUCT "Bond_law_by" [DWLocalGetValue $GDN $STRUCT "Bond_law_by"] "normal"]
	 }
   }
   }
   return ""
}


proc TK_DEPEND_Reinf_01_Activate_CCSteelDRC_parameters { event args } {
   set x [TK_DEPEND_Reinf_X_Activate_CCSteelDRC_parameters  $event $args 1]
   return ""
}
proc TK_DEPEND_Reinf_02_Activate_CCSteelDRC_parameters { event args } {
   set x [TK_DEPEND_Reinf_X_Activate_CCSteelDRC_parameters  $event $args 2]
   return ""
}
proc TK_DEPEND_Reinf_03_Activate_CCSteelDRC_parameters { event args } {
   set x [TK_DEPEND_Reinf_X_Activate_CCSteelDRC_parameters  $event $args 3]
   return ""
}
proc TK_DEPEND_Reinf_04_Activate_CCSteelDRC_parameters { event args } {
   set x [TK_DEPEND_Reinf_X_Activate_CCSteelDRC_parameters  $event $args 4]
   return ""
}
proc TK_DEPEND_Reinf_05_Activate_CCSteelDRC_parameters { event args } {
   set x [TK_DEPEND_Reinf_X_Activate_CCSteelDRC_parameters  $event $args 5]
   return ""
}
proc TK_DEPEND_Reinf_06_Activate_CCSteelDRC_parameters { event args } {
   set x [TK_DEPEND_Reinf_X_Activate_CCSteelDRC_parameters  $event $args 6]
   return ""
}

proc TK_GENERATE_CHLORIDES { event args } {
   switch $event {
  DEPEND {

   #WarnWin "depend"
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
    # Combination_dof_3

    set sc [DWLocalGetValue $GDN $STRUCT "Generate"]
    set sc2 [DWLocalGetValue $GDN $STRUCT "Generate2"]
    
    #set slave [DWLocalGetValue $GDN $STRUCT "Slave_dof"]
    #WarnWin "Generate = $sc Generate2= $sc2"
    #set isc [string equal $sc "GLOBAL"]
    if { $sc == 0 & $sc2 == 1 } {

     WarnWinText "Chlorides Generation"
     WarnWinText "===================="
     
     
     set Mass_of_Binder [DWLocalGetValue $GDN $STRUCT "Mass_of_Binder"]
     set Water_binder_Ratio [DWLocalGetValue $GDN $STRUCT "Water/binder_Ratio"]
     set Cement_Type [DWLocalGetValue $GDN $STRUCT "Cement_Type"]
     set Char_Compressive_Strength [DWLocalGetValue $GDN $STRUCT "Char_Compressive_Strength"]
    set n1 [GidConvertValueUnit $Char_Compressive_Strength]
    set n1 [ParserNumberUnit $n1 Char_Compressive_StrengthValue Char_Compressive_StrengthValueUnit]     
     
      
      
      
     set ConcreteCover [DWLocalGetValue $GDN $STRUCT "Concrete_Cover_Thickness"]
     set Maximum_Reinforcement_Depth [DWLocalGetValue $GDN $STRUCT "Maximum_Reinforcement_Depth"]
     set Temperature [DWLocalGetValue $GDN $STRUCT "Temperature"]
     set Critical_Chloride_Concentration [DWLocalGetValue $GDN $STRUCT "Critical_Chloride_Concentration"]
     set Exposure_Conditions [DWLocalGetValue $GDN $STRUCT "Exposure_Conditions"]
     set Corrosivity_Zone [DWLocalGetValue $GDN $STRUCT "Corrosivity_Zone"]
     set Pitting_Factor [DWLocalGetValue $GDN $STRUCT "Pitting_Factor"]
     WarnWinText "----------"
     WarnWinText "Input data"
     WarnWinText "----------"

     WarnWinText "Mass_of_Binder = $Mass_of_Binder"
     WarnWinText "Water_binder_Ratio = $Water_binder_Ratio"
     WarnWinText "Cement_Type = $Cement_Type"
     WarnWinText "Char_Compressive_Strength = $Char_Compressive_Strength"
     WarnWinText "Concrete_Cover_Thickness = $ConcreteCover"
     WarnWinText "Maximum_Reinforcement_Depth = $Maximum_Reinforcement_Depth"
     WarnWinText "Temperature = $Temperature"
     WarnWinText "Critical_Chloride_Concentration = $Critical_Chloride_Concentration"
     WarnWinText "Exposure_Conditions = $Exposure_Conditions"
     WarnWinText "Corrosivity_Zone = $Corrosivity_Zone"
     WarnWinText "Pitting_Factor = $Pitting_Factor"
     WarnWinText "-----------"
     WarnWinText "Output data"
     WarnWinText "-----------"
     
     if {$Cement_Type == "CEM_I"} {
        set da [expr 0.0121*exp([expr 10.056*$Water_binder_Ratio])*pow(10,-12)]
        set m_coeff 0.37
        if {$Exposure_Conditions == "submerged"} { set cs 0.103
        } elseif {$Exposure_Conditions == "tidal_and_splash"} { set cs 0.0776
        } elseif {$Exposure_Conditions == "atmospheric"} { set cs 0.0257
        } else { WarnWinText "Unknown type of Exposure_Conditions = $Exposure_Conditions" }
     } elseif {$Cement_Type == "CEM_I_+_5_%_SF"} {
        set da [expr 0.0018*exp([expr 13.951*$Water_binder_Ratio])*pow(10,-12)]
        set m_coeff 0.39
        if {$Exposure_Conditions == "submerged"} { set cs 0.125
        } elseif {$Exposure_Conditions == "tidal_and_splash"} { set cs 0.0896
        } elseif {$Exposure_Conditions == "atmospheric"} { set cs 0.0323
        } else { WarnWinText "Unknown type of Exposure_Conditions = $Exposure_Conditions" }        
     } elseif {$Cement_Type == "CEM_I_+_10_%_SF"} {
        set da [expr 0.0111*exp([expr 6.2117*$Water_binder_Ratio])*pow(10,-12)]
        set m_coeff 0.39
        if {$Exposure_Conditions == "submerged"} { set cs 0.125
        } elseif {$Exposure_Conditions == "tidal_and_splash"} { set cs 0.0896
        } elseif {$Exposure_Conditions == "atmospheric"} { set cs 0.0323
        } else { WarnWinText "Unknown type of Exposure_Conditions = $Exposure_Conditions" }        
     } elseif {$Cement_Type == "CEM_II/A-S"} {
        set da [expr 0.0595*exp([expr 0.6235*$Water_binder_Ratio])*pow(10,-12)]
        set m_coeff 0.6
        if {$Exposure_Conditions == "submerged"} { set cs 0.0506
        } elseif {$Exposure_Conditions == "tidal_and_splash"} { set cs 0.0677
        } elseif {$Exposure_Conditions == "atmospheric"} { set cs 0.0305
        } else { WarnWinText "Unknown type of Exposure_Conditions = $Exposure_Conditions" }        
     } elseif {$Cement_Type == "CAM_II/A-LL"} {
        set da [expr 0.0006*exp([expr 15.659*$Water_binder_Ratio])*pow(10,-12)]
        set m_coeff 0.37
        if {$Exposure_Conditions == "submerged"} { set cs 0.103
        } elseif {$Exposure_Conditions == "tidal_and_splash"} { set cs 0.0776
        } elseif {$Exposure_Conditions == "atmospheric"} { set cs 0.0257
        } else { WarnWinText "Unknown type of Exposure_Conditions = $Exposure_Conditions" }        
     } elseif {$Cement_Type == "CEM_III_44_%_GGBS"} {
        set da [expr 0.0033*exp([expr 8.9801*$Water_binder_Ratio])*pow(10,-12)]
        set m_coeff 0.6
        if {$Exposure_Conditions == "submerged"} { set cs 0.0506
        } elseif {$Exposure_Conditions == "tidal_and_splash"} { set cs 0.0677
        } elseif {$Exposure_Conditions == "atmospheric"} { set cs 0.0305
        } else { WarnWinText "Unknown type of Exposure_Conditions = $Exposure_Conditions" }        
     } else {
       WarnWinText "Unknown type of Cement_Type = $Cement_Type"
     }
     
     set d_ref [expr $da*(1-$m_coeff)]m^2/sec
     WarnWinText "D_REF = $d_ref"
     set on [DWLocalSetValue $GDN $STRUCT "D_REF" $d_ref]

     set time_d_ref 20year    
     WarnWinText "TIME_D_REF = $time_d_ref"
     set on [DWLocalSetValue $GDN $STRUCT "TIME_D_REF" $time_d_ref] 

     WarnWinText "M_COEFF = $m_coeff"
     set on [DWLocalSetValue $GDN $STRUCT "M_COEFF" $m_coeff] 
     
     set time_m_coeff 30year    
     WarnWinText "TIME_M_COEFF = $time_m_coeff"
     set on [DWLocalSetValue $GDN $STRUCT "TIME_M_COEFF" $time_m_coeff]      
     
     WarnWinText "CS = $cs"
     set on [DWLocalSetValue $GDN $STRUCT "CS" $cs] 
     
     WarnWinText "CL_CRIT = $Critical_Chloride_Concentration"
     set on [DWLocalSetValue $GDN $STRUCT "CL_CRIT" $Critical_Chloride_Concentration]                   
        
     WarnWinText "CONCRETE_COVER = $ConcreteCover"
     set on [DWLocalSetValue $GDN $STRUCT "CONCRETE_COVER" $ConcreteCover]        
        
     WarnWinText "MAX_REINF_DEPTH = $Maximum_Reinforcement_Depth"
     set on [DWLocalSetValue $GDN $STRUCT "MAX_REINF_DEPTH" $Maximum_Reinforcement_Depth]      
     
     #vzorec pro F T CH 	0.3*f_c^(2/3)
     #WarnWinText "Char_Compressive_StrengthValue = $Char_Compressive_StrengthValue"
     #set f_t_ch0 [expr pow($Char_Compressive_StrengthValue,[expr 2.0/3.0])]
     #WarnWinText "f_t_ch0 = $f_t_ch0"
     #set f_t_ch1 [expr pow($Char_Compressive_StrengthValue,(0.666666666666666666))]
     #WarnWinText "f_t_ch1 = $f_t_ch1"     
     set f_t_ch [expr 0.3*pow($Char_Compressive_StrengthValue,[expr 2.0/3.0])]$Char_Compressive_StrengthValueUnit
     WarnWinText "F T CH = $f_t_ch"
     set on [DWLocalSetValue $GDN $STRUCT "F_T_CH" $f_t_ch]
     
    
     if {$Corrosivity_Zone == "dry_indoors"} {
       set dx_corr_dt_spalling 1.3um/year
     } elseif {$Corrosivity_Zone == "low_arid/urban_inland"} {
       set dx_corr_dt_spalling 13.15um/year
     } elseif {$Corrosivity_Zone == "coastal_and_industral"} {
       set dx_corr_dt_spalling 37.5um/year
     } elseif {$Corrosivity_Zone == "calm_sea-shore"} {
       set dx_corr_dt_spalling 65um/year
     } elseif {$Corrosivity_Zone == "surf_sea-shore"} {
       set dx_corr_dt_spalling 140um/year
     } elseif {$Corrosivity_Zone == "ocean/off-shore"} {
       set dx_corr_dt_spalling 450um/year
     } else {
       WarnWinText "Unknown type of Corrosivity_Zone = $Corrosivity_Zone"
     }
     WarnWinText "DX_CORR_DT_SPALLING = $dx_corr_dt_spalling"
     set on [DWLocalSetValue $GDN $STRUCT "DX_CORR_DT_SPALLING" $dx_corr_dt_spalling]
     
     WarnWinText "R_CORR = $Pitting_Factor"
     set on [DWLocalSetValue $GDN $STRUCT "R_CORR" $Pitting_Factor]  
     
     WarnWinText "CEMENT MASS = $Mass_of_Binder" 
     set on [DWLocalSetValue $GDN $STRUCT "CEMENT_MASS" $Mass_of_Binder]        

     WarnWinText "T_AVER_OFFSET = $Temperature"
     set on [DWLocalSetValue $GDN $STRUCT "T_AVER_OFFSET" $Temperature] 

     WarnWinText "View_Advanced_durability_parameters deactivated"
     set on [DWLocalSetValue $GDN $STRUCT "View_Advanced_durability_parameters" 0]      


     set on [DWLocalSetValue $GDN $STRUCT "Generate" 0]
    }
    return ""
   }   
   }
}

proc TK_Help_Reinf_Calulator { event args } {
 # WarnWin "event=$event; args=$args"
   switch $event {
	 INIT {
	  # do nothing here
	 }
	 SYNC {
	   set area [Reinf_Area_of_Profile $args "Help_Calculator" "Reinf_01_Profile" "Reinf_01_Number_of_Profiles"]
	 }
	 CLOSE {
	  # do nothing here
	 }
   }
}

proc TK_Circumsphere { event args } {
    switch $event {
	 INIT {
 	  # do nothing here
	  return ""
	 }
	 SYNC {
             # WarnWin "event=$event; args=$args"
             set GDN [lindex $args 0]
	     set STRUCT [lindex $args 1]
	     set QUESTION [lindex $args 2]

	     set calcflag [DWLocalGetValue $GDN $STRUCT $QUESTION]

	     if { $calcflag == 1 } {
 		  set pi 3.14159265358979323846
		  set np       [DWLocalGetValue $GDN $STRUCT Number_of_Profiles]
		  set diameterunit [DWLocalGetValue $GDN $STRUCT Profile]
		  set bondBarOld [DWLocalGetValue $GDN $STRUCT Bond_Bar_Diameter]
      set Bar_PerimeterOld [DWLocalGetValue $GDN $STRUCT Bar_Perimeter]
      set Geom_Type [DWLocalGetValue $GDN $STRUCT Geom_Type]
		  
		  set n [GidConvertValueUnit $diameterunit]
		  set n [ParserNumberUnit $n diameter unit]		  

		  set Circumsphere [expr $pi*$diameter*$np]$unit
		  set n            [DWLocalSetValue $GDN $STRUCT "Bar_Perimeter" $Circumsphere]
		  set n            [DWLocalSetValue $GDN $STRUCT "Bond_Bar_Diameter" $diameterunit]

      if {$Geom_Type == "BAR_WITH_BOND" || $Geom_Type == "BAR_WITH_MEMORY_BOND" || $Geom_Type == "INTERNAL_CABLE" } { 
      		  if { $Bar_PerimeterOld!=$Circumsphere} {
               WarnWin "Bar_with_Bond -> Bar_Perimeter was updated"
            }     
      
      }

		  
		  set generate       [DWLocalGetValue $GDN $STRUCT Generate_parameter_automaticaly]
      		  if { $generate == 1 && $bondBarOld!=$diameterunit} {
               WarnWin "A new reinforcement diameter value was detected and therefore the Bond_Bar_Diameter was updated, it may be necessary to regenerate the bond-slip law."
            }
	     }
	  return ""
	 }
	 CLOSE {
	  # do nothing here
	  return ""
	 }
    }
  return ""
}

proc TK_Reinf_Calulator { event args } {
 # WarnWin "event=$event; args=$args"
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
   set area [Reinf_Area_of_Profile $args "Calculator" "Profile" "Number_of_Profiles"]
 }
 CLOSE {
  # do nothing here
 }
 }
}


proc Reinf_Diameter_of_Profile { args p_calcflag p_profile p_diameters } {
 set GDN  [lindex $args 0]
 set STRUCT [lindex $args 1]
 set QUESTION [lindex $args 2]
   
 set value [DWLocalGetValue $GDN $STRUCT $p_calcflag]
 if { $value == 1} {
   set profileunit [DWLocalGetValue $GDN $STRUCT $p_profile]
   #set n [GidConvertValueUnit $profileunit]
   set n [ParserNumberUnit $profileunit profile unit]
   set profile $profile$unit
   set calcflag [DWLocalSetValue $GDN $STRUCT $p_diameters $profile]
   return 1
  } else {
  return 0
 }
}

proc TK_Reinf_01_Calulator { event args } {
 # WarnWin "event=$event; args=$args"
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
 set area [Reinf_Area_of_Profile $args "Reinf_01_Calculator" "Reinf_01_Profile" "Reinf_01_Number_of_Profiles"]
 set diameter [Reinf_Diameter_of_Profile $args "Reinf_01_Calculator" "Reinf_01_Profile" "Reinf_01_Diameter"] 
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc TK_Reinf_02_Calulator { event args } {
 # WarnWin "event=$event; args=$args"
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
   set area [Reinf_Area_of_Profile $args "Reinf_02_Calculator" "Reinf_02_Profile" "Reinf_02_Number_of_Profiles"]
   set diameter [Reinf_Diameter_of_Profile $args "Reinf_02_Calculator" "Reinf_02_Profile" "Reinf_02_Diameter"]
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc TK_Reinf_03_Calulator { event args } {
 # WarnWin "event=$event; args=$args"
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
   set area [Reinf_Area_of_Profile $args "Reinf_03_Calculator" "Reinf_03_Profile" "Reinf_03_Number_of_Profiles"]
   set diameter [Reinf_Diameter_of_Profile $args "Reinf_03_Calculator" "Reinf_03_Profile" "Reinf_03_Diameter"]
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc TK_Reinf_04_Calulator { event args } {
 # WarnWin "event=$event; args=$args"
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
   set area [Reinf_Area_of_Profile $args "Reinf_04_Calculator" "Reinf_04_Profile" "Reinf_04_Number_of_Profiles"]
   set diameter [Reinf_Diameter_of_Profile $args "Reinf_04_Calculator" "Reinf_04_Profile" "Reinf_04_Diameter"]
 }
 CLOSE {
  # do nothing here
 }
 }
}
proc Update_INTEGRATION_TIME_INCREMENT { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {

 set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  set startvalueunit [DWLocalGetValue $GDN $STRUCT Increment_Transient_Time]
  set n1 [GidConvertValueUnit $startvalueunit]
  set n1 [ParserNumberUnit $n1 value1 unit1]


  #set current [GiD_IntervalData set]
  #set myvalueunit [GiD_AccessValue get IntvData $current Integration_Time_Increment]

  set myvalueunit [DWLocalGetValue $GDN $STRUCT Integration_Time_Increment]
  set n2 [GidConvertValueUnit $myvalueunit]
  set n2 [ParserNumberUnit $n2 value2 unit2]

  if {$value1<$value2} {

  WarnWinText "Warning: Increment_Transient_Time > Integration_Time_Increment !"
  WarnWinText "It will be decreased to $startvalueunit."

  set valueunit [format %g%s $value1 $unit1]
  if {[string is double $value1]} {

  set on [DWLocalSetValue $GDN $STRUCT Integration_Time_Increment $valueunit]
  
  } else {
  WarnWinText "Could not sync $QUESTION because Increment_Transient_Time is not a real value"
  }

   }





  #set GDN [lindex $args 0]
  #set STRUCT [lindex $args 1]
  #set QUESTION [lindex $args 2]

  #set nlss [DWLocalGetValue $GDN $STRUCT Number_of_LOAD_STEPs]

  #set itt [DWLocalGetValue $GDN $STRUCT INCREMENT_TRANSIENT_TIME]
  #set n1 [GidConvertValueUnit $itt]
  #set n1 [ParserNumberUnit $n1 value1 unit1]

  #set value [expr double($value1)/double($nlss)]
  #set valueunit [format %g%s $value $unit1]

  #if {[string is double $value]} {
  # GiD_AccessValue set IntvData ... INTEGRATION_TIME_INCREMENT ...
  #set n [DWLocalSetValue $GDN $STRUCT $QUESTION $valueunit]
  #} else {
  #WarnWinText "Could not sync $QUESTION because INCREMENT_TRANSIENT_TIME is not a real value"
  #}
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc Set_Starting_Time1Interval_To_Current_TimeGenData { } {

  set startvalueunit [GiD_AccessValue get IntvData 1 INTERVAL_STARTING_TIME]
#  set n1 [GidConvertValueUnit $startvalueunit]
#  set n1 [ParserNumberUnit $n1 value1 unit1]

  set currenttime [GiD_AccessValue set GenData CURRENT_TRANSIENT_TIME $startvalueunit]
  return ""
}

proc Update_INCREMENT_TIME { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  set startvalueunit [DWLocalGetValue $GDN $STRUCT INTERVAL_STARTING_TIME]
  set n1 [GidConvertValueUnit $startvalueunit]
  set n1 [ParserNumberUnit $n1 value1 unit1]

  set endvalueunit [DWLocalGetValue $GDN $STRUCT INTERVAL_END_TIME]
  set n2 [GidConvertValueUnit $endvalueunit]
  set n2 [ParserNumberUnit $n2 value2 unit2]

  # set valueunit [DWLocalGetValue $GDN $STRUCT INCREMENT_TRANSIENT_TIME]

  set nlss [DWLocalGetValue $GDN $STRUCT Number_of_LOAD_STEPs]
  if { $nlss <= 0 } {
  	set nlss 1
  }
  set value [expr ($value2-$value1)/double($nlss)]
  set value [expr (floor($value*1000000))/1000000]
  set valueunit [format %g%s $value $unit1]

  if {[string is double $value]} {
  # GiD_AccessValue set IntvData ... INCREMENT_TRANSIENT_TIME ...
  set n [DWLocalSetValue $GDN $STRUCT $QUESTION $valueunit]
  
  set actual_problemType [GiD_AccessValue get gendata "Calculation_Analysis"]
  if { $actual_problemType=="Creep" || $actual_problemType=="Dynamic" } {
    set neglTimeFract [GiD_AccessValue get gendata "Extend_NEGLIGIBLE_TIME_FRACTION"]
    set limitValue [expr 0.1/$neglTimeFract]
  set on [GiD_AccessValue get gendata Calculation_Analysis]
  if {$on=="Creep" && $value <= $limitValue } {
      WarnWinText "Error: The minimal INCREMENT_TRANSIENT_TIME (step time) is lower or equal to $limitValue day ! Please increase it or change the tolerance, set Extend_NEGLIGIBLE_TIME_FRACTION in ProblemData/Creep (Dynamic)"
    }
  }  
  
  
  } else {
  WarnWinText "Could not sync $QUESTION because INTERVAL_END_TIME-INTERVAL_STARTING_TIME is not a real value"
  }
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc Update_TRANSPORT_INTERVAL_STARTEND_TIME { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

  # INTERVAL_STARTING_TIME:
  set ist [DWLocalGetValue $GDN $STRUCT INTERVAL_STARTING_TIME]
      #set n [GidConvertValueUnit $at]
      #set n [ParserNumberUnit $n at unit]
  DWLocalSetValue $GDN $STRUCT TRANSPORT_INTERVAL_STARTING_TIME $ist

  # INTERVAL_END_TIME:
  set iet [DWLocalGetValue $GDN $STRUCT $QUESTION]
      #set n [GidConvertValueUnit $iat]
      #set n [ParserNumberUnit $n iat unit]
  DWLocalSetValue $GDN $STRUCT TRANSPORT_INTERVAL_END_TIME $iet

  #set nls [DWLocalGetValue $GDN $STRUCT Number_of_LOAD_STEPs]
  #set value [expr $at+$nls*$iat]
  #set value $value$unit
  #set at $at$unit
 }
 CLOSE {
  # do nothing here
 }
 }

}

proc Update_Number_of_TRANSPORT_LOAD_STEPs { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
  set value [DWLocalGetValue $GDN $STRUCT "Number_of_LOAD_STEPs"]

  if {[string is double $value]} {
  DWLocalSetValue $GDN $STRUCT $QUESTION [format %g $value]
  } else {
  WarnWinText "Could not sync $QUESTION because Number_of_LOAD_STEPs is not a real value"
  }
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc UpdateCompresion_Strength { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
  if {[string is double [set value [DWLocalGetValue $GDN $STRUCT "FCYL28"]]]} {
  DWLocalSetValue $GDN $STRUCT $QUESTION [format %g [expr -[DWLocalGetValue $GDN $STRUCT "FCYL28"]]]
  } else {
  WarnWinText "Could not sync $QUESTION because FCYL28 is not a real value"
  }
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc UpdateYoung_modulus { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
  if {[string is double [set value [DWLocalGetValue $GDN $STRUCT "E28"]]]} {
  DWLocalSetValue $GDN $STRUCT $QUESTION [format %g [expr -[DWLocalGetValue $GDN $STRUCT "E28"]]]
  } else {
  WarnWinText "Could not sync $QUESTION because E28 is not a real value"
  }
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc TK_InitContactName { } {
  GiD_AccessValue set gendata "UniqueContactName" ""
  return ""
}

proc TK_CreateArraysContactName { ContactName } {
  set ucn [GiD_AccessValue get gendata "UniqueContactName" ]
  lappend ucn $ContactName

  set sucn [lsort -ascii -unique $ucn]
  # WarnWinText "UniqueContactName=$sucn"
  GiD_AccessValue set gendata "UniqueContactName" $sucn
  return ""
}

proc TK_FinishArraysContactName { } {
  set ucn [GiD_AccessValue get gendata "UniqueContactName" ]
  if { [llength $ucn] > 0 } {
    set oucn "#N# [llength $ucn] $ucn"
  } else {
    set oucn "#N# 1 none"
  }
  # WarnWinText "oucn=$oucn"
  GiD_AccessValue set gendata "UniqueContactName" $oucn
  return ""
}

proc TK_InitSelectionName { } {
  GiD_AccessValue set gendata "UniqueSelectionName" ""
  return ""
}

proc TK_CreateArraysSelectionName { ContactName } {
  set ucn [GiD_AccessValue get gendata "UniqueSelectionName" ]
  lappend ucn $ContactName

  set sucn [lsort -ascii -unique $ucn]
  # WarnWinText "UniqueContactName=$sucn"
  GiD_AccessValue set gendata "UniqueSelectionName" $sucn
  return ""
}

proc TK_FinishArraysSelectionName { } {
  set ucn [GiD_AccessValue get gendata "UniqueSelectionName" ]
  if { [llength $ucn] > 0 } {
    set oucn "#N# [llength $ucn] $ucn"
  } else {
    set oucn "#N# 1 none"
  }
  # WarnWinText "oucn=$oucn"
  GiD_AccessValue set gendata "UniqueSelectionName" $oucn
  return ""
}


proc TK_Generate_Fatigue_substeps { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
  
  #set current [GiD_IntervalData set]
  #set numLoadCollectives [GiD_AccessValue get IntvData $current Num_Load_Collectives]
  set numLoadCollectives [DWLocalGetValue $GDN $STRUCT Num_Load_Collectives]
  #set numCyclesPerCollect [GiD_AccessValue get IntvData $current Num_Cycles_per_Collect]
  set numCyclesPerCollect [DWLocalGetValue $GDN $STRUCT Num_Cycles_per_Collect]
  #set generate [GiD_AccessValue get IntvData $current Generate_substeps]
  set generate [DWLocalGetValue $GDN $STRUCT Generate_substeps]
  

  set FatInt [DWLocalGetValue $GDN $STRUCT "Fatigue_Interval"]
  
  if { $generate == 1 && $FatInt == "AUTOMATIC" } {      
   set step 0
   set array "#N# 0"
    for {set i $step} {$i < $numLoadCollectives} {incr i} {
        set array [AddItem2Array $array $numCyclesPerCollect ]
    }
     set on [DWLocalSetValue $GDN $STRUCT "Cycles_in_substeps" $array]
     set on [DWLocalSetValue $GDN $STRUCT "Generate_substeps" 0]   
      
      # Number_of_Fatigue_Cycles
   }
 }
 CLOSE {
  # do nothing here
 }
 }
}

proc TK_Recalculate_Fatigue_steps { event args } {
 switch $event {
 INIT {
  # do nothing here
 }
 SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
  
  #set current [GiD_IntervalData set]
  #set onls [GiD_AccessValue get IntvData $current Cycles_in_substeps]
  set onls [DWLocalGetValue $GDN $STRUCT Cycles_in_substeps]

  if { $onls == 0 } { 
  	return "" 
  }  
  set FatInt [DWLocalGetValue $GDN $STRUCT "Fatigue_Interval"]
  
  if { $FatInt == "AUTOMATIC" } {      
      set valueLoad [DWLocalGetValue $GDN $STRUCT "Num_step_Load"]
      set valueUnLoad [DWLocalGetValue $GDN $STRUCT "Num_step_Unload"]
      set valueApply [DWLocalGetValue $GDN $STRUCT "Num_step_Apply"]
    
      set NumCells [lindex $onls 1]
      set steps  [expr $valueLoad+$valueUnLoad+$valueApply]
      set steps  [expr $NumCells*$steps]
      
      set cyka 0
      set cykb 0
      
      for {set j 2} {$j <= [expr $NumCells+1]} {set j [expr $j+1]} {
        set cyka [lindex $onls $j]
        #WarnWinText "cyka=$cyka"
        set cykb  [expr $cykb+$cyka]
        #WarnWinText "cykb=$cykb"
      }
  
      #set NumCells [lindex $cycles 1]
      #WarnWinText "valueLoad=$valueLoad"
      #WarnWinText "NumCells=$NumCells"
      #WarnWinText "celkem=$celkem"
      #GiD_AccessValue set IntvData $current "Number_of_Load_Steps" $celkem
      set n [DWLocalSetValue $GDN $STRUCT "Number_of_Load_Steps" $steps]
      set n [DWLocalSetValue $GDN $STRUCT "Number_of_Fatigue_Cycles" $cykb]

   }
 }
 CLOSE {
  # do nothing here
 }
 }
}




proc TK_Read_INTERVAL_STARTING_TIME { event args } {

 switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   # ...
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]

    set value [GiD_AccessValue get IntvData 1 INTERVAL_STARTING_TIME]
    
		set n2 [GidConvertValueUnit $value]
 		set n2 [ParserNumberUnit $n2 value unit]
    set value2 [format %g%s $value $unit]    
    
    set n [GiD_AccessValue set GenData CURRENT_TRANSIENT_TIME $value2]
    # set n [DWLocalSetValue $GDN $STRUCT $QUESTION $value]
    return ""
   }
   DEPEND {
   # ...
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
  }
  return ""
}

proc TK_History_TRANSPORT_import { event args } {

 switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   # ...
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]

    set value [DWLocalGetValue $GDN $STRUCT $QUESTION]
    set inInterval [GiD_Info intvdata NUM]
    set nInterval [lindex $inInterval 1]
    # WarnWinText "nInterval=$nInterval"
    for {set i 1} {$i <= $nInterval} {set i [expr $i+1]} {
      if { $value == 1 } {
#       set naccess [GiD_AccessValue set intvdata $i READ_TRANSPORT_DATA 1]
       set naccess [GiD_AccessValue set intvdata $i sw_READ_TRANSPORT_DATA 1]
      }  else {
       set naccess [GiD_AccessValue set intvdata $i READ_TRANSPORT_DATA 0]
       set naccess [GiD_AccessValue set intvdata $i sw_READ_TRANSPORT_DATA 0]

      }
    }
    return ""
   }
   DEPEND {
   # ...
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
  }
  return ""
}

proc TK_LoadStoredStepFromDirectory { event args } {

 switch $event {
	SYNC {
		 # ...
		  set GDN [lindex $args 0]
		  set STRUCT [lindex $args 1]
		  set QUESTION [lindex $args 2]

		  set sc [DWLocalGetValue $GDN $STRUCT $QUESTION]
		  if { $sc == 1 } {
       set on [DWLocalSetValue $GDN $STRUCT $QUESTION 0]
      } 
      
		  if { $sc == 0 } {
       return ""
      }       
   
    global problem_dir
    global GIDDEFAULT
    cd $GIDDEFAULT
    global GiDProjectDir GiDProjectName
    global taskName 

   if { $GiDProjectName == "UNNAMED"} {
   return ""
   }
   
   set ProblemDirectory [GetDirectoryProblemType]
  
   if { ![file isdirectory $ProblemDirectory] } {
    set ProblemDirectory [file join $GIDDEFAULT problemtypes $ProblemType.gid]
   }
  
   if { ![file isdirectory $ProblemDirectory] } {
    return ""
   }          
      
   set existujeStarsi 0
   set soubor "$GiDProjectDir\\AtenaCalculation\\$taskName." 
   set step 0
   set array "#N# 0"
   
    for {set i $step} {$i < 10000} {incr i} {
        set cislo [getStepNumber $i]
        set Batka $soubor
        append Batka $cislo 
        #WarnWinText $Batka
        if { [file exists $Batka] == 1} {  
            #WarnWinText $Batka
	          set array [AddItem2Array $array $i ]
        }
    }
   
     set on [DWLocalSetValue $GDN $STRUCT "Steps_To_Import" $array]   

 	  return ""
		 }
	}
	return ""
}

proc TK_Update_TaskName { event args } {

 switch $event {
	INIT {
		 # ...
		  return ""
		 }
	SYNC {
		 # ...
		  set GDN [lindex $args 0]
		  set STRUCT [lindex $args 1]
		  set QUESTION [lindex $args 2]

		  set sc [DWLocalGetValue $GDN $STRUCT "TaskName"]
		  set on [DWLocalSetValue $GDN $STRUCT $QUESTION $sc]

		  return ""
		 }
		 DEPEND {
		 # ...
		  return ""
		 }
		 CLOSE {
		 # ...
		  return ""
		 }
	}
	return ""
}

proc TK_FindMaterialNameById { matid } {
 if { $matid <= 0 } {
  return ""
 }
   foreach mat_name [GiD_Info materials] {
       set mat_id [TK_FindMaterialNumber $mat_name "TK_FindMaterialNameById"]
       if { $mat_id == $matid } {
        return $mat_name
       }       
       
       }
   return ""
}

proc TK_FindMaterialPrototypeName { matname } {

 set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]
 if { $internalmatnum <= 0 } {
  return ""
 }
 set prototype [GiD_AccessValue get materials $matname "Material_Prototype"]
 return $prototype
}

proc TK_FindMaterialPrototypeNum { internalmatnum } {
 if { $internalmatnum <= 0 } {
  return ""
  }
  set prototype [GiD_AccessValue -index get materials $internalmatnum Material_Prototype]
  return $prototype
  
  set matname [TK_FindMaterialNameById $internalmatnum]
# set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]
 if { $internalmatnum == 0 } {
  return ""
 }
 set prototype [GiD_AccessValue get materials $matname "Material_Prototype"]
 return $prototype
}

proc TK_CheckMaterialPrototypeForShell { event args } {
#jumbo
switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]

   #WarnWinText "TK_Info G S Q"
   #WarnWinText $GDN
   #WarnWinText $STRUCT
   #WarnWinText $QUESTION
    
  set oBase [DWLocalGetValue $GDN $STRUCT $QUESTION]
   #WarnWinText "oBase" 
   #WarnWinText $oBase" 	
 

 set prototype [GiD_AccessValue get materials $oBase "Material_Prototype"]
 #WarnWinText "prototype"
 #WarnWinText $prototype
  if { $prototype == "CCSBETAMaterial" || $prototype == "CCPlaneStressSteel" || $prototype == "CCPlaneStressElastIsotropic" || $prototype == "CCPlaneStrainElastIsotropic" || $prototype == "CCASymElastIsotropic" || $prototype == "CCCombinedMaterial" || $prototype == "CCCombinedMaterialWithTempDepProperties"} {
  WarnWinText "ERROR: Material $oBase with prototype $prototype can not be used for shell macroelement. Use another material."
                      }
     return ""
   }
   DEPEND {
   # ...
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
 }
 return ""
}

proc TK_CheckMaterialPrototypeForSolidCreep { event args } {
#jumbo
switch $event {
   INIT {
    return ""
   }

   SYNC {
  set GDN [lindex $args 0]
  set STRUCT [lindex $args 1]
  set QUESTION [lindex $args 2]
   #WarnWinText "TK_Info G S Q"
   #WarnWinText $GDN
   #WarnWinText $STRUCT
   #WarnWinText $QUESTION
    
  set oBase [DWLocalGetValue $GDN $STRUCT $QUESTION]
   #WarnWinText "oBase" 
   #WarnWinText $oBase" 	

 set prototype [GiD_AccessValue get materials $oBase "Material_Prototype"]
 #WarnWinText "prototype"
 #WarnWinText $prototype
  if { $prototype == "CCMicroplane4" || $prototype == "CCMicroplane7" } {
  WarnWinText "ERROR: Material $oBase with prototype $prototype can not be used for base of this macroelement. Use another material."
                      }
           
                      
                      
     return ""
   }

   DEPEND {
    return ""
   }

   CLOSE {
    return ""
   }
 }
 return ""
}


proc TK_FindMaterialNumber { matname mothername} {
#ZJ
 set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]
 if { $internalmatnum == 0 } {
  WarnWinText "Material $matname does not exist. See Use_Base_Material for material or conditions $mothername."
  set internalmatnum -1
 }
#  set interk [GiD_Info materials $matname otherfields]
   # WarnWinText "internalmatnum:$internalmatnum"
 #set prototype [GiD_AccessValue get materials $matname "Material_Number"]
 return $internalmatnum
}

proc TK_GENERATE_VECTOR_SUPPORT { event args } {
 switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   # ...
    return ""
   }
   DEPEND {
   # ...
   #WarnWin "depend"
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
    # Combination_dof_3

    set sc [DWLocalGetValue $GDN $STRUCT "Generate"]
    set sc2 [DWLocalGetValue $GDN $STRUCT "Generate2"]
    set slave [DWLocalGetValue $GDN $STRUCT "Slave_dof"]
    #WarnWin "Generate = $sc Generate2= $sc2"
    #set isc [string equal $sc "GLOBAL"]
    if { $sc == 0 & $sc2 == 1 } {
    
      set vx [DWLocalGetValue $GDN $STRUCT "Normal_Vector_x"]
      set vy [DWLocalGetValue $GDN $STRUCT "Normal_Vector_y"]
      set vz [DWLocalGetValue $GDN $STRUCT "Normal_Vector_z"]
      
      if {$vx != 0} {
        set dof 1
        set multi1 -1
        set multi2 [expr 1.0*$vy/$vx]
        set multi3 [expr 1.0*$vz/$vx]
      } elseif {$vy != 0} {
        set dof 2
        set multi1 [expr 1.0*$vx/$vy]
        set multi2 -1
        set multi3 [expr 1.0*$vz/$vy]      
      } elseif {$vz != 0} {
        set dof 3
        set multi1 [expr 1.0*$vx/$vz]
        set multi2 [expr 1.0*$vy/$vz]
        set multi3 -1      
      } else {
        WarnWin "Use diferent vector."
        return ""
      }
        WarnWin "Generated coefficients:\n $multi1 \n $multi2 \n $multi3"
        
      if {$slave > 3} {
          set dof [expr $dof+3]
        set on [DWLocalSetValue $GDN $STRUCT "Multiplier_for_Dof_4_f4" $multi1]
        set on [DWLocalSetValue $GDN $STRUCT "Multiplier_for_Dof_5_f5" $multi2]
        set on [DWLocalSetValue $GDN $STRUCT "Multiplier_for_Dof_6_f6" $multi3]
        set on [DWLocalSetValue $GDN $STRUCT "Slave_dof" $dof]            
      } else {
        set on [DWLocalSetValue $GDN $STRUCT "Multiplier_for_Dof_1_f1" $multi1]
        set on [DWLocalSetValue $GDN $STRUCT "Multiplier_for_Dof_2_f2" $multi2]
        set on [DWLocalSetValue $GDN $STRUCT "Multiplier_for_Dof_3_f3" $multi3]
        set on [DWLocalSetValue $GDN $STRUCT "Slave_dof" $dof]          
      }        
      
    
        
    }
    #set on [DWLocalSetValue $GDN $STRUCT "Generate" 0] 
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
 }
 return ""
}      

proc TK_GENERATE_LINE_VECTOR_SUPPORT { event args } {
 switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   # ...
    return ""
   }
   DEPEND {
   # ...
   #WarnWin "depend"
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
    # Combination_dof_3

    set sc [DWLocalGetValue $GDN $STRUCT "Generate_from_line"]
    set sc2 [DWLocalGetValue $GDN $STRUCT "Generate_from_line2"]
    set master [DWLocalGetValue $GDN $STRUCT "Master_dof"]
    #WarnWin "Generate = $sc Generate2= $sc2"
    #set isc [string equal $sc "GLOBAL"]
    if { $sc == 0 & $sc2 == 1 } {
    
      set vx [DWLocalGetValue $GDN $STRUCT "Line_Vector_x"]
      set vy [DWLocalGetValue $GDN $STRUCT "Line_Vector_y"]
      set vz [DWLocalGetValue $GDN $STRUCT "Line_Vector_z"]
      
      if {$vx != 0} {
        set dof 1
        set multi1 -1
        set multi2 [expr 1.0*$vy/$vx]
        set multi3 [expr 1.0*$vz/$vx]
      } elseif {$vy != 0} {
        set dof 2
        set multi1 [expr 1.0*$vx/$vy]
        set multi2 -1
        set multi3 [expr 1.0*$vz/$vy]      
      } elseif {$vz != 0} {
        set dof 3
        set multi1 [expr 1.0*$vx/$vz]
        set multi2 [expr 1.0*$vy/$vz]
        set multi3 -1      
      } else {
        WarnWin "Use diferent vector."
        return ""
      }
        WarnWin "Generated coefficients:\n $multi1 \n $multi2 \n $multi3"
      
      if {$master > 3} {
          set dof [expr $dof+3]
          set on [DWLocalSetValue $GDN $STRUCT "Line_Multiplier_for_Dof_4_f4" $multi1]
          set on [DWLocalSetValue $GDN $STRUCT "Line_Multiplier_for_Dof_5_f5" $multi2]
          set on [DWLocalSetValue $GDN $STRUCT "Line_Multiplier_for_Dof_6_f6" $multi3]
          set on [DWLocalSetValue $GDN $STRUCT "Master_dof" $dof]            
      } else {
          set on [DWLocalSetValue $GDN $STRUCT "Line_Multiplier_for_Dof_1_f1" $multi1]
          set on [DWLocalSetValue $GDN $STRUCT "Line_Multiplier_for_Dof_2_f2" $multi2]
          set on [DWLocalSetValue $GDN $STRUCT "Line_Multiplier_for_Dof_3_f3" $multi3]
          set on [DWLocalSetValue $GDN $STRUCT "Master_dof" $dof]          
      }
         
    }
    #set on [DWLocalSetValue $GDN $STRUCT "Generate" 0] 
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
 }
 return ""
} 

proc TK_GENERATE_COEFF { event args } {
 switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   # ...
    return ""
   }
   DEPEND {
   # ...
   #WarnWin "depend"
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
    # Combination_dof_3

    set sc [DWLocalGetValue $GDN $STRUCT "Generate"]
    set sc2 [DWLocalGetValue $GDN $STRUCT "Generate2"]
    #WarnWin "Generate = $sc Generate2= $sc2"
    #set isc [string equal $sc "GLOBAL"]
    if { $sc == 0 & $sc2 == 1 } {
    
      set pax [DWLocalGetValue $GDN $STRUCT "Point_A_x"]
      set pay [DWLocalGetValue $GDN $STRUCT "Point_A_y"]
      set paz [DWLocalGetValue $GDN $STRUCT "Point_A_z"]
      set pahx [DWLocalGetValue $GDN $STRUCT "Point_A_value_for_x"]
      set pahy [DWLocalGetValue $GDN $STRUCT "Point_A_value_for_y"]
      set pahz [DWLocalGetValue $GDN $STRUCT "Point_A_value_for_z"]            

      set pbx [DWLocalGetValue $GDN $STRUCT "Point_B_x"]
      set pby [DWLocalGetValue $GDN $STRUCT "Point_B_y"]
      set pbz [DWLocalGetValue $GDN $STRUCT "Point_B_z"]
      set pbhx [DWLocalGetValue $GDN $STRUCT "Point_B_value_for_x"]
      set pbhy [DWLocalGetValue $GDN $STRUCT "Point_B_value_for_y"]
      set pbhz [DWLocalGetValue $GDN $STRUCT "Point_B_value_for_z"]

      set n [GidConvertValueUnit $pax]
      set n [ParserNumberUnit $n pax unit]
      set n [GidConvertValueUnit $pay]
      set n [ParserNumberUnit $n pay unit]
      set n [GidConvertValueUnit $paz]
      set n [ParserNumberUnit $n paz unit]
      
      set n [GidConvertValueUnit $pbx]
      set n [ParserNumberUnit $n pbx unit]
      set n [GidConvertValueUnit $pby]
      set n [ParserNumberUnit $n pby unit]
      set n [GidConvertValueUnit $pbz]
      set n [ParserNumberUnit $n pbz unit]                    

      set n [GidConvertValueUnit $pahx]
      set n [ParserNumberUnit $n pahx unit]
      set n [GidConvertValueUnit $pahy]
      set n [ParserNumberUnit $n pahy unit]
      set n [GidConvertValueUnit $pahz]
      set n [ParserNumberUnit $n pahz unit]
      
      set n [GidConvertValueUnit $pbhx]
      set n [ParserNumberUnit $n pbhx unit]
      set n [GidConvertValueUnit $pbhy]
      set n [ParserNumberUnit $n pbhy unit]
      set n [GidConvertValueUnit $pbhz]
      set n [ParserNumberUnit $n pbhz unit]      
      
      set delta_x [expr $pbx-$pax]
      set delta_y [expr $pby-$pay]
      set delta_z [expr $pbz-$paz]
      set soucin_A_delta [expr $pax*$delta_x+$pay*$delta_y+$paz*$delta_z]
      set soucin_B_delta [expr $pbx*$delta_x+$pby*$delta_y+$pbz*$delta_z]
      
      set stejneBody [expr $soucin_A_delta-$soucin_B_delta]
      if { $stejneBody == 0.0 } {
        WarnWin "Use diferent coordinates for A and B point."
        return ""
      } 
      
        #WarnWin "STRUCT=$STRUCT QUESTION = $QUESTION"
        set for_surface [string equal $STRUCT "CND,Load_Force_for_Surface"]
        set for_surface_shell [string equal $STRUCT "CND,Load_Force_for_Surface_2D_Shell"]
        #WarnWin "for_surface=$for_surface"
        if { $for_surface == 1 } {
          set unit_coef "MN/m^3"
          set unit_const "MN/m^2"
        } elseif { $for_surface_shell == 1 } {
          set unit_coef "MN/m^3"
          set unit_const "MN/m^2"
        } else {
          set unit_coef "MN/m^2"
          set unit_const "MN/m"
        }      
      
      set pocitej_x [DWLocalGetValue $GDN $STRUCT "Force_Component_X"]
      #WarnWin "pocitej_x = $pocitej_x"
      if { $pocitej_x == 1 } {
        set delta_H_x [expr $pbhx-$pahx]
        set t_x [expr (-1.0*$delta_H_x)/($soucin_A_delta-$soucin_B_delta)]
        
        set Comp_X_Coeff_X [expr $delta_x*$t_x]
        set Comp_X_Coeff_Y [expr $delta_y*$t_x]
        set Comp_X_Coeff_Z [expr $delta_z*$t_x]
        set Coeff_D [expr $pahx-($Comp_X_Coeff_X*$pax+$Comp_X_Coeff_Y*$pay+$Comp_X_Coeff_Z*$paz)]    
        WarnWin "Generated for X: Comp_X_Coeff_X=$Comp_X_Coeff_X\n Comp_X_Coeff_Y=$Comp_X_Coeff_Y\n Comp_X_Coeff_Z=$Comp_X_Coeff_Z\n X-Force=$Coeff_D"      
        
        set olen $Comp_X_Coeff_X$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_X_Coeff_X" $olen]
  
        set olen $Comp_X_Coeff_Y$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_X_Coeff_Y" $olen]
  
        set olen $Comp_X_Coeff_Z$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_X_Coeff_Z" $olen]
        
        set olen $Coeff_D$unit_const
        set on [DWLocalSetValue $GDN $STRUCT "X-Force" $olen]      
      }
      
      set pocitej_y [DWLocalGetValue $GDN $STRUCT "Force_Component_Y"]
      #WarnWin "pocitej_x = $pocitej_x"
      if { $pocitej_y == 1 } {
        set delta_H_y [expr $pbhy-$pahy]
        set t_y [expr (-1.0*$delta_H_y)/($soucin_A_delta-$soucin_B_delta)]
  
        set Coeff_A [expr $delta_x*$t_y]
        set Coeff_B [expr $delta_y*$t_y]
        set Coeff_C [expr $delta_z*$t_y]
        set Coeff_D [expr $pahy-($Coeff_A*$pax+$Coeff_B*$pay+$Coeff_C*$paz)]    
        WarnWin "Generated for Y: Comp_Y_Coeff_X=$Coeff_A\n Comp_Y_Coeff_Y=$Coeff_B\n Comp_Y_Coeff_Z=$Coeff_C\n Y-Force=$Coeff_D"      
        
        set olen $Coeff_A$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_Y_Coeff_X" $olen]
  
        set olen $Coeff_B$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_Y_Coeff_Y" $olen]
  
        set olen $Coeff_C$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_Y_Coeff_Z" $olen]
        
        set olen $Coeff_D$unit_const
        set on [DWLocalSetValue $GDN $STRUCT "Y-Force" $olen]      
      }
      
      set pocitej_z [DWLocalGetValue $GDN $STRUCT "Force_Component_Z"]
      #WarnWin "pocitej_x = $pocitej_x"
      if { $pocitej_z == 1 } {
        set delta_H_z [expr $pbhz-$pahz]
        set t_z [expr (-1.0*$delta_H_z)/($soucin_A_delta-$soucin_B_delta)]
  
        set Coeff_A [expr $delta_x*$t_z]
        set Coeff_B [expr $delta_y*$t_z]
        set Coeff_C [expr $delta_z*$t_z]
        set Coeff_D [expr $pahz-($Coeff_A*$pax+$Coeff_B*$pay+$Coeff_C*$paz)]    
        WarnWin "Generated for Z: Comp_Z_Coeff_X=$Coeff_A\n Comp_Z_Coeff_Y=$Coeff_B\n Comp_Z_Coeff_Z=$Coeff_C\n Z-Force=$Coeff_D"      
        
        set olen $Coeff_A$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_Z_Coeff_X" $olen]
  
        set olen $Coeff_B$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_Z_Coeff_Y" $olen]
  
        set olen $Coeff_C$unit_coef
        set on [DWLocalSetValue $GDN $STRUCT "Comp_Z_Coeff_Z" $olen]
        
        set olen $Coeff_D$unit_const
        set on [DWLocalSetValue $GDN $STRUCT "Z-Force" $olen]      
      }           
    }
    #set on [DWLocalSetValue $GDN $STRUCT "Generate" 0] 
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
 }
 return ""
}

proc TK_SPRING_LENGTH { event args } {
 switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   # ...
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
    # Combination_dof_3

    set sc [DWLocalGetValue $GDN $STRUCT "Coordinate_System"]
    set isc [string equal $sc "GLOBAL"]
    if { $isc == 1 } {
      set df1 [DWLocalGetValue $GDN $STRUCT "Dir_X"]
      set df2 [DWLocalGetValue $GDN $STRUCT "Dir_Y"]
      set df3 [DWLocalGetValue $GDN $STRUCT "Dir_Z"]

      set n [GidConvertValueUnit $df1]
      set n [ParserNumberUnit $n df1 unit]
      set n [GidConvertValueUnit $df2]
      set n [ParserNumberUnit $n df2 unit]
      set n [GidConvertValueUnit $df3]
      set n [ParserNumberUnit $n df3 unit]

      set olen [expr sqrt($df1*$df1+$df2*$df2+$df3*$df3)]
      if { $olen == 0.0 } {
        WarnWin [join [list "Bad Length of spring. \n Please, check nonzero vector of direction."]]
      }
       set olen $olen$unit
      set on [DWLocalSetValue $GDN $STRUCT "Spring_Length" $olen]
    }
    return ""
   }
   DEPEND {
   # ...
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
 }
 return ""
}

proc TK_Check_BC_ComplexSupport { event args } {
  # WarnWinText $event

 switch $event {
   INIT {
   # ...
    return ""
   }
   SYNC {
   # ...
    set GDN [lindex $args 0]
    set STRUCT [lindex $args 1]
    set QUESTION [lindex $args 2]
    # Combination_dof_3

    set sc [DWLocalGetValue $GDN $STRUCT "Coordinate_System"]
    set isc [string equal $sc "COMPLEX"]
    if { $isc == 1 } {
      set dof1 [DWLocalGetValue $GDN $STRUCT "Combination_dof_1"]
      set dof2 [DWLocalGetValue $GDN $STRUCT "Combination_dof_2"]
      set dof3 [DWLocalGetValue $GDN $STRUCT $QUESTION]

      set od1 0.0
      set od2 0.0
      set od3 0.0

      if { $dof1 != 0.0 && $dof1 != 0 } {
        set od1 1
      }
      if { $dof2 != 0.0 && $dof2 != 0 } {
        set od2 1
      }
      if { $dof3 != 0.0 && $dof3 != 0 } {
        set od3 1
      }
      set odc [expr $od1+$od2+$od3]
      if { $odc < 2 } {
        WarnWin [join [list "The condition for complex support has to have min. 2 nonzero DoFs. \n Hint: supports in a single global axis direction can be defined in global coordinates easily."]]
      }
    }
    return ""
   }
   DEPEND {
   # ...
    return ""
   }
   CLOSE {
   # ...
    return ""
   }
 }
 return ""
}

proc SelectGIDBatFile { dir basename } {
    #set batfile AtenaWin.bat
    
    set batfile Atena.bat
    return $batfile
    
    #if { [GidUtils::GetProblemDataValue "Calculate_In#CB#(AtenaStudio,AtenaWin,AtenaConsole,AtenaStudio64,AtenaWin64,AtenaConsole64)"] == "AtenaWin" } {
    #  set batfile AtenaWin.bat
    #} elseif { [GidUtils::GetProblemDataValue "Calculate_In#CB#(AtenaStudio,AtenaWin,AtenaConsole,AtenaStudio64,AtenaWin64,AtenaConsole64)"] == "AtenaStudio" } {
    #  set batfile AtenaStudio.bat
    #} elseif { [GidUtils::GetProblemDataValue "Calculate_In#CB#(AtenaStudio,AtenaWin,AtenaConsole,AtenaStudio64,AtenaWin64,AtenaConsole64)"] == "AtenaStudio64" } {
    #  set batfile AtenaStudio64.bat
    #} elseif { [GidUtils::GetProblemDataValue "Calculate_In#CB#(AtenaStudio,AtenaWin,AtenaConsole,AtenaStudio64,AtenaWin64,AtenaConsole64)"] == "AtenaWin64" } {
    #  set batfile AtenaWin64.bat
    #} elseif { [GidUtils::GetProblemDataValue "Calculate_In#CB#(AtenaStudio,AtenaWin,AtenaConsole,AtenaStudio64,AtenaWin64,AtenaConsole64)"] == "AtenaConsole64" } {
    #  set batfile AtenaConsole64.bat
    #} else {        
    #  set batfile AtenaConsole.bat
    #}
    #return $batfile
 }


proc AfterSaveImage { filename format } {
   loadGlobals $filename
}


#proc CheckWriteTest { dir problemtypedir } {
#     set hlaska 0
#
#  # GiD_Process escape escape escape Files WriteForBAS "$problemtypedir/../Include.src.bas/Ver.bas" "$dir\\WriteTest.txt"     set soubor "$dir\\WriteTest.txt" 
#     if { [file exists $soubor] == 1} {
#        set datum [file atime $soubor]
#        set systemTime [clock seconds]
#        set rozdil [expr $systemTime -$datum]
#        #WarnWinText $datum
#        #WarnWinText $systemTime
#        #WarnWinText $rozdil
#
#
#        if { $rozdil >= 5} {
#           set hlaska 1
#        }                   
#        file delete $soubor
#        #set answer [tk_messageBox -message "Delete test file" -type ok -icon warning]
#     } else {
#        set hlaska 1
#     }
#     
#     if { $hlaska == 1} {
#        set answer [tk_messageBox -message "It is not possible to write to the current directory. Please ->Save as<- this project somewhere you have write permission." -type ok -icon warning]
#     }
#}
 
proc BeforeRunCalculation { batfilename basename dir problemtypedir gidexe args } {
     #WarnWinText $batfilename
     #WarnWinText $basename
     #WarnWinText $dir
     #WarnWinText $problemtypedir
    #C:\Program Files (x86)\GiD\GiD 11.0.0-rc3\problemtypes\Atena\Static.gid\AtenaStudio.bat
    #3DBeam_4-after_contacts
    #C:\GiD\ATENA seminar 12 CZ\Den1\Data\V5\3DBeam_4-after_contacts.gid
    #C:\Program Files (x86)\GiD\GiD 11.0.0-rc3\problemtypes\Atena\Static.gid

    set substring "\\\\"
    if {[string first $substring $dir] != -1} {
        #puts "\"$substring\" found in \"$variable\""
        WarnWinText "ERROR: The current directory is $dir. If you are working in a network disk, please map the disk to a letter and open from there, or move your model to a local disk." 
    }

    loadGlobals $dir

    if { [file writable $dir\\$basename.geo] == 0} {
         #set answer [tk_messageBox -message "It is not possible to write to the current directory. Please ->Save as<- this project somewhere you have write permission." -type ok -icon warning]
         Atena_MessageBoxOk "Warning" "It is not possible to write to the current directory. Please ->Save as<- this project somewhere you have write permission." warning
    }
    
    #set a [CheckWriteTest $dir $problemtypedir]

     GiD_Process escape escape escape Files WriteForBAS "$problemtypedir\\..\\Execute\\template_run.bat" "$dir\\copy_inp.bat"
     GiD_Process escape escape escape Files WriteForBAS "$problemtypedir\\..\\Execute\\template_run2console.bat" "$dir\\run_inp_in_AtenaConsole.bat"
    # GiD_Process escape escape escape Files WriteForBAS "$problemtypedir\\..\\Execute\\template_run2win.bat" "$dir\\run_inp_in_AtenaWin.bat"
     GiD_Process escape escape escape Files WriteForBAS "$problemtypedir\\..\\Execute\\template_run2studio.bat" "$dir\\run_inp_in_AtenaStudio.bat"
          
     #set answer [tk_messageBox -message "$problemtypedir/static_template.bat. $dir\\spust.bat" -type ok -icon warning]
   
 }
 
 
proc WriteLinesInfo { num layer_name } {

 return [GiD_Info list_entities lines $num layer:$layer_name ]

# return [GiD_Info list_entities lines $num layer:Cables_Gamma]
# return [GiD_Info list_entities lines $num layer:Cables_Hori]
# return [GiD_Info list_entities lines $num layer:Cables_Vpurs]
}



proc ReinfCheckMonitor { eNum vName} {
# jumbo - zapise monitory pro vyztuz. 
 set cond [GiD_Info conditions "Monitor_for_Reinforcement" -interval 1 mesh $eNum]
 
 set a ""
 set b ""
 set c ""
 set d ""
 set e ""
 set f ""
 set g ""
 set h ""
 set i ""
 set j ""
 set k ""
 set l ""
 set m ""
 set n ""
 set o ""
 set p ""
 set q ""    
 set nazev ""
 set ar ""
 set as ""
 set at ""
 set au ""
 set av ""
 set aw ""
 set ax ""
 
# WarnWinText "***************" 
# WarnWinText $cond 

set writen -1

if {$cond == ""} {
  #WarnWinText "**************nic*"
} else {
  #WarnWinText "***************mam "
  set writen 0
}
if {[string first "\{" $cond 3] != -1} {
        #WarnWinText "found"
    set prvni [string first "\{" $cond 3]
        #WarnWinText "prvni = $prvni"
    set prvniplus [ expr $prvni+3]
        #WarnWinText "prvniplus = $prvniplus"
    set druhy [string first "\}" $cond $prvniplus]
        #WarnWinText "druhy = $druhy"
    set nazev_delka [ expr $druhy - $prvni]
    set nazev2 [string range $cond [expr $prvni+1] [expr $druhy-1]  ]
        #WarnWinText "nazev2 = $nazev2"   
    #set nazev3 [regsub " " $nazev2 "_"] 
    set nazev [string map {" " "_"} $nazev2]
        #WarnWinText "nazev = $nazev"
    set zacatek [string range $cond 0 [expr $prvni]  ]
        #WarnWinText "zacatek = $zacatek"
    set konec [string range $cond $druhy 1000]
        #WarnWinText "konec = $konec"
        
    #zacatek = {E 82 - 0 {
    #konec = } 1 1 0 0 0 0 149 0 0 0 0 0 0 0 0}        
    scan $zacatek "\{E %d - %d \{" a b          
               scan $konec "\} %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d" c d e f g i h j k l m n o p q ar as at au av aw ax  
} else {
    scan $cond "\{E %d - %d %s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d" a b nazev c d e f g i h j k l m n o p q ar as at au av aw ax 
}

#E 2433 - 0 Eps_204 0 0 0 0 0 0 17591 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
#E 2436 - 0 Eps_203 1 0 1 0 0 0 17594 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1

 
 #     a - b nazev   c d e f g i h
 #  {E 5 - 0 Monitor 1 0 1 0 1 0 6} 


 
# WarnWinText $nazev 
# c - max stress
# d - min stress
# e - max strain
# f - min strain
# g - max plastic strain
# i - min plastic strain
# h - entity number
# j - Monitor_Min_Bond_Slip
# k - Monitor_Max_Bond_Slip
# l - Monitor_Min_Bond_Stress
# m - Monitor_Max_Bond_Stress

# j - Monitor_Min_Bond_Slip_Delta_Slip#CB#(0,1)
# k - Monitor_Max_Bond_Slip_Delta_Slip#CB#(0,1)
# l - Monitor_Min_Bond_Stress_Bond_Force#CB#(0,1)
# m - Monitor_Max_Bond_Stress_Bond_Force#CB#(0,1)
# n - Monitor_Min_Bond_Slip_Total_Slip#CB#(0,1)
# o - Monitor_Max_Bond_Slip_Total_Slip#CB#(0,1)
# p - Monitor_Min_Bond_Stress_Bond_Stress#CB#(0,1)
# q - Monitor_Max_Bond_Stress_Bond_Stress#CB#(0,1)

#ar  Monitor_Aver_Stress#CB#(0,1)
#as QUESTION: Monitor_Aver_Strain#CB#(0,1)
#at QUESTION: Monitor_Aver_Plastic_Strain#CB#(0,1)
#au QUESTION: Monitor_Aver_Bond_Slip_Delta_Slip#CB#(0,1)
#av QUESTION: Monitor_Aver_Bond_Stress_Bond_Force#CB#(0,1)
#aw QUESTION: Monitor_Aver_Bond_Slip_Total_Slip#CB#(0,1)
#ax QUESTION: Monitor_Aver_Bond_Stress_Bond_Stress#CB#(0,1)

set t ""
set monitornavic ""

      if { $b == 0 } {
        set moni "MONITOR_2"
      } else {
        set moni "MONITOR_1 EACH ITERATION"
      }
      
# set t "$t a:$a \n"
# set t "$t b:$b \n"
# set t "$t c:$c \n"
# set t "$t d:$d \n"
# set t "$t e:$e \n"
# set t "$t f:$f \n"
# set t "$t g:$g \n"
# set t "$t h:$h \n"
# set t "$t nazev:$nazev \n"
# set t "$t cond:$cond \n"



      if { $nazev == "" } {
        set nazev "ReinfMonitor"
      }

      if { $c == 1 } {
        #set t "$t \nOutput Name \"$nazev MAX_STRESS $vName\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"STRESS\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MAX_STRESS\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }

      if { $d == 1 } {
        #set t "$t \nOutput Name \"$nazev MIN_STRESS $vName\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"STRESS\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MIN_STRESS\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }

      if { $e == 1 } {
        #set t "$t \nOutput Name \"$nazev MAX_STRAIN $vName\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"STRAIN\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MAX_STRAIN\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }

      if { $f == 1 } {
        #set t "$t \nOutput Name \"$nazev MIN_STRAIN $vName\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"STRAIN\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MIN_STRAIN\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      
      if { $g == 1 } {
        #set t "$t \nOutput Name \"$nazev MAX_PLASTIC_STRAIN $vName\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"PLASTIC_STRAIN\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MAX_PLASTIC_STRAIN\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      
      if { $i == 1 } {
        #set t "$t \nOutput Name \"$nazev MIN_PLASTIC_STRAIN $vName\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"PLASTIC_STRAIN\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MIN_PLASTIC_STRAIN\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      
      
      if { $j == 1 } {
        #set t "$t \nOutput Name \"$nazev MIN_BOND_SLIP_1 $vName\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_SLIP\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MIN_BOND_SLIP_1\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $k == 1 } {
        #set t "$t \nOutput Name \"$nazev MAX_BOND_SLIP_1 $vName\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_SLIP\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MAX_BOND_SLIP_1\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $l == 1 } {
        #set t "$t \nOutput Name \"$nazev MIN_BOND_STRESS_1 $vName\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_STRESS\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MIN_BOND_STRESS_1\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $m == 1 } {
        #set t "$t \nOutput Name \"$nazev MAX_BOND_STRESS_1 $vName\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_STRESS\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-MAX_BOND_STRESS_1\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }                        

      if { $n == 1 } {
        #set t "$t \nOutput Name \"$nazev MIN_BOND_SLIP_2 $vName\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_SLIP\" ITEM AT 2 End ; \n
        set t "$t \n SELECTION \"$nazev-MIN_BOND_SLIP_2\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $o == 1 } {
        #set t "$t \nOutput Name \"$nazev MAX_BOND_SLIP_2 $vName\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_SLIP\" ITEM AT 2 End ; \n
        set t "$t \n SELECTION \"$nazev-MAX_BOND_SLIP_2\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $p == 1 } {
        #set t "$t \nOutput Name \"$nazev MIN_BOND_STRESS_2 $vName\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_STRESS\" ITEM AT 2 End ; \n
        set t "$t \n SELECTION \"$nazev-MIN_BOND_STRESS_2\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $q == 1 } {
        #set t "$t \nOutput Name \"$nazev MAX_BOND_STRESS_2 $vName\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_STRESS\" ITEM AT 2 End ; \n
        set t "$t \n SELECTION \"$nazev-MAX_BOND_STRESS_2\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }    

      if { $ar == 1 } {
        #set t "$t \nOutput Name \"$nazev AVER_STRESS $vName\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"STRESS\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-AVER_STRESS\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $as == 1 } {
        #set t "$t \nOutput Name \"$nazev AVER_STRAIN $vName\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"STRAIN\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-AVER_STRAIN\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }      
      if { $at == 1 } {
        #set t "$t \nOutput Name \"$nazev AVER_PLASTIC_STRAIN $vName\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"PLASTIC_STRAIN\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-AVER_PLASTIC_STRAIN\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $au == 1 } {
        #set t "$t \nOutput Name \"$nazev AVER_BOND_SLIP_1 $vName\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_SLIP\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-AVER_BOND_SLIP_1\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $av == 1 } {
        #set t "$t \nOutput Name \"$nazev AVER_BOND_STRESS_1 $vName\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_STRESS\" ITEM AT 1 End ; \n
        set t "$t \n SELECTION \"$nazev-AVER_BOND_STRESS_1\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }                        
      if { $aw == 1 } {
        #set t "$t \nOutput Name \"$nazev AVER_BOND_SLIP_2 $vName\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_SLIP\" ITEM AT 2 End ; \n
        set t "$t \n SELECTION \"$nazev-AVER_BOND_SLIP_2\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }
      if { $ax == 1 } {
        #set t "$t \nOutput Name \"$nazev AVER_BOND_STRESS_2 $vName\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"\$N\$ME$h\" DATA LIST \"BOND_STRESS\" ITEM AT 2 End ; \n
        set t "$t \n SELECTION \"$nazev-AVER_BOND_STRESS_2\" INSERT \"\$N\$ME$h\" \n"
        set writen 1
      }    

      if { $writen == 0 } {
         TK_WarnWinText "Warning: Monitor with name $nazev does not have any checked field. "
      }


      if { $c == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MAX_STRESS\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MAX_STRESS\" DATA LIST \"STRESS\" ITEM AT 1 End ; \n"
      }

      if { $d == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MIN_STRESS\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MIN_STRESS\" DATA LIST \"STRESS\" ITEM AT 1 End ; \n"
      }

      if { $e == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MAX_STRAIN\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MAX_STRAIN\" DATA LIST \"STRAIN\" ITEM AT 1 End ; \n"
      }

      if { $f == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MIN_STRAIN\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MIN_STRAIN\" DATA LIST \"STRAIN\" ITEM AT 1 End ; \n"
      }
      
      if { $g == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MAX_PLASTIC_STRAIN\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MAX_PLASTIC_STRAIN\" DATA LIST \"PLASTIC_STRAIN\" ITEM AT 1 End ; \n"
      }
      
      if { $i == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MIN_PLASTIC_STRAIN\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MIN_PLASTIC_STRAIN\" DATA LIST \"PLASTIC_STRAIN\" ITEM AT 1 End ; \n"
      }    
      
      if { $j == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MIN_BOND_SLIP - Delta_Slip\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MIN_BOND_SLIP_1\" DATA LIST \"BOND_SLIP\" ITEM AT 1 End ; \n"
      }    
      if { $k == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MAX_BOND_SLIP - Delta_Slip\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MAX_BOND_SLIP_1\" DATA LIST \"BOND_SLIP\" ITEM AT 1 End ; \n"
      }    
      if { $l == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MIN_BOND_STRESS - Bond_Force\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MIN_BOND_STRESS_1\" DATA LIST \"BOND_STRESS\" ITEM AT 1 End ; \n"
      }    
      if { $m == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MAX_BOND_STRESS - Bond_Force\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MAX_BOND_STRESS_1\" DATA LIST \"BOND_STRESS\" ITEM AT 1 End ; \n"
      }      
      
      if { $n == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MIN_BOND_SLIP - Total_Slip\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MIN_BOND_SLIP_2\" DATA LIST \"BOND_SLIP\" ITEM AT 2 End ; \n"
      }    
      if { $o == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MAX_BOND_SLIP - Total_Slip\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MAX_BOND_SLIP_2\" DATA LIST \"BOND_SLIP\" ITEM AT 2 End ; \n"
      }    
      if { $p == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MIN_BOND_STRESS - Bond_Stress\" \n$moni MINIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MIN_BOND_STRESS_2\" DATA LIST \"BOND_STRESS\" ITEM AT 2 End ; \n"
      }    
      if { $q == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev MAX_BOND_STRESS - Bond_Stress\" \n$moni MAXIMUM LOCATION NODES NODE AT SELECTION \"$nazev-MAX_BOND_STRESS_2\" DATA LIST \"BOND_STRESS\" ITEM AT 2 End ; \n"
      }  
      
      if { $ar == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev AVER_STRESS\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"$nazev-AVER_STRESS\" DATA LIST \"STRESS\" ITEM AT 1 End ; \n"
      }
      if { $as == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev AVER_STRAIN\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"$nazev-AVER_STRAIN\" DATA LIST \"STRAIN\" ITEM AT 1 End ; \n"
      }
      if { $at == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev AVER_PLASTIC_STRAIN\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"$nazev-AVER_PLASTIC_STRAIN\" DATA LIST \"PLASTIC_STRAIN\" ITEM AT 1 End ; \n"
      }
      if { $au == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev AVER_BOND_SLIP - Delta_Slip\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"$nazev-AVER_BOND_SLIP_1\" DATA LIST \"BOND_SLIP\" ITEM AT 1 End ; \n"
      }    
      if { $av == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev AVER_BOND_STRESS - Bond_Force\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"$nazev-AVER_BOND_STRESS_1\" DATA LIST \"BOND_STRESS\" ITEM AT 1 End ; \n"
      }      
      if { $aw == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev AVER_BOND_SLIP - Total_Slip\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"$nazev-AVER_BOND_SLIP_2\" DATA LIST \"BOND_SLIP\" ITEM AT 2 End ; \n"
      }    
      if { $ax == 1 } {
        set monitornavic "$monitornavic \nOutput Name \"$nazev AVER_BOND_STRESS - Bond_Stress\" \n$moni AVERAGE LOCATION NODES NODE AT SELECTION \"$nazev-AVER_BOND_STRESS_2\" DATA LIST \"BOND_STRESS\" ITEM AT 2 End ; \n"
      }        
      set t "$t\n $monitornavic\n\n"

return "$t" 
} 
 
 
proc Find_Elem_of_Line_num_of_Node_num { lineNum nodeNum notElemNum firstElem } {
 #ZJ_WriteTime 3
 #WarnWinText "vstup Find_Elem_of_Line_num_of_Node_num lineNum=$lineNum,nodeNum=$nodeNum, notElemNum=$notElemNum, firstElem=$firstElem"
 # WarnWinText "lineNum=$lineNum; nodeNum=$nodeNum; notElemNum=$notElemNum"
 set neret ""
 set aelems [GiD_Info conditions -interval 1 "Reinforcement_Elems_Identification" mesh]
 set e_len [llength $aelems]
 #WarnWinText "e_len = $e_len "
 set IsQuadratic [lindex [GiD_Info Project] 5]
 #ZJ_WriteTime pred1
 for {set i 0 } { $i < $e_len } { set i [expr $i + 1] } {
  set cnd_elem  [lindex $aelems $i]
  #WarnWinText "i= $i --- cnd_elem = $cnd_elem "

      #set internal_num [lindex $cnd_elem 3]
     #WarnWinText "internal_num = [lindex $cnd_elem 3], lineNum=$lineNum"
     if { [lindex $cnd_elem 3] == $lineNum } { 
  
   #set numElem  [lindex $cnd_elem 1]
   #WarnWinText "numElem = [lindex $cnd_elem 1], notElemNum=$notElemNum"
   if { [lindex $cnd_elem 1] != $notElemNum } {
        set numElem  [lindex $cnd_elem 1]

    
     
       set ennnm [GiD_Info Mesh Elements Linear $numElem]
       #WarnWinText "ennnm = $ennnm"
       set n1 [lindex $ennnm 1]
       set n2 [lindex $ennnm 2]
       if { $nodeNum == $n1 } {
          if { $firstElem==$numElem } {
            return ""
          }
         #set neret $n2
         #lappend neret [lindex $ennnm 0]
         #ZJ_WriteTime po1b
         #WarnWinText "return neret= $neret"
         #return $neret
         return [list $n2 [lindex $ennnm 0]]
         
       } elseif { $nodeNum == $n2 } {
          if { $firstElem==$numElem } {
            return ""
          }
         #set neret $n1
         #lappend neret [lindex $ennnm 0]
         #ZJ_WriteTime po1a
         #WarnWinText "return neret= $neret"
         #return $neret
         return [list $n1 [lindex $ennnm 0]]
       }
     }
   }
 }
# return $neret
 return ""
}

proc lremove {l p} {
    #set p [lsearch -exact $l $p]
    return "[lrange $l 0 $p-1] [lrange $l $p+1 end]"
}
 


proc Find_End_of_Line_num { lineNum } {
 #ZJ_WriteTime 3
 #WarnWinText "vstup Find_End_of_Line_num lineNum=$lineNum"
 set ret ""
 set eret ""
 set neret ""
 set aelems [GiD_Info conditions -interval 1 "Reinforcement_Elems_Identification" mesh]
 set e_len [llength $aelems]
 set IsQuadratic [lindex [GiD_Info Project] 5]
 set last ""

 for {set i 0 } { $i < $e_len } { set i [expr $i + 1] } {
  set cnd_elem  [lindex $aelems $i]
   set numElem  [lindex $cnd_elem 1]
   set internal_num [lindex $cnd_elem 3]

   if { $internal_num == $lineNum } {
    set ennnm [GiD_Info Mesh Elements Linear $numElem]
    
    #WarnWinText "ennnm=$ennnm"
    # if { $IsQuadratic==1 } {
    #  lappend ret [lindex $ennnm 1] [lindex $ennnm 3] [lindex $ennnm 2]
    #  lappend eret $numElem $numElem
    # } else {
    
#    set n_ret [llength $ret]
#    set n_retminus [expr [llength $ret] -1]
#    #WarnWinText "Compare [lindex $ennnm 1] and ($last), n_ret=$n_ret"
#    if {[lindex $ennnm 1] == $last } {
#      #WarnWinText "Delete from $ret polozku # $n_ret-1"
#      set ret [lremove $ret $n_retminus]
#      set eret [lremove $eret $n_retminus]
#      #WarnWinText "Zbylo $ret" 
#      set last [lindex $ennnm 2]
#      lappend ret [lindex $ennnm 2]
#      lappend eret $numElem      
#    } elseif { [lindex $ennnm 2] == $last }  {
#      #WarnWinText "Delete2 from $ret polozku # $n_ret-1"
#      set ret [lremove $ret $n_retminus]
#      set eret [lremove $eret $n_retminus]
#      #WarnWinText "Zbylo $ret" 
#      set last [lindex $ennnm 1]
#      lappend ret [lindex $ennnm 1]
#      lappend eret $numElem      
#    } else {
#      set last [lindex $ennnm 2]
      lappend ret [lindex $ennnm 1] [lindex $ennnm 2]
      #lappend ret [lindex $ennnm 1] [lindex $ennnm 2]
      lappend eret $numElem $numElem
#      }
      #WarnWinText "Find_End_of_Line_num 1 lineNum=$lineNum, ret=$ret eret=$eret"
    # }
  }
 }
 # WarnWinText "lineNum=$lineNum; eret=$eret; ret=$ret; IsQuadratic=$IsQuadratic"



# promazani pole ret a eret, vyhozeni zdublovanych nodu, ktery urcite jsou vnitrni a tim padem je neni treba testovat
#WarnWinText "Ret = $ret"
#WarnWinText "eret = $eret"
set n_len [llength $ret]
set ret2 [lindex $ret 0]
set eret2 [lindex $eret 0]
for { set i 1 } { $i < $n_len } { set i [expr $i + 1] } {

   if { [lindex $ret $i] == [lindex $ret [expr $i + 1]] } {
   set i [expr $i + 1]
   } else {
   set test_node [lindex $ret $i]
   lappend ret2 [lindex $ret $i]
   lappend eret2 [lindex $eret $i]
   }
} 
set ret $ret2
set eret $eret2
#WarnWinText "Ret po = $ret"
#WarnWinText "eret po = $eret"
# promazani pole ret a eret, konec


 #ZJ_WriteTime pred
 set n_len [llength $ret]
 # WarnWinText "n_len=$n_len"
 set internal 0
 for { set i 0 } { $i < $n_len } { set i [expr $i + 1] } {
  set test_node [lindex $ret $i]
  set internal 0
  set numElem [lindex $eret $i]
  #WarnWinText "test_node =$test_node "
  for { set j [expr $i+1] } { $j < $n_len } { set j [expr $j + 1] } {
    set next_node [lindex $ret $j]
    #WarnWinText "test_node =$test_node, next_node=$next_node "
    if { $test_node == $next_node } {
     set internal 1
    }
  }
  if { $internal == 0 } {
    #set neret $test_node
    #lappend neret $numElem
    #WarnWinText "neret=$neret; internal=$internal"
    #ZJ_WriteTime po
    #return $neret
    return [list $test_node $numElem]
  }
 }
 
  #WarnWinText "neret=$neret; internal=$internal"
 return $neret
}

proc Nodes_of_Line { lineNum oQuadAproxFlag} {
 #ZJ_WriteTime Nodes_of_Line
 #WarnWinText "vstup Nodes_of_Line lineNum=$lineNum, oQuadAproxFlag=$oQuadAproxFlag"
 set IsQuadratic [lindex [GiD_Info Project] 5]
 set internal_entity_num 0

 set EOL_NodeNum_ElemNum [Find_End_of_Line_num $lineNum]
 set ret  [lindex $EOL_NodeNum_ElemNum 0]
 set numElem [lindex $EOL_NodeNum_ElemNum 1]
 set first_element $numElem
 set ennnm [GiD_Info Mesh Elements Linear $numElem]
 
 if { [lindex $EOL_NodeNum_ElemNum 0]==[lindex $ennnm 1] } {
 
   if { $IsQuadratic == 1 && $oQuadAproxFlag == 1 } {
      lappend ret [lindex $ennnm 3] [lindex $ennnm 2]
   } else {
      lappend ret [lindex $ennnm 2]
   }
   set last_node [lindex $ennnm 2]
   
 } else {
   if { $IsQuadratic == 1 && $oQuadAproxFlag == 1 } {
   
      lappend ret [lindex $ennnm 3] [lindex $ennnm 1]
   } else {
      lappend ret [lindex $ennnm 1]
   }
   set last_node [lindex $ennnm 1]
   
 }
 # WarnWinText "Find_End_of_Line_num=$EOL_NodeNum_ElemNum; last_node=$last_node"
# return ""

 set aelems [GiD_Info conditions -interval 1 "Reinforcement_Elems_Identification" mesh]
 set e_len [llength $aelems]

 set podminka [Find_Elem_of_Line_num_of_Node_num $lineNum $last_node $numElem $first_element]
 # WarnWinText "numElem=$numElem"
  #WarnWinText "podminka Find_Elem_of_Line_num_of_Node_num == $podminka"
  #ZJ_WriteTime predwhile
 while { [llength $podminka] > 0 } {
   set numElem [lindex $podminka 1]
   # WarnWinText "numElem=$numElem"
   set ennnm [GiD_Info Mesh Elements Linear $numElem]
   set nalezeny_posledni_node [lindex $podminka 0]
   if { $nalezeny_posledni_node==[lindex $ennnm 1] } {
     if { $IsQuadratic==1 && $oQuadAproxFlag == 1 } {
        lappend ret [lindex $ennnm 3] [lindex $ennnm 1]
     } else {
        lappend ret [lindex $ennnm 1]
     }
     set last_node [lindex $ennnm 1]
   } else {
     if { $IsQuadratic==1 && $oQuadAproxFlag == 1 } {
        lappend ret [lindex $ennnm 3] [lindex $ennnm 2]
     } else {
        lappend ret [lindex $ennnm 2]
     }
     set last_node [lindex $ennnm 2]
   }
   # WarnWinText "ret=$ret"
   set podminka [Find_Elem_of_Line_num_of_Node_num $lineNum $last_node $numElem $first_element]
   #WarnWinText "Find_Elem_of_Line_num_of_Node_num=$podminka"
# return ""
 }
 #ZJ_WriteTime powhile
 if { $ret == "" } {
   set text "Probably line num $lineNum has not assignment BC Reinforcement_Elem_Identification"
   #tk_messageBox -icon error -title [_ "Error:"] -type ok -message "$text"
   Atena_MessageBoxOk "ATENA-GiD Error" "$text" error       
 }
 return $ret
}

proc NodesWithMaterial_And_EntityNum { matname entity_num } {
 #return the node list of the elements with matname, ordered and without repetition
 set ret ""
 set last_node_num ""

 set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]
 if { $internalmatnum == 0 } {
  return ""
 }

 foreach truss_elems [lrange [GiD_Info mesh] 2 2 ] {
   WarnWinText "truss_elems=$truss_elems"
   # return "ahoj"
  set elems [GiD_Info mesh elements $truss_elems]
  foreach "num n1 n2 mat" $elems {
   if { $mat == $internalmatnum } {
    if { $last_node_num == $n1 } {
     lappend ret $n2
      set last_node_num $n2
    } else {
      lappend ret $n1
     set last_node_num $n1
    }
   }
  }
 }
 return $ret
}

proc NodesWithMaterial { matname } {
 #return the node list of the elements with matname, ordered and without repetition
 set ret ""
 set ret2 ""
 set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]
 if { $internalmatnum == 0 } {
  return ""
 }
 set IsQuadratic [lindex [GiD_Info Project] 5]
# return $internalmatnum
 foreach elemtype [lrange [GiD_Info mesh] 1 end] {
   set elems [GiD_Info mesh elements $elemtype]
   # set nnodes 20
   # set nnodes [expr [llength $elems]-2]

   if { $elemtype == "Triangle" && $IsQuadratic == 0} {
     foreach "num n1 n2 n3 mat" $elems {
     # set nnodes [GiD_Mesh element $num nnode]
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3
#       return "1"
       }
     }
   } elseif { $elemtype == "Triangle" && $IsQuadratic == 1} {
     foreach "num n1 n2 n3 n4 n5 n6 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4 $n5 $n6
#       return "1"
       }
     }
   } elseif { $elemtype == "Quadrilateral" && $IsQuadratic == 0} {
     foreach "num n1 n2 n3 n4 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4
#       return "2"
       }
     }
   } elseif { $elemtype == "Quadrilateral" && $IsQuadratic == 1} {
     foreach "num n1 n2 n3 n4 n5 n6 n7 n8 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8
#       return "2"
       }
     }
   } elseif { $elemtype == "Tetrahedra" && $IsQuadratic == 0} {
     foreach "num n1 n2 n3 n4 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4
#       return "3"
       }
     }
   } elseif { $elemtype == "Tetrahedra" && $IsQuadratic == 1} {
     foreach "num n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8 $n9 $n10
#       return "3"
       }
     }
   } elseif { $elemtype == "Prism" && $IsQuadratic == 0} {
     foreach "num n1 n2 n3 n4 n5 n6 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4 $n5 $n6
#       return "4"
       }
     }
   } elseif { $elemtype == "Prism" && $IsQuadratic == 1} {
     foreach "num n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 n15 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8 $n9 $n10 $n11 $n12 $n13 $n14 $n15
#       return "4"
       }
     }
   } elseif { $elemtype == "Hexahedra" && $IsQuadratic == 0} {
     foreach "num n1 n2 n3 n4 n5 n6 n7 n8 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8
#       return "5"
       }
#       lappend ret2 $mat
#       $internalmatnum $num $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8
#       return $ret2
     }
   } elseif { $elemtype == "Hexahedra" && $IsQuadratic == 1} {
     foreach "num n1 n2 n3 n4 n5 n6 n7 n8 n9 n10 n11 n12 n13 n14 n15 n16 n17 n18 n19 n20 mat" $elems {
     # set nnodes [GiD_Mesh element $num nnode]
     # set a [GiD_Info list_entities PreElements $num]

       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8 $n9 $n10 $n11 $n12 $n13 $n14 $n15 $n16 $n17 $n18 $n19 $n20
#       return "5"
       }
#       lappend ret2 $mat
#       $internalmatnum $num $n1 $n2 $n3 $n4 $n5 $n6 $n7 $n8 $n9 $n10 $n11 $n12 $n13 $n14 $n15 $n16 $n17 $n18 $n19 $n20
#       return $ret2
     }
   } elseif { $elemtype == "Linear" && $IsQuadratic == 0} {
     foreach "num n1 n2 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2
#       return "6"
       }
     }
   } elseif { $elemtype == "Linear" && $IsQuadratic == 1} {
     foreach "num n1 n2 n3 mat" $elems {
       if { $mat == $internalmatnum } {
        lappend ret $n1 $n2 $n3
#       return "6"
       }
     }
   } else {
    return -1
   }
 }
# return $ret2
 set ret [lsort -integer -unique $ret]
 return $ret
}

# proc userHelpWindow {} {
# exec NOTEPAD.EXE
# }

proc AddItem2Array { array item } {
  set NumCells [lindex $array 1]
  set fval  [lindex $array 2]
  if { $NumCells == 1 && $fval == -1 } {
    set NumCells 0
  }
  set oArray "#N# [expr $NumCells+1]"
#  WarnWinText "oArray =$oArray"

  for {set j 2} {$j <= [expr $NumCells+1]} {set j [expr $j+1]} {
    lappend oArray [lindex $array $j]
  }
  lappend oArray $item
#  WarnWinText "oArray =$oArray"
  return $oArray
}

proc TK_Check_Warning_Spring_Beam_Shell { matname elementId } {
  set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]
  set prototype [GiD_AccessValue get materials $matname "Material_Prototype"]  
set oCCShellMaterial [string equal $prototype "CCShellMaterial"]
set oCCBeam3DMaterial [string equal $prototype "CCBeam3DMaterial"] 
if { $oCCBeam3DMaterial==1 } {
    WarnWinText "Warning: Some springs are assigned on element id $elementId with beam material. Some nodes may not be connected. Use preferably spring material with duplicated surfaces and master-slave connection."   
}
if { $oCCShellMaterial==1 } {
    WarnWinText "Warning: Some springs are assigned on element id $elementId with shell material. Some nodes may not be connected. Use preferably spring material with duplicated surfaces and master-slave connection."   
}
 return ""
} 

proc TK_WriteElementType2Activity { matname oElemsType oElemsNnode oAddTranspAnalysis groupID } {
  set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]

  if { $internalmatnum == 0 } {
   return ""
  }
  set prototype [GiD_AccessValue get materials $matname "Material_Prototype"]
  set geomNonlinearity [GiD_AccessValue get materials $matname "Geometrical_Non-Linearity"]
  set inactiveElementsWithError [GiD_AccessValue get materials $matname "Inactive_elements_with_error"]
  set ignoreNegativeJacobian [GiD_AccessValue get materials $matname "Ignore_negative_Jacobian"]
  set MaterialQuadratic [GiD_AccessValue get materials $matname "Non-Quadratic_Element"]
  set oIsQuadratic [GiD_Info Project Quadratic]
  set oIsAxysymmetricTask [GiD_AccessValue get genData Axi_symmetric_task]

  set ignoreText ""
if ($inactiveElementsWithError==1) {
    append ignoreText " IGNORE_ELEMENT_TYPE_EXCEPTION "
}
if ($ignoreNegativeJacobian==1) {
    append ignoreText " IGNORE_NEGATIVE_JACOBIAN "
}

if ($MaterialQuadratic==1) {

  if ($oIsQuadratic==1) {  
    if ($oElemsNnode==6) { set oElemsNnode 3 
    } elseif ($oElemsNnode==8) { set oElemsNnode 4
    } elseif ($oElemsNnode==10) { set oElemsNnode 4
    } elseif ($oElemsNnode==15) { set oElemsNnode 6
    } elseif ($oElemsNnode==20) { set oElemsNnode 8
    }
  }
  set oIsQuadratic 0
  
} else {
  set oIsQuadratic [GiD_Info Project Quadratic]
}

#
#   ElemsType:
#       1=Linear,
#       2=Triangle,
#       3=Quadrilateral,
#       4=Tetrahedra,
#       5=Hexahedra,
#       6=Prism,
#       7=OnlyPoints.
#
#  podle poctu uzlu "ElemsnNode" se nepozna jednoznacne co je to za prvek!
#  nnode 2 ... je Truss
#   3 ... je linearni Triangle || kvadraticky Truss
#   4 ... je linearni Quad || Tetrahedron || bikvadraticky Truss
#   6 ... je kvadraticky Triangle || linearni Prism(Wedge)
#   8 ... je linearni Hexahedron || kvadraticky Quad
#   9 ... je bikvadraticky triangle
#   10 ... je kvadraticky Tetrahedron
#   12 ... je bikvadraticky Quad
#   16 ... je bikvadraticky Tetrahedron
#   20 ... je kvadraticky Hexahedron
#   32 ... je bikvadraticky Hexahedron
#

set oGeometricalNonLinearity [string equal $geomNonlinearity "NONLINEAR"]

set oCC2DInterface [string equal $prototype "CC2DInterface"]
set oCC3DInterface [string equal $prototype "CC3DInterface"]
set oCCModelBaXi94 [string equal $prototype "CCModelBaXi94"]
set oCCModelTranport [string equal $prototype "CCTransportMaterial"]
set oCCModelTranportLevel7 [string equal $prototype "CCTransportMaterialLevel7"]
set oCCSpring [string equal $prototype "CCSpringMaterial"]

if { $oCCModelTranport==1 || $oCCModelTranportLevel7==1 } {
set oCCModelBaXi94 1
}

set oCCShellMaterial [string equal $prototype "CCShellMaterial"]
set oCCBeam3DMaterial [string equal $prototype "CCBeam3DMaterial"]


# check if in beam 3d is beam3d and beam 1d is beam1d
if { $oCCBeam3DMaterial==1 } {
   set oIDealisation [GiD_AccessValue get materials $matname "Idealisation"]
   if { $oIDealisation=="Beam1D" && ( $oElemsType==4 || $oElemsType==5 || $oElemsType==6 )  } {
     WarnWinText "Error: Geometry 3D, but Idealisation is Beam1D in material $matname !"
     error "Error: Geometry 3D, but Idealisation is Beam1D in material $matname ! Stop writing inp. (It is not error in this file) "
     #tk_messageBox -icon error -message "Geometry 3D, but Idealisation is Beam1D in material $matname !" -icon error -type ok
   }
   if { $oIDealisation=="Beam3D" && ( $oElemsType==1 || $oElemsType==2 || $oElemsType==3 )  } {
     WarnWinText "Error: Geometry is not 3D, but Idealisation isBeam3D in material $matname !"
     error "Error: Geometry is not 3D, but Idealisation isBeam3D in material $matname ! Stop writing inp.  (It is not error in this file)"
   }
}

set oCCReinforcement  [string equal $prototype "CCReinforcement"]
set oCC1DElastic      [string equal $prototype "CC1DElastIsotropic"]
set oCCCyclingReinf   [string equal $prototype "CCCyclingReinforcement"]
set oCCReinfTemDep    [string equal $prototype "CCReinforcementWithTempDepProperties"]
set oCCSteelDRC       [string equal $prototype "CCSteelDRC"]

set oBarWithBond 0
set oCable 0
set uvozovky \"
set reinf1d 0

	if { $oCCReinforcement==1 || $oCC1DElastic==1 || $oCCCyclingReinf==1 || $oCCReinfTemDep==1 || $oCCSteelDRC==1} {
		set reinf1d 1
		set BarWithBond [GiD_AccessValue get materials $matname "Bar_With_Bond"]
		if { $BarWithBond==1 } {
			set oBarWithBond 1
		} else {
			set Cable [GiD_AccessValue get materials $matname "Cable"]
			if { $Cable==1 } {
				set oCable 1
			}
		}
	}

	if { $oIsQuadratic==0 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==5 && $oElemsNnode==8 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoBrick<xxxxxxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==5 && $oElemsNnode==20 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoBrick<xxxxxxxxxxxxxxxxxxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==6 && $oElemsNnode==6 } {
	#
	  WarnWinText "Error: WEDGE For transport analysis is not implemented!"
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoWedge<xxxxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==6 && $oElemsNnode==15 } {
	#
	  WarnWinText "Error: QUADRATIC WEDGE for transport analysis is not implemented!"
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoWedge<xxxxxxxxxxxxxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==4 && $oElemsNnode==4 } {
	#
	  # WarnWinText "Error: TETRAHEDRON for transport analysis is not implemented!"
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoTetra<xxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==4 && $oElemsNnode==10 } {
	#
	  WarnWinText "Error: QUADRATIC TETRAHEDRON for transport analysis is not implemented!"
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoTetra<xxxxxxxxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==3 && $oElemsNnode==4 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoQuad<xxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==3 && $oElemsNnode==8 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoQuad<xxxxxxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==2 && $oElemsNnode==6 } {
	#
	  WarnWinText "Error: QUADRATIC TRIANGLE for transport analysis is not implemented!"
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoTriangle<xxxxxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oAddTranspAnalysis==60 && $oCCModelBaXi94==1 && $oElemsType==2 && $oElemsNnode==3 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"IsoTriangle<xxx>$uvozovky $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oCC2DInterface==1 && $oElemsType==3 && $oElemsNnode==4 && $oIsAxysymmetricTask==1} { 
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oCC2DInterface==1 && $oElemsType==3 && $oElemsNnode==4 && $oIsAxysymmetricTask==0} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oCC2DInterface==1 && $oElemsType==3 && $oElemsNnode==8 && $oIsAxysymmetricTask==1} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oCC2DInterface==1 && $oElemsType==3 && $oElemsNnode==8 && $oIsAxysymmetricTask==0} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oElemsType==4 && $oElemsNnode==4 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoTetra<xxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oCC3DInterface==1 && $oElemsType==5 && $oElemsNnode==20 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxxxxxxxxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oCC3DInterface==1 && $oElemsType==5 && $oElemsNnode==8 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oElemsType==5 && $oElemsNnode==8 && $oCCShellMaterial==0} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoBrick<xxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oCCShellMaterial==1 && ((($oElemsType==5 || $oElemsType==6) && $oElemsNnode==8 ) || ($oElemsType==6 && $oElemsNnode==6) || ($oElemsType==3 && $oElemsNnode==4) || ( $oElemsType==2 && $oElemsNnode==3 ) )  } {
	#
	  set sstress [GiD_AccessValue get materials $matname "Initial_STRESS_Application"]
	  set istress [string equal $sstress "DEFAULT_PROCESSING"]
	  set sstrain [GiD_AccessValue get materials $matname "Initial_STRAIN_Application"]
	  set istrain [string equal $sstrain "DEFAULT_PROCESSING"]
	  # set defaultprocessing [expr $istress+$istrain]

	  set sret "ELEMENT TYPE ID $groupID "
	  if { $istress!=1 } {
	  	lappend sret $sstress
	  #	lappend sret " "
	  }
	  if { $istrain!=1 } {
	  	lappend sret $sstrain
	  #	lappend sret " "
	  }
	  set matelemtype [GiD_AccessValue get materials $matname "Element_Type"]
	  set uret "$sret Name $uvozovky$matname $oElemsType $oElemsNnode Shell Element type$uvozovky TYPE $uvozovky$matelemtype$uvozovky $geomNonlinearity $ignoreText ;"
	  return $uret
	#
	} elseif { $oIsQuadratic==1 && $oCCShellMaterial==1 && ((($oElemsType==5 || $oElemsType==6) && $oElemsNnode==20 ) || ($oElemsType==6 && $oElemsNnode==15) || ($oElemsType==3 && $oElemsNnode==8) || ( $oElemsType==2 && $oElemsNnode==6 ) )  } {
	#
	  set sstress [GiD_AccessValue get materials $matname "Initial_STRESS_Application"]
	  set istress [string equal $sstress "DEFAULT_PROCESSING"]
	  set sstrain [GiD_AccessValue get materials $matname "Initial_STRAIN_Application"]
	  set istrain [string equal $sstrain "DEFAULT_PROCESSING"]
	  # set defaultprocessing [expr $istress+$istrain]

	  set sret "ELEMENT TYPE ID $groupID "
	  if { $istress!=1 } {
	  	lappend sret $sstress
	  #	lappend sret " "
	  }
	  if { $istrain!=1 } {
	  	lappend sret $sstrain
	  #	lappend sret " "
	  }
	  set matelemtype [GiD_AccessValue get materials $matname "Element_Type"]
	  set uret "$sret Name $uvozovky$matname $oElemsType $oElemsNnode Shell Element type$uvozovky TYPE $uvozovky$matelemtype$uvozovky $geomNonlinearity $ignoreText ;"
	  return $uret
	#
	} elseif { $oIsQuadratic==1 && $oCCBeam3DMaterial==1 && $oElemsType==5 && $oElemsNnode==20 } {
	#
	  set matelemtype [GiD_AccessValue get materials $matname "Element_Type"]

	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode Beam Element type$uvozovky TYPE $uvozovky$matelemtype$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oElemsType==5 && $oElemsNnode==20 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoBrick<xxxxxxxxxxxxxxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oCC3DInterface==1 && $oElemsType==6 && $oElemsNnode==6 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oCC3DInterface==1 && $oElemsType==6 && $oElemsNnode==15 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoGap<xxxxxxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oElemsType==6 && $oElemsNnode==6 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoWedge<xxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oElemsType==6 && $oElemsNnode==15 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoWedge<xxxxxxxxxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#                                                                                             
	} elseif { $oIsQuadratic==1 && $oElemsType==4 && $oElemsNnode==10 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoTetra<xxxxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oElemsType==3 && $oElemsNnode==4 && $oCCSpring==1} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCPlaneSpringQuad<xxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oElemsType==3 && $oElemsNnode==4 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoQuad<xxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oElemsType==3 && $oElemsNnode==8 && $oCCSpring==1} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCPlaneSpringQuad<xxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oElemsType==3 && $oElemsNnode==8 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoQuad<xxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
#	} elseif { $oIsQuadratic==1 && $oCCShellMaterial==1 && $oElemsType==3 && $oElemsNnode==8 } {
#	#
#	  return "ELEMENT TYPE2 ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoShellQuad<xxxxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#  
	} elseif { $oIsQuadratic==0 && $oElemsType==2 && $oElemsNnode==3 && $oCCSpring==1} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCPlaneSpring$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==0 && $oElemsType==2 && $oElemsNnode==3 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoTriangle<xxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oElemsType==2 && $oElemsNnode==6 && $oCCSpring==1} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCPlaneSpring$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oIsQuadratic==1 && $oElemsType==2 && $oElemsNnode==6 } {
    #
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoTriangle<xxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
    #
#	} elseif { $oIsQuadratic==1 && $oCCShellMaterial==1 && $oElemsType==2 && $oElemsNnode==6 } {
#	  return "ELEMENT TYPE2 ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoShellTriangle<xxxxxx>$uvozovky $geomNonlinearity $ignoreText ;"
#  #
	} elseif { $oBarWithBond==1 && $oElemsType==1 && ($oElemsNnode==2 || $oElemsnNode==3)  } {
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCBarWithBond$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $oCable==1 && $oElemsType==1 && ($oElemsNnode==2 || $oElemsnNode==3)  } {
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCExternalCable$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $reinf1d == 1 && $oIsQuadratic==0 && $oElemsType==1 && $oElemsNnode==2 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoTruss<xx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $reinf1d == 0 && $oIsQuadratic==0 && $oElemsType==1 && $oElemsNnode==2 && $oCCBeam3DMaterial==0} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCLineSpring$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $reinf1d == 0 && $oIsQuadratic==0 && $oElemsType==1 && $oElemsNnode==2 && $oCCBeam3DMaterial==1} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoBeamBar<xx>$uvozovky $geomNonlinearity $ignoreText ;"
	#  
	} elseif { $reinf1d == 1 && $oIsQuadratic==1 && $oElemsType==1 && $oElemsNnode==3 } {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoTruss<xxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $reinf1d == 0 && $oIsQuadratic==1 && $oElemsType==1 && $oElemsNnode==3 && $oCCBeam3DMaterial==0} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCLineSpring$uvozovky $geomNonlinearity $ignoreText ;"
	#
	} elseif { $reinf1d == 0 && $oIsQuadratic==0 && $oElemsType==1 && $oElemsNnode==3 && $oCCBeam3DMaterial==0} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCLineSpring$uvozovky $geomNonlinearity $ignoreText ;"
	#  
	} elseif { $reinf1d == 0 && $oIsQuadratic==1 && $oElemsType==1 && $oElemsNnode==3 && $oCCBeam3DMaterial==1} {
	#
	  return "ELEMENT TYPE ID $groupID Name $uvozovky$matname $oElemsType $oElemsNnode$uvozovky TYPE \"CCIsoBeamBar<xxx>$uvozovky $geomNonlinearity $ignoreText ;"
	#  
	} elseif { $oAddTranspAnalysis==60 && $oElemsType==1 } {
	  WarnWinText "Warning: TRUSS in Transport analysis is not implemented!"
	#
	} else {
	  WarnWinText "Error: Non-signed(nondefined) element type!"
          return "Error: Non-signed(nondefined) element type! IsQuadratic=$oIsQuadratic; ElemsType=$oElemsType; ElemsNnode=$oElemsNnode; AddTranspAnalysis=$oAddTranspAnalysis; GeomNonlinearity=$geomNonlinearity; CCShellMaterial=$oCCShellMaterial; CCBeam3DMaterial=$oCCBeam3DMaterial; oCC2DInterface=$oCC2DInterface; CC3DInterface=$oCC3DInterface; CCModelBaXi94=$oCCModelBaXi94; CCReinforcement=$oCCReinforcement"
	}
	return "error -789"
}

proc TK_WriteShellPrepareCalculation { matname oElemsType oElemsNnode oAddTranspAnalysis groupID } {
	set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]

	if { $internalmatnum == 0 } {
	return ""
	}
	set prototype [GiD_AccessValue get materials $matname "Material_Prototype"]
	set geomNonlinearity [GiD_AccessValue get materials $matname "Geometrical_Non-Linearity"]
	set oIsQuadratic [GiD_Info Project Quadratic]

	set oGeometricalNonLinearity [string equal $geomNonlinearity "NONLINEAR"]
	set oCCShellMaterial [string equal $prototype "CCShellMaterial"]
	set oCCBeam3DMaterial [string equal $prototype "CCBeam3DMaterial"]
	set uvozovky \"
  
	if { $oIsQuadratic==1 && $oCCShellMaterial==1 && $oElemsType==5 && $oElemsNnode==20 } {
	#
	  return "ELEMENT TYPE ID $groupID PREPARE_CALCULATION ;"
	#
	} elseif { $oIsQuadratic==1 && $oCCBeam3DMaterial==1 && $oElemsType==5 && $oElemsNnode==20 } {
	#
	  return "ELEMENT TYPE ID $groupID PREPARE_CALCULATION ;"
	#
	}
	return ""
}

proc TK_ShellCheck { matname oElemsType oElemsNnode oAddTranspAnalysis groupID } {
	set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]

	if { $internalmatnum == 0 } {
	return ""
	}
	set prototype [GiD_AccessValue get materials $matname "Material_Prototype"]
	set geomNonlinearity [GiD_AccessValue get materials $matname "Geometrical_Non-Linearity"]
	set oIsQuadratic [GiD_Info Project Quadratic]

  # // WarnWinText  "$elementType"
	set oGeometricalNonLinearity [string equal $geomNonlinearity "NONLINEAR"]
	set oCCShellMaterial [string equal $prototype "CCShellMaterial"]
	set oCCBeam3DMaterial [string equal $prototype "CCBeam3DMaterial"]
	set uvozovky \"
  
  
  if {$oCCShellMaterial==1} {
  
    set elementType [GiD_AccessValue get materials $matname "Element_Type"]
    
     if {$elementType=="CCIsoShellBrick<xxxxxxxxxxxxxxxx>" && ($oElemsType!=5 || $oElemsNnode!=20) } {
        WarnWinText "Error: Material $matname is assigned on geometry with not adequate element type !"
        WarnWinText "Material = $matname, elementType=$elementType,  oElemsType=$oElemsType,  oElemsNnode= $oElemsNnode"
        error "Error: Material $matname is assigned on geometry with not adequate element type ! Stop writing inp. (It is not error in this file) "
     }
     if {$elementType=="CCIsoShellWedge<xxxxxxxxxxxx>" && ($oElemsType!=6 || $oElemsNnode!=15) } {
        WarnWinText "Error: Material $matname is assigned on geometry with not adequate element type !"
        WarnWinText "Material = matname, elementType=$elementType,  oElemsType=$oElemsType,  oElemsNnode= $oElemsNnode"  
        error "Error: Material $matname is assigned on geometry with not adequate element type ! Stop writing inp. (It is not error in this file) "
     }   
     if {$elementType=="CCIsoShellQuad<xxxxxxxx>" && ($oElemsType!=3 || $oElemsNnode!=8) } {
        WarnWinText "Error: Material $matname is assigned on geometry with not adequate element type !"
        WarnWinText "Material = $matname, elementType=$elementType,  oElemsType=$oElemsType,  oElemsNnode= $oElemsNnode"
        error "Error: Material $matname is assigned on geometry with not adequate element type ! Stop writing inp. (It is not error in this file) "
     }     
     if {$elementType=="CCIsoShellTriangle<xxxxxx>" && ($oElemsType!=2 || $oElemsNnode!=6) } {
        WarnWinText "Error: Material $matname is assigned on geometry with not adequate element type !"
        WarnWinText "Material = $matname, elementType=$elementType,  oElemsType=$oElemsType,  oElemsNnode= $oElemsNnode"
        error "Error: Material $matname is assigned on geometry with not adequate element type ! Stop writing inp. (It is not error in this file) "
     }   
     #WarnWinText "Only info: Material = $matname, elementType=$elementType,  oElemsType=$oElemsType,  oElemsNnode= $oElemsNnode"     
  }  
  
# ElemsType:
#       1=Linear,
#       2=Triangle,
#       3=Quadrilateral,
#       4=Tetrahedra,
#       5=Hexahedra,
#       6=Prism,
#       7=OnlyPoints.
#
#  podle poctu uzlu "ElemsnNode" se nepozna jednoznacne co je to za prvek!
#  nnode 2 ... je Truss
#   3 ... je linearni Triangle || kvadraticky Truss
#   4 ... je linearni Quad || Tetrahedron || bikvadraticky Truss
#   6 ... je kvadraticky Triangle || linearni Prism(Wedge)
#   8 ... je linearni Hexahedron || kvadraticky Quad
#   9 ... je bikvadraticky triangle
#   10 ... je kvadraticky Tetrahedron
#   12 ... je bikvadraticky Quad
#   16 ... je bikvadraticky Tetrahedron
#   20 ... je kvadraticky Hexahedron
#   32 ... je bikvadraticky Hexahedron
  
	return ""
}

proc TK_WriteBeamGeometryActive { matname beamCount } {
	set internalmatnum [expr [lsearch [GiD_Info materials] $matname]+1]

	if { $internalmatnum == 0 } {
	return "TK_WriteBeamGeometryActive non exist material"
	}
#WarnWinText $beamCount
  
set INACTIVE_CELLS [GiD_AccessValue get materials $matname "INACTIVE_CELLS"]  
set jmax [lindex $INACTIVE_CELLS 1]
set txt ""
#WarnWinText "INACTIVE_CELLS  $INACTIVE_CELLS"
#WarnWinText "velikost INACTIVE_CELLS  $jmax"

for {set i 1 } { $i <= $beamCount } { set i [expr $i + 1] } {
#WarnWinText $i
set checkActivity 1
  if { $jmax >=0 } {
    for {set j 2 } { $j <= [expr $jmax + 1] } { set j [expr $j + 1] } {
  	  set inactive [lindex $INACTIVE_CELLS $j]
      
      if { $i == $inactive } {
        set checkActivity 0
      }
      #WarnWinText "i=$i, j=$j, inactive = $inactive, checkActivity = $checkActivity"      
    }
    if { $checkActivity == 1 } {
#         WarnWinText "zapisuji $i"
         lappend txt $i  
    }    
  } else {
#         WarnWinText "zapisuji $i"
         lappend txt $i  
  }
}    
    
#foreach InactiveCell [GiD_AccessValue get materials $matname "INACTIVE_CELLS"] { 
#WarnWinText $InactiveCell
#}
#WarnWinText "result $txt"  
return $txt      
  
}



proc TK_PlusOne { number } {
  set ndiv [expr {int($number+1)}]
  return $ndiv      
}

proc TK_SBETAWarnWin { event args } {
# pokud je arg SBETAMaterial, tak se hodi hlaska, ze se meni IDEALISATION
     switch $event {
	 INIT {
	  # do nothing here
	  return ""
	 }
	 SYNC {
	  set GDN [lindex $args 0]
	  set STRUCT [lindex $args 1]
	  set QUESTION [lindex $args 2]


        # set oBaseMaterial [GiD_AccessValue get materials $QUESTION]
  	set BaseMaterial [DWLocalGetValue $GDN $STRUCT $QUESTION]
	#  && $oBaseMaterial == $BaseMaterial
	if { $BaseMaterial == "CCSBETAMaterial" } {
		DWLocalSetValue $GDN $STRUCT IDEALISATION PLANE_STRESS
		WarnWinText "The Material template CCSBETAMaterial is only 2D Plane_Stress. The idealisation was modified.  It can be assigned only for Surfaces/2D elements!"
		 # set text "The Material template CCSBETAMaterial is only 2D Plane_Stress. The idealisation was modified. In this case you can regular assign it only for Surfaces/2D elements!"
		 #	  tk_messageBox -icon info -title [_ "Info:"] -type ok \
		 #			 -message "$text"
	  }
	  return ""
	 }
	 CLOSE {
	  # do nothing here
	  return ""
     }
 }
 return ""
}
