#!/afs/sipb/project/perldev/p -w

use strict;
use IO::File;
use DirHandle;
use lib '/afs/sipb.mit.edu/user/bert/dev/perl5';
use Finger;

my $LIST_ACTIVE = 1;


$Finger::ConnectTimeout = 5;
sub finger {
  scalar( eval { Finger::data(@_) } || '' );
}

sub perl_glob_sucks {
  my ($dir, $regexp, $name_only) = @_;
  my $argh = new DirHandle $dir;
  my (@list, $entry);
  ($entry =~ /^$regexp$/) && push(@list, $entry)
    while defined($entry = $argh->read);
  $argh->close;
  return sort @list if $name_only;
  map "$dir/$_", sort @list;
}


chdir('/afs/zone.mit.edu/user/bert/THESIS_DATA')
  or die "can't chdir???: $!\n";

use vars qw( %file %host $MAGIC_SIZE $log $queue $new $ln @subdirs $dir $seq );
@subdirs = ('current', 'returns');
$MAGIC_SIZE = 2853;
$seq = 'S000';

print "Scanning files...\n";
foreach $dir (@subdirs) {
  foreach (perl_glob_sucks($dir, 'return_.*', 1)) {
    $file{$_} = "$dir/$_";
  }
}
%file or die "No return files present.\n";

print "Building host table...\n";
foreach (map( (perl_glob_sucks($_, 'log'), perl_glob_sucks($_, 'log\..*')),
	      @subdirs )) {
  $log = new IO::File $_, 'r'
    or die "can't open '$_': $!\n";
  while (<$log>) { /^\+ (\S+) (\S+)/; $host{$1} = $2; }
  $log->close;
}

print "Cross-referencing master queue...\n";
$queue = new IO::File 'current/queue.master', 'r'
  or die "can't open master queue: $!\n";
scalar <$queue>;  # dump first line
$ln = 2;

$new = new IO::File 'current/queue.new', 'w'
  or die "can't open add queue: $!\n";

use vars qw( $tag $x $y $step $off $froot );
use vars qw( $i $fname $size @missing @zero @bad );

while (<$queue>) {
  my @l = /^(.{4})> -x ([^,]+),([^,]+) -y ([^,]+),([^,]+) -a (\d+) -A (\d+)$/
    or die "Bad format: '$_'\n";
  ($tag, $x, $y, $step, $off) = @l[0,1,3,5,6];
  $froot = "return_$l[1],$l[3]_";

  @bad = ();

  for ($i = $off;  $i < 180;  $i += $step) {
    $fname = sprintf('%s%03d', $froot, $i);
    if (!exists $file{$fname}) {
      push @bad, $i;
    } else {
      $size = -s $file{$fname};
      push @bad, $i unless $size;
      print "$fname: bad size? ($size)\n" if $size and ($size != $MAGIC_SIZE);
      delete $file{$fname};
    }
  }

  if (@bad) {
    if ( finger('@'.$host{$tag}) =~ /\sbert\s/s) {
      print "  [$tag\@\L$host{$tag}\E: calculating @bad]\n"
	if $LIST_ACTIVE;
    } else {
      printf "%20s*: %s\n", $froot, "redoing @bad";
      print $_;
      ++$seq;
      print      "$seq> -x $x,$x -y $y,$y -a $step -A $bad[0]\n";
      print $new "$seq> -x $x,$x -y $y,$y -a $step -A $bad[0]\n";
    }
  }

  last unless %file;

  $ln++;
}

print "Last set of files corresponds to tag $tag.\n";
