
# $Id: Atila.tcl,v 1.23 2004/08/04 18:18:41 dwb Exp $
#
#
#

proc Splash { dir PTVersion} {
  global GIDDEFAULT

  if { [.central.s disable windows] } { return }

  # images are stored in "images" sud-directory
  set imdir [file join [.central.s info problemtypepath] "images"]
  set imname "Logo_ATILA_V"
  append imname $PTVersion ".gif"
  
  if { [ winfo exist .splash] } {
    destroy .splash
    update
  }

  if {![file exist [file join $imdir $imname]]} { return }
  
  toplevel .splash
        
  set im [image create photo -file [ file join $imdir $imname]]
  set x [expr [winfo screenwidth .splash]/2-[image width $im]/2]
  set y [expr [winfo screenheight .splash]/2-[image height $im]/2]

  pack [label .splash.l -image $im -relief ridge -bd 2]

  wm geom .splash +$x+$y
  wm transient .splash .gid
  wm overrideredirect .splash 1

  after 2000 "if { [ winfo exist .splash] } { 
    destroy .splash
  }"
}

#
###
#

proc SplashWarning {dir Message} {
  global GIDDEFAULT

  if { [.central.s disable windows] } { return }

  # images are stored in "images" sud-directory
  set imdir [file join [.central.s info problemtypepath] "images"]

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

#  toplevel .splash


#  message .m -justify center -text "this is a test" -background black
#  pack .m -expand true -fill both -ipadx 100 -ipady 40

#message .msg -width 2i -justify left \
#    -text "Document now being printed.  \
#           It is too late to change it!"
#pack .msg

          
#  set im [image create photo -file [ file join $imdir Frame2.gif]]
#  set x [expr [winfo screenwidth .splash] / 2 - [image width $im] / 2]
#  set y [expr [winfo screenheight .splash] / 2 - [image height $im] / 2]

#  pack [label .splash.l -image $im]
#  label .splash.lv -text $Message -font "times 15"
#  place .splash.lv -x [expr $x - 230] -y [expr $y - 100]
#  wm geom .splash +$x+$y
#  wm transient .splash .gid
#  wm overrideredirect .splash 1

#  after 1500 "if { [ winfo exist .msg] } { 
#    destroy .msg
#  }"
}

#
###
#

proc MyOpenIntervals {} {

  if {[lindex [.gid.central.s info gendata] 10] != "HARMONIC"} {
    WarnWin "Interval data will only apply to Harmonic analyses."
  }
  GidOpenIntervals
}

#
###
#

proc MyPreBitmaps { dir { type "DEFAULT INSIDELEFT"} } {
  global MyPreBitmapsNames MyPreBitmapsCommands MyPreBitmapsHelp ATILA

  # images are stored in "images" subdirectory
  set dir [.central.s info problemtypepath]
  set imdir [file join $dir "images"]

  set MyPreBitmapsNames(0) "conditions.gif \
                            mat_elastic.gif \
                            mat_piezoelectric.gif \
                            mat_magnetostrictive.gif \
                            mat_magnetic.gif \
                            mat_fluid.gif \
                            intervals.gif \
                            pbdata.gif"
  set MyPreBitmapsCommands(0) [list [list -np- GidOpenConditions] \
                                    [list -np- GidOpenMaterials "Elastic"] \
                                    [list -np- GidOpenMaterials "Piezoelectric"] \
                                    [list -np- GidOpenMaterials "Magnetostrictive"] \
                                    [list -np- GidOpenMaterials "Magnetic"] \
                                    [list -np- GidOpenMaterials "Fluid"] \
                                    [list -np- MyOpenIntervals] \
                                    [list -np- GidOpenProblemData] ]
  set MyPreBitmapsHelp(0) { "Assign conditions" "Assign elastic materials" \
    "Assign piezoelectric materials" "Assign magnetostrictive materials" \
    "Assign magnetic materials" "Assign fluid materials" "Define frequency intervals" \
    "Problem data"}
    
  # prefix values:
  #          Pre        Only active in the preprocessor
  #          Post       Only active in the postprocessor
  #          PrePost    Active Always

  set prefix Pre

  set ATILA(pretoolbarwin) [CreateOtherBitmaps MyPreBar "ATILA Pre Toolbar" \
    MyPreBitmapsNames MyPreBitmapsCommands \
    MyPreBitmapsHelp $imdir "MyPreBitmaps [list $dir]" $type $prefix]
    AddNewToolbar "ATILA pre bar" ${prefix}MyBarWindowGeom \
    "MyPreBitmaps [list $dir]"
}

#
###
#

proc MyPostBitmaps { dir { type "DEFAULT INSIDELEFT"} } {
  global MyPostBitmapsNames MyPostBitmapsCommands MyPostBitmapsHelp ATILA

  # images are stored in "images" subdirectory
  set dir [.central.s info problemtypepath]
  set imdir [file join $dir "images"]

  set MyPostBitmapsNames(0)  "Freq.gif \
                              animation.gif 
                              Y.gif \
                              TVR.gif \
                              pattern.gif\
                              ClearGraphs.gif"
  set MyPostBitmapsCommands(0) [list  [list -np- ShowFreq] \
                                      [list -np- MyAnimate] \
                                      [list -np- ShowAdmittance] \
                                      [list -np- ShowTVR] \
                                      [list -np- ShowPatterns] \
                                      [list -np- MyClearGraphs]]
  set MyPostBitmapsHelp(0) {  "List of frequencies" \
                              "Animation of a frequency case" \
                              "Magnitude and phase of the admittance" \
                              "TVR plot" \
                              "Beam patterns" \
                              "Clear graphs"}
    
  # prefix values:
  #          Pre        Only active in the preprocessor
  #          Post       Only active in the postprocessor
  #          PrePost    Active Always

  set prefix Post

  set ATILA(posttoolbarwin) [CreateOtherBitmaps MyPostBar "ATILA Post Toolbar" \
    MyPostBitmapsNames MyPostBitmapsCommands \
    MyPostBitmapsHelp $imdir "MyPostBitmaps [list $dir]" $type $prefix]
  AddNewToolbar "ATILA Post Toolbar" ${prefix}MyBarWindowGeom \
    "MyPostBitmaps [list $dir]"
}

#
###
#

proc InitAnimAndGraphs {} {
  global MyAnimFlag MyGraphFlag
  
  # At beginning of post process make sure flags are properly initialized

  # Set Switch for post animation
  #   0 -> animation not loaded
  #   1 -> animation loaded

  set MyAnimFlag 0

  # Set Switch for graph
  #   0  -> graph not loaded
  #   >0 -> graph loaded
  #      1 -> Magnitude, G, B, R, X
  #      2 -> Phase
  #      3 -> TVR
  #      4 -> Beam pattern

  set MyGraphFlag 0
}

#
###
#

proc MyFakeAnimateLoad {} {
global GidPriv 
set fileId [open temp w 0600]
foreach item [array names GidPriv] {puts $fileId "$item = $GidPriv($item)"}
close $fileId
}

