namespace eval timestamp {
  set timestamps {}
  set read_time 0
  set filename "$GRACER_USER/timestamp"

  namespace export store save load check check_load
}

proc timestamp::check_load {} {
  variable read_time
  variable filename

  if [file readable $filename] {
    set time [file mtime $filename]
    if {$time > $read_time} {
      timestamp::load
    }
  }
}

proc timestamp::store {key second} {
  variable timestamps

  timestamp::check_load

  set modified 0
  set length [llength $timestamps]
  for {set i 0} {$i < $length} {incr i} {
    set entry [lindex $timestamps $i]
    if [string match $key [lindex $entry 0]] {
      if {$second != [lindex $entry 1]} {
	set timestamps [lreplace $timestamps $i $i [list $key $second]]
	set modified 1
      }
      break
    }
  }
  if {$i == $length} {
    lappend timestamps [list $key $second]
    set modified 1
  }

  if {$modified} {
    timestamp::save
  }
  return $modified
}

proc timestamp::check {filename} {
  return [timestamp::store [cache::url $filename] [get_time_stamp $filename]]
}

proc timestamp::load {} {
  variable timestamps
  variable read_time
  variable filename

  set timestamps {}
  if [file readable $filename] {
    set file [open $filename "r"]
    while {![eof $file]} {
      gets $file entry
      if [string length $entry] {
	lappend timestamps $entry
      }
    }
    close $file
  }
  set read_time [file mtime $filename]
}

proc timestamp::save {} {
  variable timestamps
  variable read_time
  variable filename

  set file [open $filename "w"]
  foreach entry $timestamps {
    puts $file $entry
  }
  close $file
  set read_time [file mtime $filename]
}
