#!/usr/bin/perl
#
# AUTHOR: Erik Nygren <nygren@mit.edu>, 1998.06.25
#
# This source code is placed into the public domain without any warranty,
# either expressed or implied.  Use at your own risk.
#


require 5.002;
use strict;



# effects:  Runs cal and loads <month,year> into a hash which it 
#           returns.  Before the hash, it returns a string describing
#           the month name.
#           The hash is keyed by day of week (Su, Mo, Tu, We, Th, Fr, Sa)
#           and contains a reference to an array of days as values. 
sub load_month {
    my ($month, $year) = @_;
    my @days = ( "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" );
    my %w = ();

    foreach (@days) { $w{$_} = []; }

    #print "<$month>,<$year>\n";
    open CAL, "cal $month $year|" or die "couldn't run cal\n";
    my $ml = <CAL>;
    $ml =~ /^\s*(\S+)\s+/;
    my ($monthname) = $1;
    my $tmp = <CAL>;

    foreach (<CAL>) {
	if (/^\s*$/) { next; }
	#print "got a line: ($_)\n";
	/^(..) (..) (..) (..) (..) (..) (..)/;
	#print "<$1> <$2> <$3> <$4> <$5> <$6> <$7>\n";
	my @d = @days;
	my $x;
	foreach $x (("$1 ", "$2 ", "$3 ", "$4 ", "$5 ", "$6 ", "$7 ")) {
	    my $dow = shift @d;	# day of week
	    #print "{$x}\n";
	    if (!($x =~ /^\s*$/)) {
		push @{$w{$dow}}, $x;
		#print "[$dow,$x]\n";
	    }
	}
    }
    close CAL;

    # Switch to 1 for debugging...
    if (0) {
	my $cd;
	foreach $cd (@days) {
	    print "$cd: ";
	    foreach (@{$w{$cd}}) {
		print "<$_> ";
	    }
	    print "\n\n";
	}
    }

    return ($monthname, %w);
}

use vars qw/ %w $mname $numwed /; 
($mname, %w) = load_month($ARGV[0], $ARGV[1]);

printf "BARC test on second Monday of the month: %s %s\n",
    $mname, $w{"Mo"}->[1];

$numwed = scalar @{$w{"We"}};

printf "MIT HAM test on the penultimate Wednesday of the month: %s %s\n",
    $mname, $w{"We"}->[$numwed-2];