proc MyAnimateLoad {} {
  global MenuEntriesP MenuCommandsP
  global MyAnimFlag AniFrame
#  global AtiFileName ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  append ProjectNameTemp $ProjectName "_temp"
  append ProjectNameLog $ProjectName ".log"
  append ProjectResName $ProjectName ".flavia.res"
  append ProjectMshName $ProjectName ".flavia.msh"
  append TempResName $ProjectName "_temp.flavia.res"
  append TempMshName $ProjectName "_temp.flavia.msh"
  
  set Step [lsearch [.central.s info postprocess get all_steps [.central.s info postprocess get cur_analisis]] [.central.s info postprocess get cur_step] ]
  set StepValue [.central.s info postprocess get cur_step]
  set MessageStep1 "Loading frequency: $StepValue Hz\n"
  set MessageStep2 ""
  set FlagProceed 1

  switch -exact -- [.central.s info postprocess get cur_analisis] {

    "Resonance_Modes" {
      set Step [expr $Step * 2]
      set MessageStep2 "Resonance Mode"
    }
  
    "Antiresonance_Modes" {
      set Step [expr $Step * 2 + 1]
      set MessageStep2 "Antiresonance Mode"
    }

    "Normal_Modes" {
      set MessageStep2 "Modal Analysis (single frequency)"
    }

    "Harmonic" {
      set MessageStep2 "Harmonic Analysis (single frequency)"
    } 
    
    "Harmonic-Magnitude" {
      set Step [expr $Step * 2]
      set MessageStep2 "Harmonic Case (Magnitude & Phase)"
    }
  
    "Harmonic-Phase" {
      set Step [expr $Step * 2]
      set MessageStep2 "Harmonic Case (Magnitude & Phase)"
    }

    "Harmonic-Real_Part" {
      set Step [expr $Step * 2]
      set MessageStep2 "Harmonic Case (Magnitude & Phase)"
    }

    "Harmonic-Imaginary_Part" {
      set Step [expr $Step * 2]
      set MessageStep2 "Harmonic Case (Magnitude & Phase)"
    }
    
    default {
      set FlagProceed 0
    }
  }
  
  # Show message

  if {$FlagProceed == 0} {
    WarnWin "Unrecognized analysis type: [.central.s info postprocess get cur_analisis]\nCannot Proceed."
    return
  } else {
    append MessageStep $MessageStep1 "(Load Case = $Step)\n" $MessageStep2 "\n\nClick OK to proceed"

    set answer [tk_messageBox -title "ATILA Animation" -message $MessageStep -type okcancel -icon info]
    case $answer {
      cancel return
      ok {}
    }
  }

  # Delete existing files

  if [file exists [file join $ProjectPath $TempMshName]] {
    file delete -force [file join $ProjectPath $TempMshName]
  }

  if [file exists [file join $ProjectPath $TempResName]] {
    file delete -force [file join $ProjectPath $TempResName]
  }

  # run pst with all the parameters...

  if {$Step >= 0} {
     catch {exec [file join [GetDirectoryProblemType] "pst.exe"] -p $ProjectPath -i $AtiFileName -o $ProjectNameTemp -c $Step -f $AniFrame}
  } else {
    WarnWin "Invalid step - Cannot proceed."
    return
  }

  if [file exists [file join $ProjectPath $ProjectMshName]] {
    file copy -force [file join $ProjectPath $ProjectMshName] [file join $ProjectPath $TempMshName]
  } else {
    if ![file exists [file join $ProjectPath $ProjectResName]] {
      WarnWin "Major problem!\nCannot find the results file for the current project!"
    }
    WarnWin "Cannot find the mesh file for the current project!\nBut results file seems to be present..."
    return
  }
  
  # Save configuration of windows

#  set GidResu $GidPriv(PostAnimateResultView)
#  WarnWin $GidResu
##  set GidResuNames [list PostResultsAnal PostResultsStep PostResultsView PostResultsVfact PostResultsRes PostResultsComp]
#  set GidResuNames [list PostResultsView PostResultsVfact PostResultsRes PostResultsComp]

#  set GidDefo $GidPriv(PostAnimateDeform)
#  WarnWin $GidDefo
##  set GidDefoNames [list PostGeomMainAnal PostGeomMainStep PostGeomShowStep PostGeomMainHow PostGeomMainFact PostGeomMainDefor PostGeomShowHow PostGeomShowAnal PostGeomShowFact PostGeomShowDefor]
#  set GidDefoNames [list PostGeomShowStep PostGeomMainHow PostGeomMainFact PostGeomMainDefor PostGeomShowHow PostGeomShowAnal PostGeomShowFact PostGeomShowDefor]

  # Save the settings for the View Results Window
#  if {$GidResu != ""} {
#    foreach item $GidResuNames {lappend GidResuSettings [array get GidPriv $item]}
#  }
  
  # Save the settings for the Mesh Deformation window
#  if {$GidDefo} {
#    foreach item $GidDefoNames {lappend GidDefoSettings [array get GidPriv $item]}
#    WarnWin $GidDefoSettings
#  }

  set MyReadFile [file join $ProjectPath $TempResName]
  regsub -all {\s} $MyReadFile "\\ " MyReadFile
  .central.s process escape escape escape escape Files Read $MyReadFile

  # First - Restore the settings for the Mesh Deformation window
#  if {$GidDefo} {
#    foreach item $GidDefoSettings {set GidPriv([lindex $item 0]) [lindex $item 1]}
#    PGAccept
#  }

  # Second - Restore the settings for the View Results Window
#  if {$GidResu != ""} {
#    foreach item $GidResuSettings {set GidPriv([lindex $item 0]) [lindex $item 1]}
#    PRAccept
#  }

  set MenuEntriesP(6)   {"View style" "View results" "Deform mesh" "Animate ATILA Frequency" "Border graph" "Several Results"}
  set MenuCommandsP(6)  {{ -np- PostDisplay} { -np- PostResults} { -np- PostGeom::Create} { -np- ATILA::PostAnimateM} { -np- PostGraphResultsWindow} { -np- PostVariosResultados}}
  UpdateMenus

  set MyAnimFlag 1
  ATILA::PostAnimateM
}

#
###
#

proc MyAnimateUnload {} {
  global MyAnimFlag MenuEntriesP MenuCommandsP
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  append ProjectResName $ProjectName ".flavia.res"
  append ProjectMshName $ProjectName ".flavia.msh"
  
  if [file exists [file join $ProjectPath $ProjectResName]] {
    if [file exists [file join $ProjectPath $ProjectMshName]] {
      set MyReadFile [file join $ProjectPath $ProjectResName]
      regsub -all {\s} $MyReadFile "\\ " MyReadFile
      .central.s process escape escape escape escape Files Read $MyReadFile
    } else {
      WarnWin "Cannot find the mesh of the original project!"
      return
    }
  } else {
    WarnWin "Cannot find the result file of the original project!"
    return
  }

  append TempResName $ProjectName "_temp.flavia.res"
  append TempMshName $ProjectName "_temp.flavia.msh"
    
  if [file exists [file join $ProjectPath $TempResName]] {
    file delete [file join $ProjectPath $TempResName]]
    if [file exists [file join $ProjectPath $TempMshName]] {
      file delete [file join $ProjectPath $TempMshName]]
    } else {
      WarnWin "Cannot find the mesh of the current project!"
    }
  } else {
    WarnWin "Cannot find the result file of the current project!"
  }

  ATILA::PostAnimateFin .wPostAnimate
  
  set MenuEntriesP(6)   {"View style" "View results" "Deform mesh" "Animate" "Border graph" "Several Results"}
  set MenuCommandsP(6)  {{ -np- PostDisplay} { -np- PostResults} { -np- PostGeom::Create} { -np- ATILAPostAnimate} { -np- PostGraphResultsWindow} { -np- PostVariosResultados}}
  UpdateMenus

  set MyAnimFlag 0
}

#
###
#

proc ATILAPostAnimate {} {
  if {[lindex [.gid.central.s info gendata] 10] == "MODAL" ||
      [lindex [.gid.central.s info gendata] 10] == "MODAL_RESANTIRES" ||
      [lindex [.gid.central.s info gendata] 10] == "HARMONIC"} {
    set Message "For Modal and Harmonic cases, you typically want to use the Animate option on the ATILA menu.\n"
    append Message "Are you sure you want to use the GiD Animation?\nClick YES to continue with GiD Animation.\nClick NO to use the ATILA Animation."
    set answer [tk_messageBox -title "Which Animation?" -message $Message -type yesno -icon question]
    case $answer {
      no {
        MyAnimate
        return
      }
      yes {}
    }
  }
  ::PostAnimateM
}

#
###
#

proc MyAnimate {} {
  global MyAnimFlag MyGraphFlag

  if {[.central.s info postprocess get cur_analisis] == "Static"} {
    PostAnimateM
    return
  }

  if {[.central.s info postprocess get cur_analisis] == "Transient"} {
    PostAnimateM
    return
  }

  if {[lindex [.gid.central.s info gendata] 10] != "MODAL" &&
      [lindex [.gid.central.s info gendata] 10] != "MODAL_RESANTIRES" &&
      [lindex [.gid.central.s info gendata] 10] != "HARMONIC"} {
    ATILA::PostAnimateM
    return
  }

  # MyGraphFlag = 0 => graph not loaded
  # MyGraphFlag > 0 => graph is loaded

  if {$MyGraphFlag > 0} {
    MyGraphOff
    return
  }

  # MyAnimFlag = 0 => frame animation not loaded
  # MyAnimFlag = 1 => frame animation is loaded

  if $MyAnimFlag {
    MyAnimateUnload
  } else {
    MyAnimateLoad
  }
}  

#
###
#

proc MyZMagGraphOn {} {
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  set ReturnValue 0

  append GraphName $ProjectName "_adm_mag.grf"
  set GraphFullName [file join $ProjectPath $GraphName]
  regsub -all {\s} $GraphFullName "\\ " GraphFullNameBk

  if [file exists $GraphFullName] {
    .central.s process escape escape escape escape Results Graphs ReadGraph $GraphFullNameBk
  } else {
    WarnWin "Cannot find the Admittance Magnitude graph!"
    set ReturnValue 1
  }
  
  return $ReturnValue
}

#
###
#

proc MyZPhaGraphOn {} {
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  set ReturnValue 0

  append GraphName $ProjectName "_adm_phase.grf"
  set GraphFullName [file join $ProjectPath $GraphName]
  regsub -all {\s} $GraphFullName "\\ " GraphFullNameBk

  if [file exists $GraphFullName] {
    .central.s process escape escape escape escape Results Graphs ReadGraph $GraphFullNameBk
  } else {
    WarnWin "Cannot find the Admittance Phase graph!"
    set ReturnValue 1
  }
  
  return $ReturnValue
}

#
###
#

proc MyGraphOff {} {
  global MyGraphFlag
  
  .central.s process escape escape escape escape Results Graphs OptionsGraph ClearGraphs

  set MyGraphFlag 0
}

#
###
#

