#!/usr/local/bin/perl
#
# Given a set of files with names of the form yearmonthday (ex: 94jan1),
# Grab all those that are w/in the last 4 months, and concatenate
# them into "rumor.event". Also build a header file that shows which
# ones are in use.
#
# Called from compose-tricky while building events.txt
#
# By Alan Schwartz (Javelin/Paul)

$dir = ".";
$out = "rumor.event";
$hdr1 = <<'EOS';
& rumors
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= Rumors -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Rumor files contain tidbits of information, some of it helpful, some
misleading. Use what you can. To read them, use 'events <date>' 
  
To start a rumor, use the +rumor <message> command.
  
Current rumor files: 
EOS
$hdr2 = '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-';

# Get today's date
$today = `date`;
@today = split(" ",$today);
($mon,$day,$yr) = (@today[1..2],$today[$#today]);
$mon =~ tr/A-Z/a-z/;
$yr =~ s/^19//;

# How far back can we go?
@months=(jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec);
foreach (0..$#months) {
  $next = ($_ - 3) % 12;
  $year = $yr;
  $year-- if $next > $_;
  $months{$months[$_]} = "$year$months[$next]";
  $mnums{$months[$_]} = $_;
}

if ($months{$mon} =~ /(\d\d)(\w\w\w)/) {
   ($byr,$bmon) = ($1,$2);
}

print "Using rumors from $bmon $byr to $mon $yr\n";

# Get the list of files
opendir(DIR,$dir) || die "Unable to open $dir\n";
@files = grep(/^9/,readdir(DIR));
closedir(DIR);

foreach (@files) {
  ($fyr,$fmon,$fday) = /(\d\d)(\w\w\w)(\d+)/;
  $fmon2 = $fmon;
  $fmon =~ s/(\w)(\w+)/\u\1\2/;
  $file{$_} = "$fmon$fday", next if $fyr > $byr;
  $file{$_} = "$fmon$fday", next if (($fyr == $byr) && ($mnums{$fmon2} >= $mnums{$bmon}));
}

open(OUT,">$out") || die "Couldn't open $out!\n";
print OUT $hdr1;
@list = sort bydate keys %file;
$count = 0; print OUT " " x 10;
foreach (@list) {
  printf OUT "%-7s", $file{$_};
  $count++;
  if ($count == 8) {
	$count = 0;
	print OUT "\n"," " x 10;
  }
}
print OUT "\n$hdr2\n";

foreach (@list) {
  open(IN,$_) || (warn "Unable to open $_!\n" && next);
  while (<IN>) {
     print OUT;
  }
  close(IN);
}

close(OUT);

print "Done.\n";

exit 0;

sub bydate {
  return 0 if ($a eq $b);
  ($ya, $ma, $da) = $a =~ /(\d\d)(\w\w\w)(\d+)/;
  ($yb, $mb, $db) = $b =~ /(\d\d)(\w\w\w)(\d+)/;
  return $ya <=> $yb if ($ya != $yb);
  return $mnums{$ma} <=> $mnums{$mb} if ($mnums{$ma} != $mnums{$mb});
  return $da <=> $db;
}
