# JStrack:  copyright 1997/2010 by Jim Graham, N5IAL, all rights reserved.
#

# Global (well, static, actually, but Tcl doesn't have static vars)
# array variable to be used in this file ONLY!

array set last_st_access {}

# Globals here must mirror test_st_files below
proc test_progs {cmd} {
   global st_names st_times last_st_access storms auto_update
   global full_update update_prog pos_est_prog last_full_update
   global ok_for_full_test new_pos_est auto_load_new

   if {[catch { eval exec $cmd } msg]} {
      tk_messageBox -type ok -message $msg
   }
}

# Globals here must be mirrored in test_progs above
proc test_st_files {{init 0}} {
   global st_names st_times last_st_access storms auto_update
   global full_update update_prog pos_est_prog last_full_update
   global ok_for_full_test new_pos_est auto_load_new

   if {[catch {glob $storms/*.trk}]} { return }
   foreach i [glob $storms/*.trk] {
      file stat $i f_stats
      set f_mtime $f_stats(mtime)
      set name [string toupper [file tail [file rootname $i]]]

      if {[string compare [array get st_times $name] ""]} {
         set full_update 0
         set new_pos_est 0
         set ok_for_full_test 0
         set tmplist [split "$st_times($name)"]
         set last_full_update [lindex $tmplist end]
      }

      if {$init} {
         set last_st_access($i) $f_mtime
      } elseif {[array get last_st_access $i] == ""} {
         if {[info exists auto_load_new] && $auto_load_new} {
            set load "yes"
         } else {
            set load [tk_messageBox -message "New storm ($name):  Load data?" \
               -type yesno]
         }

         if {$load == "yes"} {
            reload $name ; update
            if {[info exists update_prog] && $update_prog != ""} {
               catch { eval exec $update_prog }
            }
         }
         set last_st_access($i) $f_mtime
      } elseif {$st_names == ""} {
         set last_st_access($i) $f_mtime
      } else {
         set f_atime $last_st_access($i)
         if {$f_atime < $f_mtime} {
            if {[array get st_times $name] != ""} {
               toplevel .file$name
               wm geometry .file$name +150+150
               wm attributes .file$name -topmost true
               label .file$name.lbl -text "Reloading storm data for $name"
               pack .file$name.lbl
               update
               after 2500
               destroy .file$name ; reload $name ; update
               set last_st_access($i) $f_mtime
               set nm [string tolower $name]
               if {[info exists update_prog] && $update_prog != "" && $full_update} {
                  catch { eval exec $update_prog }
               } elseif {[info exists pos_est_prog] && $pos_est_prog != "" && $new_pos_est} {
                  catch { eval exec $pos_est_prog }
               }
            }
         }
      }
   }
   if {$auto_update} { after 60000 test_st_files }
}