proc MyZMagGraph {} {
  global MyGraphFlag

  # MyGraphFlag = 0 => no graph is loaded
  # MyGraphFlag = 1 => A graph is loaded: Z mag
  # MyGraphFlag = 2 => A graph is loaded: Z phase

  if {$MyGraphFlag == 1} {
    MyGraphOff
  } else {
    if {$MyGraphFlag != 0} {MyGraphOff}
    catch {MyZMagGraphOn} result
    if {$result == 0} {
      set MyGraphFlag 1
    }
  }
}

#
###
#

proc MyZPhaGraph {} {
  global MyGraphFlag

  # MyGraphFlag = 0 => no graph is loaded
  # MyGraphFlag = 1 => A graph is loaded: Z mag
  # MyGraphFlag = 2 => A graph is loaded: Z phase

  if {$MyGraphFlag == 2} {
    MyGraphOff
  } else {
    if {$MyGraphFlag != 0} {MyGraphOff}
    catch {MyZPhaGraphOn} result
    if {$result == 0} {
      set MyGraphFlag 2
    }
  }
}

#
###
#

proc EndMyBitmaps {} {
  global ATILA
    
  ReleaseToolbar "ATILA pre bar"
  ReleaseToolbar "ATILA post bar"
  rename MyPreBitmaps ""
  rename MyPostBitmaps ""
    
  catch { destroy $ATILA(pretoolbarwin) }
  catch { destroy $ATILA(posttoolbarwin) }
}

#
###
#

proc About {} {
  global PTVersion
  
  set w .wPBX_About

  InitWindow $w "About..." PrePostAGAbout

  frame $w.f1
  label $w.f1.lbl1 -text "ATILA-GiD Interface"
  label $w.f1.lbl2 -text "Version $PTVersion"
  
  frame $w.f2
  label $w.f2.lbl1 -text "Developed by:"
  label $w.f2.lbl2 -text "Magsoft Corporation"
  label $w.f2.lbl3 -text "ISEN"
  label $w.f2.lbl4 -text "Genfo, Inc."
  
  frame $w.f3
  label $w.f3.lbl1 -text "Visit the ATILA Web Pages:"
  label $w.f3.lbl2 -text "http://www.atilafem.com/"
  label $w.f3.lbl3 -text "Join the ATILA Mailing List:"
  label $w.f3.lbl4 -text "http://lists.adaptronics.com/mailman/listinfo/atila"

  frame $w.btn
  button $w.btn.ok -text "OK" -command "destroy .wPBX_About"

  pack $w.f1 $w.f1.lbl1 $w.f1.lbl2 -side top -padx 5 -pady 2
  pack $w.f2 $w.f2.lbl1 $w.f2.lbl2 $w.f2.lbl3 $w.f2.lbl4 -side top -padx 5 -pady 0
  pack $w.f3 $w.f3.lbl1 $w.f3.lbl2 $w.f3.lbl3 $w.f3.lbl4 -side top -padx 5 -pady 0

  pack $w.btn $w.btn.ok -side bottom -padx 5 -pady 2
  pack $w.f1 $w.f2 $w.f3 $w.btn -side top
}

#
###
#

proc Preferences {} {
  global IniHasChanged AniFrame

  # Load Settings
  if [file exists [file join [GetDirectoryProblemType] "ATILA-GiD.ini"]] {
    if [catch {open [file join [GetDirectoryProblemType] "ATILA-GiD.ini"] r} fileId] {
      WarnWin "Could not read default settings."
    } else {
      if {![catch {gets $fileId IniLine}]} {
        # Check that first line has not been modified
        if [string equal $IniLine "# Settings for the ATILA-GiD interface - Please do not edit"] {
          if {![catch {gets $fileId IniLine}]} {
            set Value [ReadIniValue $IniLine "PTVersion"]
            if {![string equal $Value "-"]} {set PTVersion $Value}
          }
          if {![catch {gets $fileId IniLine}]} {
            set Value [ReadIniValue $IniLine "IdealGiDVersion"]
            if {![string equal $Value "-"]} {set IdealGiDVersion $Value}
          }
          if {![catch {gets $fileId IniLine}]} {
            set Value [ReadIniValue $IniLine "ReadAtiPostPath"]
            if {![string equal $Value "-"]} {set ReadAtiPostPath $Value}
          }
          close $fileId
          
          set w .wPBX_Preferences
        
          InitWindow $w "Preferences" PrePostAGPreferences
        
          frame $w.f1
          label $w.f1.lbl1a -text "ATILA-GiD Interface Version: "
          label $w.f1.lbl1b -text $PTVersion
          label $w.f1.lbl2a -text "Ideal GiD Version: "
          label $w.f1.lbl2b -text $IdealGiDVersion
          label $w.f1.lbl3a -text "Read ATI Post Path: "
          label $w.f1.lbl3b -text $ReadAtiPostPath
          
          grid $w.f1.lbl1a -row 0 -column 0 -sticky w
          grid $w.f1.lbl1b -row 0 -column 1 -sticky w
          grid $w.f1.lbl2a -row 1 -column 0 -sticky w
          grid $w.f1.lbl2b -row 1 -column 1 -sticky w
          grid $w.f1.lbl3a -row 2 -column 0 -sticky w
          grid $w.f1.lbl3b -row 2 -column 1 -sticky w
          
          
          frame $w.e1
          label $w.e1.lbl1 -text "Number of animation frames: "
          entry $w.e1.ent1 -textvariable AniFrame -relief sunken
          grid $w.e1.lbl1 -row 3 -column 0 -sticky w
          grid $w.e1.ent1 -row 3 -column 1 -sticky w
          bind $w.e1.ent1 $AniFrame

          frame $w.btn
          button $w.btn.cl -text "Close" -command "destroy .wPBX_Preferences"
          button $w.btn.sa -text "Save" -command {
            set IniHasChanged 0
            SaveSettings
          }
          grid $w.btn.cl -row 3 -column 0
          grid $w.btn.sa -row 3 -column 1

          pack $w.f1 -anchor nw
          pack $w.e1 -anchor w
          pack $w.btn -anchor s -expand y
                                      
        } else {
          WarnWin "Settings have been edited.\nLast settings not restored."
        }
      }
    }
  } else {
      WarnWin "Could not find ATILA-GiD.ini file"
  }
}

#
###
#

proc HelpOnAbout {} {
  global GIDDEFAULT GidPriv

  set HelpPath [file join [.central.s info problemtypepath] "html"]
  set HelpFile [file join $HelpPath "About" "index.html"]
  
  if [file exists $HelpFile] {
    HelpWindow "TUTORIAL" $HelpFile
  } else {
    WarnWin "Could not find help files."
  }

}

#
###
#

proc HelpOnATILAReference {} {
  global GIDDEFAULT GidPriv

  set HelpPath [file join [.central.s info problemtypepath] "html"]
  set HelpFile [file join $HelpPath "doc" "index.html"]
  
  if [file exists $HelpFile] {
    HelpWindow "TUTORIAL" $HelpFile 
  } else {
    WarnWin "Could not find help files."
  }

}

#
###
#

proc HelpOnATILATutorial1 { } {
  global GIDDEFAULT GidPriv

  set HelpPath [file join [.central.s info problemtypepath] "html"]
  set HelpFile [file join "problemtypes" $HelpPath Tutorial1 "1.html"]

  if [file exists $HelpFile] {
    HelpWindow "TUTORIAL" $HelpFile
  } else {
    WarnWin "Could not find help files."
  }

}

#
###
#

proc HelpOnATILATutorial2 { } {
  global GIDDEFAULT GidPriv

  set HelpPath [file join [.central.s info problemtypepath] "html"]
  set HelpFile [file join "problemtypes" $HelpPath Tutorial2 "1.html"]

  if [file exists $HelpFile] {
    HelpWindow "TUTORIAL" $HelpFile
  } else {
    WarnWin "Could not find help files."
  }

}

#
###
#

