#!/usr/bin/perl

use strict;

use Time::Local;

use DBI;
my  $dsn = "DBI:mysql:database=status";
my $user = "root";
my $password = "escort";
my $dbh = DBI->connect($dsn, $user, $password) or die $DBI::errstr;

my ($loncenter,$timecenter,$trainlength,undef,$x) = @ARGV;

my $x0 = $x - 3200;
my $x9 = $x + 3200;

my $tc = $dbh->selectall_arrayref("SELECT trkid,pointname,trklen,trklon from trklon where (trklon+trklen>$x0) and trklon<$x9 order by trklon");

my %rtuhit;

for (@$tc) {
#  print "a block to map is ",$_->[0],"\n";
  if ($_->[0] =~ /^(\w\d\d)/) {
    $rtuhit{$1}++;
  }
}

my ($s,$m,$h) = localtime $timecenter;

my $t = $h*3600+$m*60+$s;

print "tsearch is $t\n";

print `/home/shoppa/getfeplogs`;

open STALE,"<","/tmp/staledata" or die "failed to open staledata log: $!";

while (<STALE>) {
  if (m/(\d\d)\:(\d\d)\:(\d\d) to (\d\d)\:(\d\d)\:(\d\d)\: (\w\d\d)/) {
    my ($h0,$m0,$s0,$h1,$m1,$s1,$rtu) = ($1,$2,$3,$4,$5,$6,$7);
    if (exists $rtuhit{$rtu}) {
      my $t0 = $h0*3600+$m0*60+$s;
      my $t1 = $h1*3600+$m1*60+$s;
      $t0 = $t0 - 120; $t1 = $t1 + 120;
      print "t0 t1 $t0 $t1";
      if ($t0<$t && $t<$t1) {
        print "looks like stale data\n";
	$dbh->do("UPDATE fitfails set color='grey' where trklon=$loncenter and time=$timecenter") or die $dbh->errstr;
        $dbh->do("UPDATE fitfails set badness=0 where trklon=$loncenter and time=$timecenter") or die $dbh->errstr;
        last;
      }
    }
  }
}
