#!/usr/local/bin/perl

# This file is: order_cal.pl - sort entries in the calendar by date
# for the DIMACS Info Service
# GEA 9/20/92

# What this program does:

# We wish to sort the Calendar file by dates of the events.
# The token ";H1" is used to indicate the start of an "item",
# which when run through the hd utility will produce a menu item.
# Items look like this:

# ;H1  9/07/92    Rutgers: Gregory Cherlin "Arity of Wreath Products"
#         Monday, Sept. 7            Logic
#           2:30 PM, Room 252        G. Cherlin, Rutgers University
#                                    "Arity of wreath products"
# *******************************************************************************

# So we'll be sorting on the first date field, which looks like mm/dd/yy.

require "ctime.pl";
$_ = $date = &ctime(time);
chop $date;
local($weekday, $month, $mday, $hourly, $year) = split;
if ($debug)
{
    print "$date\n";
    print "weekday = $weekday\n";
    print "month = $month\n";
    print "mday = $mday\n";
    print "hourly = $hourly\n";
    print "year = $year\n";
}

undef @month_names;

%month_names = 
(
    'Jan', 1,
    'Feb', 2,
    'Mar', 3,
    'Apr', 4,
    'May', 5,
    'Jun', 6,			
    'Jul', 7,
    'Aug', 8,
    'Sep', 9,
    'Oct', 10,
    'Nov', 11,			
    'Dec', 12,
 );

$today = $mday + ($month_names{$month} * 31) + ($year * 365);	

undef @items;
undef @keys;

while(<stdin>)    # skip past any garbage in the header until the first real entry
{
    if (/^;H1/)
    {
	$string = $_;
	last;
    }
}       

while(<stdin>) 
{
    if (/^;H1/)			# found the start of a new item
    {
	$keep = $_;
	($month, $mday, $year) = ($string =~ /\s*(\d\d?)\/(\d\d?)\/(\d\d)/);
	$year += 1900;		# years are specified by last two digits only
	$value = $mday + ($month * 31) + ($year * 365);
	if ($value >= $today) # date has not yet passed
	{			
#	    print  "$month/$mday/$year has not yet arrived\n";
	    push(@items, $string);	# save the old item
	    push(@keys, $value);
	}
#	else 
#	{ 
#	    print "$month/$mday/$year has already passed\n"; 
#	}
	$string = $keep;		# start the new item
    }			       
    else { $string .= $_; }
}

# This sort is not terribly obvious.  See the Perl book, pp 245-246.


@sortdata = @items[sort by_date $[..$#items]; # sort the items
print @sortdata;		# output

sub by_date {  $keys[$a] <=> $keys[$b] } # simple numerical comparison