proc HelpOnATILA { } {
  global GIDDEFAULT GidPriv

  set dir [.central.s info problemtypepath]
  set base .gid.tutorials

  InitWindow $base "ATILA Help" GiDTutorialswin "" "" 1
  $base configure -background #000000

   set image_About     [image create photo -file [file join $dir images About_Bk.gif]]
   set image_Reference [image create photo -file [file join $dir images Logo_ATILA_Small_Bk.gif]]
   set image_tutorial1 [image create photo -file [file join $dir images Tutorial1_Bk.gif]]
   set image_tutorial2 [image create photo -file [file join $dir images Tutorial2_Bk.gif]]

   set image_About_over     [image create photo -file [file join $dir images About_Tp.gif]]
   set image_Reference_over [image create photo -file [file join $dir images Logo_ATILA_Small_Tp.gif]]
   set image_tutorial1_over [image create photo -file [file join $dir images Tutorial1_Tp.gif]]
   set image_tutorial2_over [image create photo -file [file join $dir images Tutorial2_Tp.gif]]

  button $base.button#1 \
    -relief flat \
    -image $image_About -background #000000 \
    -command {
      HelpOnAbout
      destroy .gid.tutorials
      }

  button $base.button#2 \
    -relief flat \
    -image $image_Reference -background #000000 \
    -command {
      HelpOnATILAReference
      destroy .gid.tutorials
      }
    
  button $base.button#3 \
    -relief flat \
    -image $image_tutorial1 -background #000000 \
    -command {
      HelpOnATILATutorial1
      destroy .gid.tutorials
      }

  button $base.button#4 \
    -relief flat \
    -image $image_tutorial2 -background #000000 \
    -command {
      HelpOnATILATutorial2
      destroy .gid.tutorials
      }

  bind $base.button#1 <Enter> ".gid.tutorials.button#1 configure -image $image_About_over"
        bind $base.button#1 <Leave> ".gid.tutorials.button#1 configure -image $image_About"

  bind $base.button#2 <Enter> ".gid.tutorials.button#2 configure -image $image_Reference_over"
        bind $base.button#2 <Leave> ".gid.tutorials.button#2 configure -image $image_Reference"

  bind $base.button#3 <Enter> ".gid.tutorials.button#3 configure -image $image_tutorial1_over"
        bind $base.button#3 <Leave> ".gid.tutorials.button#3 configure -image $image_tutorial1"
  
  bind $base.button#4 <Enter> ".gid.tutorials.button#4 configure -image $image_tutorial2_over"
        bind $base.button#4 <Leave> ".gid.tutorials.button#4 configure -image $image_tutorial2"

  # Geometry management

  grid $base.button#1 -in $base  -row 0 -column 0 
  grid $base.button#2 -in $base  -row 0 -column 1
  grid $base.button#3 -in $base  -row 1 -column 0 
  grid $base.button#4 -in $base  -row 1 -column 1 

  # Resize behavior management

  grid rowconfigure $base 1 -weight 1 -minsize 30

  tkwait visibility $base
  grab  $base 

}

#
###
#

proc OpenAtiDialog {} {
  global IniHasChanged ReadAtiPostPath

  set CompleteFilename [tk_getOpenFile \
                        -title "Import ATILA File" \
                        -initialdir $ReadAtiPostPath \
                        -parent . \
                        -filetypes {{{ATILA Files} {.ati}}}]

  if {[string equal $CompleteFilename ""]} {
    return ""
  }
  
  if {![file exists $CompleteFilename]} {
    return ""
  }

  set the_path [file dirname $CompleteFilename]

  # We must save the new setting here because endgidproject won't run on gid quit
  if {![string equal $ReadAtiPostPath $the_path]} {
    set ReadAtiPostPath $the_path
    set IniHasChanged 0
    SaveSettings
  }
  
  return $CompleteFilename
}

#
###
#

proc CreateAtiMsh {} {
#  global AtiFileName ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  if {![file exists [file join [GetDirectoryProblemType] "ati2msh.exe"]]} {
    WarnWin "The ATILA Problem Type is incorrectly installed.\nFile ati2msh.exe is missing.\nCannot proceed."
    return
  }

  #Generate Mesh
  catch {exec [file join [GetDirectoryProblemType] "ati2msh.exe"] -i $AtiFileName -o $ProjectName -p $ProjectPath}

  set msh_file [file join $ProjectPath $ProjectName]
  append msh_file ".flavia.msh"
  
  if {![file exists $msh_file]} {
    return ""
  }

  return $msh_file
}

#
###
#

proc CreateAtiRes {} {
#  global AtiFileName ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  if {![file exists [file join [GetDirectoryProblemType] "pst.exe"]]} {
    WarnWin "The ATILA Problem Type is incorrectly installed.\nFile pst.exe is missing.\nCannot proceed."
    return
  }

  append FileSY4 [file join $ProjectPath $AtiFileName $AtiFileName] ".sy4"
  append FilePST [file join $ProjectPath $AtiFileName $AtiFileName] ".pst"

  if [file exists $FileSY4] {
    if [file exists $FilePST] {
      #Generate Results
      catch {exec [file join [GetDirectoryProblemType] "pst.exe"] -p $ProjectPath -i $AtiFileName -o $ProjectName}
    } else {
      WarnWin "Cannot find PST file:\n $FilePST"
      return ""
    }
  } else {
    WarnWin "Cannot find SY4 File:\n $FileSY4"
    return ""
  }

  append ResFile [file join $ProjectPath $ProjectName] ".flavia.res"

  if {![file exists $ResFile]} {
    WarnWin "The Results file ($ResFile) was not successfully generated."
    return ""
  }

  return $ResFile
}

#
###
#

proc ConditionalCopy {src_name dest_name} {
  if {[file exists $src_name]} {
    if {![catch {open $src_name r} in]} {
      if {![catch {open $dest_name w} out]} {
        fconfigure $in -translation binary -buffersize 262144
        fconfigure $out -translation binary -buffersize 262144
        fcopy $in $out
        close $out
      }
      close $in
    }
  }
}

proc ReadAtiPre {} {
  global IniHasChanged ReadAtiPostPath
#  global ProjectPath ProjectName AtiFileName

  GetProjectNames AtiFileName ProjectPath ProjectName

# Do we have a project name?
  if {[string equal $ProjectName "UNNAMED"]} {
    WarnWin "To import an ATI file, you must save your project first."
    .gid.central.s process escape escape escape escape escape escape Files SaveAs
    return
  }

# Do we already have a mesh?
  append ati_file [file join $ProjectPath $AtiFileName] ".ati"
  if {([.central.s info Mesh MaxNumNodes] > 0) || ([file exists $ati_file])} {
    set answer [tk_messageBox -title "Are you sure?" -message "ATI import will overwrite your existing mesh.  Do you want to continue?" -type yesno -icon question]
    case $answer {
      no return
      yes {}
    }
  }

# Get the file name from the user
  set CompleteFilename [OpenAtiDialog]

  if {[string equal $CompleteFilename ""]} {
    return
  }

# Set our global variables for CreateAtiMsh()
# NO LONGER USED -- See GetProjectNames() function
#  set ProjectPath [lindex [.central.s info Project] 1]
#  append ProjectPath ".gid"
#  set ProjectName [file tail [lindex [.central.s info Project] 1]]
  set ati_file [file join $ProjectPath $AtiFileName]
  append ati_file ".ati"

# copy the user's ATI file to our $AtiFileName
  ConditionalCopy $CompleteFilename $ati_file

  set msh_file [CreateAtiMsh]
  
  if {![file exists $msh_file]} {
    WarnWin "Import unsuccessful:  Mesh file ($msh_file) not found."
    return
  }

  regsub -all {\s} $msh_file "\\ " msh_file  

  if {[.central.s info Mesh MaxNumNodes] > 0} {
    #if mesh exists
    .gid.central.s process escape escape escape escape Files MeshRead "E" $msh_file
  } else {
    .gid.central.s process escape escape escape escape Files MeshRead $msh_file
  }

# See if results already exist for the ati file

  # source files
  set ati_path [file root $CompleteFilename]
  set ati_name [file root [file tail $CompleteFilename]]
  set ati_dir [file join $ati_path $ati_name]
  append sy4_filename $ati_dir ".sy4"
  append pst_filename $ati_dir ".pst"
  append pat_filename $ati_dir ".pat"

  # do any of the source files exist?
  if {[file exists $sy4_filename] ||
      [file exists $pat_filename] ||
      [file exists $pst_filename]} {

    # yes, so try to create the directory in the GiD project folder
    set ati_path [file join $ProjectPath $AtiFileName]
    if {![catch {file mkdir $ati_path}]} {

      # destination files
      set ati_dir [file join $ati_path $AtiFileName]
      append to_sy4 $ati_dir ".sy4"
      append to_pst $ati_dir ".pst"
      append to_pat $ati_dir ".pat"

      # copy each file
      ConditionalCopy $sy4_filename $to_sy4
      ConditionalCopy $pst_filename $to_pst
      ConditionalCopy $pat_filename $to_pat

      # if the PST file exists, ask if the user wants to recreate the GiD results
      if {[file exists $to_pst]} {
        RunPST
      }
    }
  }
}

#
###
#

proc ReadAtiPost {} {
  global IniHasChanged ReadAtiPostPath
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  set CompleteFilename [OpenAtiDialog]

  if {[string equal $CompleteFilename ""]} {
    return
  }

  set MshFile [CreateAtiMsh $CompleteFilename]
# Second argument to CreateAtiRes indicates whether or not to use the default name "project" for the ATILA file.
  set ResFile [CreateAtiRes]
    
  set ReadWhat "Nothing"
  
  if {![file exists $MshFile]} {
    WarnWin "Cannot find mesh file.\nLeaving"
    return
  } else {
    set ReadWhat "Msh"
  }

  if {![file exists $ResFile]} {
    WarnWin "Cannot find results file.\nReading mesh only."
  } else {
    set ReadWhat "Res"
  }
  
  if {$ReadWhat != "Nothing"} {
    if {$ReadWhat == "Msh"} {
      regsub -all {\s} $MshFile "\\ " MshFile  
      .gid.central.s process escape escape escape escape Files Read $MshFile
    }
    if {$ReadWhat == "Res"} {
      regsub -all {\s} $ResFile "\\ " ResFile  
      .gid.central.s process escape escape escape escape Files Read $ResFile
    }

    InitAnimAndGraphs
  }
}

