#!/afs/athena/contrib/perl5/perl -w

use strict;
use Carp;
use FileHandle;
use lib '/mit/bert/PERL';
use DataDump;

$SIG{'SEGV'} = sub { die "Perl sucks!!!"; };

#### parse arguments

$0 =~ s@.*/@@g;

sub usage {
  die("Usage:  $0 directory\n" . join('', map("$_\n", @_)));
}

(@ARGV == 1)    || usage("Invalid number of arguments specified.");

#### cd to relevant directory

chdir($ARGV[0]) || usage("Cannot chdir to '$ARGV[0]'; check permissions.");

#### get and parse the list of data files

my (@files) = glob 'logins.*';
(@files)        || usage("No data files found in directory '$ARGV[0]'");

my (%fset);

foreach (@files) {
  /^logins\.([^.]+)(?:\.(.*))?$/
    ? $fset{"$2"}{"$1"} = $_
      : warn("Invalid file name '$_' ignored");
}

#### insure each dataset has a .quick. and a .cmp. file, the process them.

use vars qw(@month %month);
@month = qw(jan feb mar apr may jun jul aug sep oct nov dec);
%month = map( ($month[$_], $_+1), 0..$#month );

sub by_date {
  my @a = ($a =~ /^(\D+)(\d+)$/);
  my @b = ($b =~ /^(\D+)(\d+)$/);
  return 0                 unless (@a || @b);
  return 1                 unless (@a);
  return -1                unless (@b);
  return ($a[1] <=> $b[1]) if ($month{$a[0]} == $month{$b[0]});
  ($month{$a[0]} <=> $month{$b[0]});
}

foreach (sort by_date keys %fset) {
  if (! exists($fset{$_}{'cmp'}) || ! exists($fset{$_}{'quick'})) {
    # The data set does not contain all data we expect.
    my $date_id = (length($_) ? "data set from $_" : 'last data set');
    warn "The $date_id does not contain a .cmp. file.\n"
      unless exists($fset{$_}{'cmp'});
    warn "The $date_id does not contain a .quick. file.\n"
      unless exists($fset{$_}{'quick'});
    my @ignored = map "'$_'", values %{$fset{$_}};
    warn "File(s) @ignored aren't a complete dataset,\n   ignoring";
  } else {
    # The data set does contain all data we expect, but may have extra.
    if (scalar(keys %{$fset{$_}}) != 2) {
      my $date_id = (length($_) ? "data set from $_" : 'last data set');
      warn "The $date_id contains extraneous files which will be ignored.\n";
    }

    process($_);
  }
}

#### code to do top-level processing of data

sub process {
  my ($date) = @_;
  print "$date\n";
}