#
###
#

proc RunDataReading {} {
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  # If there is no project, then quit
  if {[string equal $ProjectName "UNNAMED"]} {
    WarnWin "The project name is not defined.\nSave your project first, then try again.\nATI file was not created!"
    return
  }

  if {![file exists [file join [GetDirectoryProblemType] "data_reading.exe"]]} {
    WarnWin "The ATILA Problem Type is incorrectly installed.\nFile data_reading.exe is missing.\nATI file was not created!"
    return
  }

  set Message "This step will convert the GiD project to an ATILA file for job $ProjectName without running the ATILA solver.\nClick OK to proceed."
  set answer [tk_messageBox -title "Convert to ATI" -message $Message -type okcancel -icon info]
  case $answer {
    cancel return
    ok {}
  }
  
  append MySaveFile "\"" [file join $ProjectPath $ProjectName] ".dat\""
  .central.s process escape escape escape escape Files WriteCalcFile $MySaveFile

  set MySaveFile [file join $ProjectPath $ProjectName]
  append MySaveFile ".dat"
  if {![file exists $MySaveFile]} {
    WarnWin "Could not create calculation file.  Correct errors and try again."
    return
  }

  append execline "\"" [file join [GetDirectoryProblemType] "data_reading.exe"] "\" \"" [file join $ProjectPath $ProjectName] "\""

  if {[catch { set pid [eval exec $execline] } errorchar]} {
    tk_messageBox -title "Convert to ATI" -message "Error converting to ATI file. ($errorchar)" -type ok -icon info
  } else {
    tk_messageBox -title "ATI File Created" -message "ATI file has been created.  Use Run Solver menu option to start the solver." -type ok -icon info
  }
}

proc RunGA {} {
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  if {![file exists [file join [GetDirectoryProblemType] "main.exe"]]} {
    WarnWin "The ATILA Problem Type is incorrectly installed.\nFile main.exe is missing.\nCannot proceed."
    return
  }

  # If there is no project, then quit
  if {[string equal $ProjectName "UNNAMED"]} {
    WarnWin "In order to run the solver, you must save the current project.\nSave this project, then select Convert to ATI before running the solver.\nSolver did not run!"
    return
  }

  set Message "This step will run the ATILA solver for job $ProjectName.\nClick OK to proceed."
  set answer [tk_messageBox -title "Run ATILA solver" -message $Message -type okcancel -icon info]
  case $answer {
    cancel return
    ok {}
  }
  
  set my_dir [pwd]
  cd $ProjectPath
  append execline "\"" [file join [GetDirectoryProblemType] "main.exe"] "\""

  if {[catch { set pid [eval exec $execline "project"] } errorchar]} {
    tk_messageBox -title "Run ATILA solver" -message "Error running the solver. ($errorchar)" -type ok -icon info
  } else {
    tk_messageBox -title "ATILA Run Complete" -message "ATILA has completed.  Use Generate Results menu option to create postprocessing files." -type ok -icon info
  }
  cd $my_dir
}

proc RunPST {} {
  global IniHasChanged ReadAtiPostPath
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  # If there is no project, then quit
  if {[string equal $ProjectName "UNNAMED"]} {
    WarnWin "The project name is not defined.\nSave your project first, then try again.\nResults were not created!"
    return
  }

  set Message "This will re-generate the results file for job $ProjectName without running the ATILA solver.\nClick OK to proceed."
  set answer [tk_messageBox -title "Generate Results" -message $Message -type okcancel -icon info]
  case $answer {
    cancel return
    ok {}
  }

  set ResFile [CreateAtiRes]
    
  if {![file exists $ResFile]} {
    WarnWin "Cannot find results file.\nLeaving."
    return
  }

  set Message "New results files have been generated for $ProjectName.\nClick OK to postprocess."
  set answer [tk_messageBox -title "Generate Results" -message $Message -type okcancel -icon info]
  case $answer {
    cancel return
    ok {TogglePrePost}
  }
}

#
###
#

proc StartATI {} {
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  set AtiName ""
  set AtiFile ""
  set AtiVersion ""
  set AtiInstallDir ""
  set ReadReg [file join [GetDirectoryProblemType] "ReadReg.exe"]
  
  if {![file exists $ReadReg]} {
    WarnWin "The ATILA Problem Type is incorrectly installed.\nFile ReadReg.exe is missing.\nCannot proceed."
    return
  }
  
  # Where is ATILA installed?
  set AtiVersion [exec $ReadReg "HKEY_LOCAL_MACHINE" "SOFTWARE\\ISEN Recherche\\ATILA" "CurrentVersion"]
    
  if [string equal $AtiVersion ""] {
    WarnWin "ATILA does not seem to be installed on this machine.\nNot found."
    return
  }
 
  if {[string length $AtiVersion] > 4} {
    if [string equal [string range $AtiVersion 0 4] "Error"] {
      WarnWin "ATILA does not seem to be installed on this machine.\nError."
      return
    }
  }

  append RKPath "SOFTWARE\\ISEN Recherche\\ATILA" "\\" $AtiVersion

  set AtiInstallDir [exec $ReadReg "HKEY_LOCAL_MACHINE" $RKPath "ATILA_DIR"]
  
  if [string equal $AtiInstallDir ""] {
    WarnWin "ATILA installation seems incorrect.\nNot found."
    return
  }
  
  if {[string length $AtiInstallDir] > 4} {
    if [string equal [string range $AtiVersion 0 4] "Error"] {
      WarnWin "ATILA installation seems incorrect.\nError."
      return
    }
  }

  # does the current project have a name?
  
  set NoName -1

  # name is defined
  if {![string equal $ProjectName "UNNAMED"]} { set NoName 1 }

  if {$NoName > 0} {
# NO LONGER USED - See GetProjectNames() function
#    if {$NoName == 1} {
#      set ProjectPath [lindex [.central.s info Project] 1]
#      append ProjectPath ".gid"
#      set ProjectName [file tail [lindex [.central.s info Project] 1]]
#    }

    # is there an ati file for the current project?
    append AtiName $ProjectName ".ati"

    if [file exists [file join $ProjectPath $AtiName]] {
      set AtiFile [file join $ProjectPath $AtiName]
    } else {
      append AtiFile $ProjectPath "/"
    }
  }

  # if unnamed            => supervisor.bat                     => AtiFile = ""
  # if job but no job.ati => supervisor.bat ProjectPath/        => AtiFile = ProjectPath/
  # if job.ati is found   => supervisor.bat ProjectPath/job.ati => AtiFile = ProjectPath/AtiName

  #exec "C:/ISEN/Atila-5.2.1/bin.win32/atila.exe"
  
  # need a bogus file to redirect the output of the command on certain windows platform
  # I am assuming we have write access to the problem type directory
  
  set BogusFile [file join [GetDirectoryProblemType] "bogus.txt"]
  
  if [string equal $AtiFile ""] {
    catch { exec [file join $AtiInstallDir "bin.win32/atila.exe"] > $BogusFile & }
  } else {
    catch { exec [file join $AtiInstallDir "bin.win32/atila.exe"] $AtiFile > $BogusFile & }
  }

}

#
###
#

proc OpenShell {} {
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  # If the project is unnamed then the path must be set to default location
  if {[string equal $ProjectName "UNNAMED"]} {
    set MyPath "C:\\"
  } else {
    set MyPath $ProjectPath
  }

  # Seems that explorer cannot deal with "/"
  regsub -all {/} $MyPath "\\" MyPath
  
  catch {exec explorer $MyPath}
  return
}

#
###
#

proc SaveSettings {} {
  global IniHasChanged PTVersion IdealGiDVersion ReadAtiPostPath AniFrame

  if {$AniFrame < 4 }  { set AniFrame 4 }
  if {$AniFrame > 50}  { set AniFrame 50 }

  if {$IniHasChanged == 0} {
#    WarnWin [file join [GetDirectoryProblemType] "ATILA-GiD.ini"]
    if [catch {open [file join [GetDirectoryProblemType] "ATILA-GiD.ini"] w 0666} fileId] {
      WarnWin "Cannot save default settings."
    } else {
      puts $fileId "# Settings for the ATILA-GiD interface - Please do not edit"
      puts $fileId [concat "PTVersion =" $PTVersion]
      puts $fileId [concat "IdealGiDVersion =" $IdealGiDVersion]
      puts $fileId [concat "ReadAtiPostPath =" $ReadAtiPostPath]
      puts $fileId [concat "AniFrame =" $AniFrame]
      close $fileId
      set IniHasChanged -1
    }
  }
}

#
###
#

proc ViewSelection { type w } {
#  global ProjectPath ProjectName AtiFileName
  global MyGraphFlag
  global dwb_Orient dwb_Frequencies dwb_AdmImpGraph

  GetProjectNames AtiFileName ProjectPath ProjectName

  if {$MyGraphFlag > 0} {
    if {$type == "Graph"} {MyGraphOff}
  }

  set pat2grf [file join [GetDirectoryProblemType] "pat2grf.exe"]

  if {![file exists $pat2grf]} {
    WarnWin "The Problem type is not properly installed.\nThe file pat2grf.exe is missing."
    return
  }

  if {[string equal $w ".wDWB_ADM_IMP"]} {
    set ReadFile [file join $ProjectPath $ProjectName]
    if {$type == "Graph"} {
      if {$dwb_AdmImpGraph == "AdmMagnitude"} {
        append ReadFile "_adm_mag.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "AdmPhase"} {
        append ReadFile "_adm_phase.grf"
        set MyGraphFlag 2
      }
      if {$dwb_AdmImpGraph == "AdmReal"} {
        append ReadFile "_adm_real.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "AdmImaginary"} {
        append ReadFile "_adm_imag.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "AdmCircle"} {
        append ReadFile "_adm_circle.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "ImpMagnitude"} {
        append ReadFile "_imp_mag.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "ImpPhase"} {
        append ReadFile "_imp_phase.grf"
        set MyGraphFlag 2
      }
      if {$dwb_AdmImpGraph == "ImpReal"} {
        append ReadFile "_imp_real.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "ImpImaginary"} {
        append ReadFile "_imp_imag.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "ImpCircle"} {
        append ReadFile "_imp_circle.grf"
        set MyGraphFlag 1
      }
    } else {
      if {$dwb_AdmImpGraph == "AdmMagnitude" ||
          $dwb_AdmImpGraph == "AdmPhase" ||
          $dwb_AdmImpGraph == "AdmReal" ||
          $dwb_AdmImpGraph == "AdmImag" ||
          $dwb_AdmImpGraph == "AdmCircle"} {
        append ReadFile ".adm.csv"
      }
      if {$dwb_AdmImpGraph == "ImpMagnitude" ||
          $dwb_AdmImpGraph == "ImpPhase" ||
          $dwb_AdmImpGraph == "ImpReal" ||
          $dwb_AdmImpGraph == "ImpImag" ||
          $dwb_AdmImpGraph == "ImpCircle"} {
        append ReadFile ".imp.csv"
      }
    }
  }

  if {[string equal $w ".wDWB_CUR"]} {
    set ReadFile [file join $ProjectPath $ProjectName]
    if {$type == "Graph"} {
      if {$dwb_AdmImpGraph == "CurMagnitude"} {
        append ReadFile "_cur_mag.grf"
        set MyGraphFlag 1
      }
      if {$dwb_AdmImpGraph == "CurPhase"} {
        append ReadFile "_cur_phase.grf"
        set MyGraphFlag 2
      }
    } else {
      if {$dwb_AdmImpGraph == "CurMagnitude" ||
          $dwb_AdmImpGraph == "CurPhase"} {
        append ReadFile ".cur.csv"
      }
    }
  }

  if {[string equal $w ".wDWB_TVR"]} {
    set ExeValue [catch {exec $pat2grf -i $AtiFileName -o $ProjectName -p $ProjectPath -t $dwb_Orient}]
    if {$ExeValue == 0} {
      append TVRName $ProjectName ".tvr"
      if {$type == "Graph"} {
        append TVRName ".grf"
        set MyGraphFlag 3
      } else {
        append TVRName ".csv"
      }
      set ReadFile [file join $ProjectPath $TVRName]
    } else {
      WarnWin "This problem does not seem to contain radiation data."
      return
    }
  }
  
  if {[string equal $w ".wDWB_PAT"]} {
    set the_freq [lindex $dwb_Frequencies [$w.lbf.lbFrequencies curselection]]
    exec $pat2grf -i $AtiFileName -o $ProjectName -p $ProjectPath -f $the_freq
    append PressureName $ProjectName ".beam"
    if {$type == "Graph"} {
      append PressureName ".grf"
      set MyGraphFlag 4
    } else {
      append PressureName ".csv"
    }
    set ReadFile [file join $ProjectPath $PressureName]
  }

  if [file exists $ReadFile] {
    if {$type == "Values"} {
      ShowTextFile $ReadFile
    } else {
      regsub -all {\s} $ReadFile "\\ " ReadFile
      .central.s process escape escape escape escape Results Graphs ReadGraph $ReadFile
    }
  } else {
    if {$type == "Values"} {
      WarnWin "Cannot find the values ($ReadFile)!"
    } else {
      WarnWin "Cannot find the graph ($ReadFile)!"
      set MyGraphFlag 0
    }
  }
}

#
###
#

proc ShowTVR { } {
#  global AtiFileName ProjectPath ProjectName
  global MyGraphFlag
  global dwb_Orient

  GetProjectNames AtiFileName ProjectPath ProjectName

  if {[winfo exist .wDWB_TVR]} {
    destroy .wDWB_TVR
    update
    if {$MyGraphFlag == 3} {
      MyGraphOff
    }
    if {[winfo exist .wShowText]} {
      destroy .wShowText
      update
    }
    return
  }

  # Test if the problem contains radiation data
  set pat2grf [file join [GetDirectoryProblemType] "pat2grf.exe"]

  if {![file exists $pat2grf]} {
    WarnWin "The Problem type is not properly installed.\nThe file pat2grf.exe is missing."
    return
  }
  
  set ExeValue [catch {exec $pat2grf -i $AtiFileName -o $ProjectName -p $ProjectPath -t 0}]
  if {$ExeValue == 0} {
    set w .wDWB_TVR

    InitWindow $w "TVR Results" PostTVRWindowGeom PostTVR

    frame $w.f
    label $w.f.lblOrientation -text Orientation:
    radiobutton $w.f.rbZeroDegrees -text Ox -variable dwb_Orient -value 0
    radiobutton $w.f.rbNinetyDegrees -text Oy -variable dwb_Orient -value 90
    pack $w.f.lblOrientation $w.f.rbZeroDegrees $w.f.rbNinetyDegrees -side left

    button $w.btnView -text "View Graph" -command "ViewSelection Graph $w"
    button $w.btnValues -text "Show Values" -command "ViewSelection Values $w"

    set dwb_Orient 0

    pack $w.f $w.btnView
    pack $w.f $w.btnValues

    update idletasks
  } else {
    WarnWin "This problem does not seem to contain radiation data."
  }
}

#
###
#

proc ShowPatterns { } {
#  global AtiFileName ProjectPath ProjectName
  global MyGraphFlag
  global dwb_Frequencies

  GetProjectNames AtiFileName ProjectPath ProjectName

  if {[winfo exist .wDWB_PAT]} {
          destroy .wDWB_PAT
    update
    if {$MyGraphFlag == 4} {
      MyGraphOff
    }
    if {[winfo exist .wShowText]} {
      destroy .wShowText
      update
    }
    return
  }

  # Test if the problem contains radiation data
  set pat2grf [file join [GetDirectoryProblemType] "pat2grf.exe"]

  if {![file exists $pat2grf]} {
    WarnWin "The Problem type is not properly installed.\nThe file pat2grf.exe is missing."
    return
  }

  set ExeValue [catch {exec $pat2grf -i $AtiFileName -o $ProjectName -p $ProjectPath --list_frequencies}]

  if {$ExeValue == 0} {
    set w .wDWB_PAT

    InitWindow $w "Pattern Results" PostPatternWindowGeom PostPattern

    label $w.lblFrequencies -text Frequencies

    frame $w.lbf
    listbox $w.lbf.lbFrequencies -selectmode single -listvar dwb_Frequencies \
                                 -yscrollcommand "$w.lbf.v_scroll set"
    scrollbar $w.lbf.v_scroll -command "$w.lbf.lbFrequencies yview"
    pack $w.lbf.v_scroll -side right -fill y
    pack $w.lbf.lbFrequencies -side left -expand yes -fill both

    button $w.btnView -text "View Graph" -command "ViewSelection Graph $w"
    button $w.btnShow -text "Show Values" -command "ViewSelection Values $w"

    set dwb_Frequencies [exec $pat2grf -i $AtiFileName -o $ProjectName -p $ProjectPath --list_frequencies]

    $w.lbf.lbFrequencies activate 0
    $w.lbf.lbFrequencies selection set 0

    pack $w.lblFrequencies
    pack $w.lbf -expand yes -fill both
    pack $w.btnView $w.btnShow

    update idletasks
  } else {
    WarnWin "This problem does not seem to contain radiation data."
  }
}

#
###
#

proc ShowTextFile { filename } {
  if {![info exists .wShowText]} {
    set v .wShowText
    InitWindow $v "Results" PostTextWindowGeom PostTextWindow


    frame $v.text
    text $v.text.t -wrap none \
         -yscrollcommand "$v.text.v_scroll set" \
         -xscrollcommand "$v.text.h_scroll set"
    scrollbar $v.text.v_scroll -command "$v.text.t yview"
    scrollbar $v.text.h_scroll -command "$v.text.t xview" -orient horizontal
    pack $v.text.v_scroll -side right -fill y
    pack $v.text.h_scroll -side bottom -fill x
    pack $v.text.t -side left -fill both -expand 1
    pack $v.text -fill both -expand 1
  }
  $v.text.t delete 1.0 end
  set filesize [file size $filename]
  set fileid [open $filename r]
  set data [read $fileid $filesize]
  close $fileid
  $v.text.t insert end $data
}

#
###
#

proc Test_ShowTextFile {} {
  set file_types {
    {"Graph Files" { .grf .GRF } }
    {"Text Files" { .txt .TXT } }
    {"All Files" * }
  }
  set filename [tk_getOpenFile -filetypes $file_types -initialdir pwd]


# I tested opening a file with spaces in the file name, and I didn't need
# to do anything special.


  ShowTextFile $filename
}

#
###
#

proc ShowAdmittance { } {
#  global ProjectPath ProjectName
  global MyGraphFlag
  global dwb_AdmImpGraph

  GetProjectNames AtiFileName ProjectPath ProjectName

  set CurAnalysis [.central.s info postprocess get cur_analisis]

  if {[string equal $CurAnalysis "Static"]} {
    WarnWin "Cannot display admittance for a Static case!"
    return
  }

  if {[string equal $CurAnalysis "Resonance_Modes"]} {
    WarnWin "Cannot display admittance for a Modal case!"
    return
  }

  if {[string equal $CurAnalysis "Antiresonance_Modes"]} {
    WarnWin "Cannot display admittance for a Modal case!"
    return
  }

  if {[string equal $CurAnalysis "Normal_Modes"]} {
    WarnWin "Cannot display admittance for a Modal case!"
    return
  }

  if {[string equal $CurAnalysis "Transient"]} {

    if {[winfo exist .wDWB_CUR]} {
      destroy .wDWB_CUR
      update
      if {$MyGraphFlag == 1 || $MyGraphFlag == 2} { MyGraphOff }
      if {[winfo exist .wShowText]} {
        destroy .wShowText
        update
      }
      return
    }

    set w .wDWB_CUR

    InitWindow $w "Current Results" PostCurWindowGeom

    frame $w.fCur
    label $w.fCur.lblCurrent -text Current:
    radiobutton $w.fCur.rbCurMagnitude -text Magnitude -variable dwb_AdmImpGraph -value "CurMagnitude"
    radiobutton $w.fCur.rbCurPhase -text Phase -variable dwb_AdmImpGraph -value "CurPhase"
    pack $w.fCur.lblCurrent $w.fCur.rbCurMagnitude $w.fCur.rbCurPhase -side left

    frame $w.fBut
    button $w.fBut.btnView -text "View Graph" -command "ViewSelection Graph $w"
    button $w.fBut.btnValues -text "Show Values" -command "ViewSelection Values $w"
    pack $w.fBut.btnView $w.fBut.btnValues -side left
  
    set dwb_AdmImpGraph "CurMagnitude"

    pack $w.fCur $w.fBut -side top
  }

  if {[string equal $CurAnalysis "Harmonic-Phase"] ||
      [string equal $CurAnalysis "Harmonic-Magnitude"] ||
      [string equal $CurAnalysis "Harmonic-Real_Part"] ||
      [string equal $CurAnalysis "Harmonic-Imaginary_Part"] ||
      [string equal $CurAnalysis "Harmonic"]} {

    if {[winfo exist .wDWB_ADM_IMP]} {
      destroy .wDWB_ADM_IMP
      update
      if {$MyGraphFlag == 1 || $MyGraphFlag == 2} {
        MyGraphOff
      }
      if {[winfo exist .wShowText]} {
        destroy .wShowText
        update
      }
      return
    }

    set w .wDWB_ADM_IMP

    InitWindow $w "Admittance & Impedance Results" PostAdmImpWindowGeom

    frame $w.fAdm
    label $w.fAdm.lblAdmittance -text Admittance:
    radiobutton $w.fAdm.rbAdmMagnitude -text Magnitude -variable dwb_AdmImpGraph -value "AdmMagnitude"
    radiobutton $w.fAdm.rbAdmPhase -text Phase -variable dwb_AdmImpGraph -value "AdmPhase"
    radiobutton $w.fAdm.rbAdmReal -text Conductance -variable dwb_AdmImpGraph -value "AdmReal"
    radiobutton $w.fAdm.rbAdmImaginary -text Susceptance -variable dwb_AdmImpGraph -value "AdmImaginary"
    radiobutton $w.fAdm.rbAdmCircle -text Circle -variable dwb_AdmImpGraph -value "AdmCircle"
    pack $w.fAdm.lblAdmittance $w.fAdm.rbAdmMagnitude $w.fAdm.rbAdmPhase $w.fAdm.rbAdmReal $w.fAdm.rbAdmImaginary $w.fAdm.rbAdmCircle -side left

    frame $w.fImp
    label $w.fImp.lblImpedance -text Impedance:
    radiobutton $w.fImp.rbImpMagnitude -text Magnitude -variable dwb_AdmImpGraph -value "ImpMagnitude"
    radiobutton $w.fImp.rbImpPhase -text Phase -variable dwb_AdmImpGraph -value "ImpPhase"
    radiobutton $w.fImp.rbImpReal -text Resistance -variable dwb_AdmImpGraph -value "ImpReal"
    radiobutton $w.fImp.rbImpImaginary -text Reactance -variable dwb_AdmImpGraph -value "ImpImaginary"
    radiobutton $w.fImp.rbImpCircle -text Circle -variable dwb_AdmImpGraph -value "ImpCircle"
    pack $w.fImp.lblImpedance $w.fImp.rbImpMagnitude $w.fImp.rbImpPhase $w.fImp.rbImpReal $w.fImp.rbImpImaginary $w.fImp.rbImpCircle -side left

    frame $w.fBut
    button $w.fBut.btnView -text "View Graph" -command "ViewSelection Graph $w"
    button $w.fBut.btnValues -text "Show Values" -command "ViewSelection Values $w"
    pack $w.fBut.btnView $w.fBut.btnValues -side left
  
    set dwb_AdmImpGraph "AdmMagnitude"

    pack $w.fAdm $w.fImp $w.fBut -side top
  }

  update idletasks
}

#
###
#

proc ShowFreq {} {
#  global ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  if {[.central.s info postprocess get cur_analisis] == "Static"} {
    WarnWin "Cannot display frequencies for a Static case!"
    return
  }

  if {[.central.s info postprocess get cur_analisis] == "Transient"} {
    WarnWin "Cannot display frequencies for a Transient case!"
    return
  }

  if {[.central.s info postprocess get cur_analisis] == "Harmonic-Phase"} {
    WarnWin "Cannot display frequencies for a Harmonic case!"
    return
  }

  if {[.central.s info postprocess get cur_analisis] == "Harmonic-Magnitude"} {
    WarnWin "Cannot display frequencies for a Harmonic case!"
    return
  }

  if {[winfo exist .wShowText]} {
    destroy .wShowText
    update
    return
  }
  
  set Filename [file join $ProjectPath $ProjectName]
  append Filename ".freq.csv"

  if {![file exist $Filename]} {
    WarnWin "Cannot find the frequency file."
    return
  } else {
    ShowTextFile $Filename
  }
}

#
###
#

proc MyClearGraphs {} {
  global MyGraphFlag

  if {$MyGraphFlag > 0} { MyGraphOff }
  
  if {[winfo exist .wDWB_ADM_IMP]} { 
    destroy .wDWB_ADM_IMP
    update
  }
  if {[winfo exist .wDWB_PAT]} {
    destroy .wDWB_PAT
    update
  }
  if {[winfo exist .wDWB_TVR]} {
    destroy .wDWB_TVR
    update
  }
  if {[winfo exist .wShowText]} {
    destroy .wShowText
    update
    return
  }
}
  
#
###
#

proc ReadIniValue {IniLine Variable} {

  set ndx [string first "=" $IniLine]
  set RetVal "-"
  
  if {$ndx != -1} {
    if {[string length $IniLine] > [expr {$ndx + 2}]} {
      set Left  [string range $IniLine 0 [expr {$ndx - 2}]]
      set Right [string range $IniLine [expr {$ndx + 2}] end]
      if [string equal $Left $Variable] {set RetVal $Right}
    }
  }
  
  return $RetVal
}

#
###
#

proc ReadIni { } {
  
  set INI1 "-"
  set INI2 "-"
  set INI3 "-"
  set INI4 "-"
  
  if [file exists [file join [GetDirectoryProblemType] "ATILA-GiD.ini"]] {
    if [catch {open [file join [GetDirectoryProblemType] "ATILA-GiD.ini"] r} fileId] {
    } else {
      if {![catch {gets $fileId IniLine}]} {
        # Check that first line has not been modified
        if [string equal $IniLine "# Settings for the ATILA-GiD interface - Please do not edit"] {
          if {![catch {gets $fileId IniLine}]} { set INI1 [ReadIniValue $IniLine "PTVersion"] }
          if {![catch {gets $fileId IniLine}]} { set INI2 [ReadIniValue $IniLine "IdealGiDVersion"] }
          if {![catch {gets $fileId IniLine}]} { set INI3 [ReadIniValue $IniLine "ReadAtiPostPath"] }
          if {![catch {gets $fileId IniLine}]} { set INI4 [ReadIniValue $IniLine "AniFrame"] }
          close $fileId
        }
      }
    }
  }
  return [list $INI1 $INI2 $INI3 $INI4]
}

#
###
#

proc InitGIDProject { dir } {
  global MenuNames MenuEntries MenuCommands MenuAcceler
  global MenuNamesP MenuEntriesP MenuCommandsP MenuAccelerP
  global MyAnimFlag MyGraphFlag AniFrame
  global IniHasChanged PTVersion IdealGiDVersion ReadAtiPostPath
#  global AtiFileName ProjectPath ProjectName

  GetProjectNames AtiFileName ProjectPath ProjectName

  set dir [.central.s info problemtypepath]

  # Default settings
# NO LONGER USED - See GetProjectNames() function
#  set AtiFileName "project"
#  set ProjectPath [lindex [.central.s info Project] 1]
#  append ProjectPath ".gid"
#  set ProjectName [file tail [lindex [.central.s info Project] 1]]
  set MyAnimFlag 0
  
  set IniHasChanged -1
  set PTVersion "1.4.5"
  set IdealGiDVersion "7.2"
  set ReadAtiPostPath "C:/"
  set AniFrame 20

  # Load Settings

  set INIList [ReadIni]
  set INI1 [lindex $INIList 0]
  set INI2 [lindex $INIList 1]
  set INI3 [lindex $INIList 2]
  set INI4 [lindex $INIList 3]
  
  if [string compare $INI1 $PTVersion      ] { set IniHasChanged 0 }
  if [string compare $INI2 $IdealGiDVersion] { set IniHasChanged 0 }
  if [string compare $INI3 $ReadAtiPostPath] { set IniHasChanged 0 }
  if [string compare $INI4 $AniFrame       ] { set IniHasChanged 0 }
  
  if [string compare $INI3 "-"] { set ReadAtiPostPath $INI3 }
  if [string compare $INI4 "-"] { set AniFrame $INI4 }

  SaveSettings
  
  # Check versions
  
  set MyVer [.central.s info GiDVersion]
  if {![string equal $MyVer $IdealGiDVersion]} {
#     SplashWarning dir "GiD version is not $IdealGiDVersion.\nThis problemtype may not work properly"
#    WarnWin "GiD version is not $IdealGiDVersion.\nThis problemtype may not work properly"
  }
  
  # set additional tcl files

  if { [catch {source [file join $dir "ATILAPostAnimate.tcl"]}] } {
    WarnWin "Error reading file MyPostAnimate.tcl\This problemtype is not correctly installed"  
    return
  }

  if { [catch {source [file join $dir "tknotepad.tcl"]}] } {
    WarnWin "Error reading file tknotepad.tcl\nThis problemtype is not correctly installed"  
    return
  }

  # Set Help 

  set ipos [lsearch $MenuNames Help]
  if { $ipos != -1 } {
    set MenuEntries($ipos) [linsert $MenuEntries($ipos) 0 "ATILA Help"]
    set MenuCommands($ipos) [linsert $MenuCommands($ipos) 0 [list -np- HelpOnATILA]]
    set MenuAcceler($ipos) [linsert $MenuAcceler($ipos) 0 ""]
    CreateTopMenus
  }
    
  set ipos [lsearch $MenuNamesP Help]
  if { $ipos != -1 } {
    set MenuEntriesP($ipos) [linsert $MenuEntriesP($ipos) 0 "ATILA Help"]
    set MenuCommandsP($ipos) [linsert $MenuCommandsP($ipos) 0 [list -np- HelpOnATILA]]
    set MenuAccelerP($ipos) [linsert $MenuAccelerP($ipos) 0 ""]
  }

  # Switch to Quadratic elements
  set quadratic [lindex [.gid.central.s info Project] 5]
  if {$quadratic != 1} {
    .gid.central.s process escape escape escape escape Meshing Quadratic Quadratic
  }
    
  # Modify Data menu
  GidChangeDataLabel "Interval" ""
  GidChangeDataLabel "Data units" ""
  GidAddUserDataOptions "---" "" 4
  GidAddUserDataOptions "---" "" 7

  # Add ATILA menu
  CreateMenu "ATILA" "PREPOST"
  InsertMenuOption "ATILA" "ATILA Help" 0 "HelpOnATILA" "PREPOST"
  InsertMenuOption "ATILA" "ATILA Supervisor" 1 "StartATI" "PREPOST"
  InsertMenuOption "ATILA" "Open shell" 2 "OpenShell" "PREPOST"
  InsertMenuOption "ATILA" "Open Editor" 3 "OpenEditor" "PREPOST"
  InsertMenuOption "ATILA" "Convert to ATI" 4 "RunDataReading" "PRE"
  InsertMenuOption "ATILA" "Run Solver" 5 "RunGA" "PRE"
  InsertMenuOption "ATILA" "Generate results" 6 "RunPST" "PRE"
  InsertMenuOption "ATILA" "Import ATI..." 7 "ReadAtiPre" "PRE"
#  InsertMenuOption "ATILA" "Read ATI (results)"  "ReadAtiPost" "POST"
  InsertMenuOption "ATILA" "Animate" 8 "MyAnimate" "POST"
  InsertMenuOption "ATILA" "Preferences" 9 "Preferences" "PREPOST"
  InsertMenuOption "ATILA" "About" 10 "About" "PREPOST"

  set MenuEntriesP(6)   {"View style" "View results" "Deform mesh" "Animate" "Border graph" "Several Results"}
  set MenuCommandsP(6)  {{ -np- PostDisplay} { -np- PostResults} { -np- PostGeom::Create} { -np- ATILAPostAnimate} { -np- PostGraphResultsWindow} { -np- PostVariosResultados}}
  UpdateMenus
  
  # Show Splash screen

  Splash $dir $PTVersion

  # Place tool bar
  MyPreBitmaps $dir
  MyPostBitmaps $dir

  # Set Switch for post animation and graph
  InitAnimAndGraphs

  # Return to main menu
  .gid.central.s process escape escape
}

#
###
#

proc EndGIDProject {} {
 
  #save settings
# when this command is ran on end gid project, the GetDirectoryProblemType function
# returns "", so the ATILA-GiD.ini file gets saved in the GiD7.1 folder instead
# of the correct 1.2.gid folder.
#  SaveSettings
   
  set MenuEntriesP(6)   {"View style" "View results" "Deform mesh" "Animate" "Border graph" "Several Results"}
  set MenuCommandsP(6)  {{ -np- PostDisplay} { -np- PostResults} { -np- PostGeom::Create} { -np- PostAnimateM} { -np- PostGraphResultsWindow} { -np- PostVariosResultados}}
  UpdateMenus

  #close bitmaps
  EndMyBitmaps
}

#
###
#

proc InitGIDPostProcess {} {
#  global ProjectPath ProjectName
  
  InitAnimAndGraphs

# NO LONGER USED - See GetProjectNames() function  
#  set ProjectPath [lindex [.central.s info Project] 1]
#  append ProjectPath ".gid"
#  set ProjectName [file tail [lindex [.central.s info Project] 1]]
}

#
###
#

proc EndGIDPostProcess {} {
}

#
###
#

proc LoadGIDProject {filespd} {
# NO LONGER USED - See GetProjectNames() function
#global ProjectPath ProjectName

#  set ProjectPath [file dirname $filespd]
#  set ProjectName [file tail [file rootname $filespd]]
  
#  if [string equal $ProjectPath [.central.s info problemtypepath]] {
#    set ProjectPath [lindex [.central.s info Project] 1]
#    append ProjectPath ".gid"
#    set ProjectName [file tail [lindex [.central.s info Project] 1]]
#  }
}

proc SaveGIDProject {filespd} {
# NO LONGER USED - See GetProjectNames() function
#global ProjectPath ProjectName

#  set ProjectPath [file dirname $filespd]
#  set ProjectName [file tail [file rootname $filespd]]

#  if [string equal $ProjectPath [.central.s info problemtypepath]] {
#    set ProjectPath [lindex [.central.s info Project] 1]
#    append ProjectPath ".gid"
#    set ProjectName [file tail [lindex [.central.s info Project] 1]]
#  }
}

proc OpenEditor {} {
#  global ProjectPath

  GetProjectNames AtiFileName ProjectPath ProjectName

  set default_eqi "default.eqi"
  if [string compare $ProjectPath "UNNAMED.gid"] {
    set default_eqi [file join $ProjectPath "default.eqi"]
  }
  startpad $default_eqi
}

proc GetProjectNames { varAtiFileName varProjectPath varProjectName } {
  upvar 1 $varAtiFileName AtiFileName
  upvar 1 $varProjectPath ProjectPath
  upvar 1 $varProjectName ProjectName

  set AtiFileName "project"
  set ProjectPath [lindex [.central.s info Project] 1]
  append ProjectPath ".gid"
  set ProjectName [file tail [lindex [.central.s info Project] 1]]
}
