#!/usr/local/bin/perl

# This file is: order.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 looks 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.


undef @items;

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
    {
	push(items, $string);	# save the old item
	$string = $_;		# start the new item
    }			       
    else { $string .= $_; }
}

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

&evaluate_dates;		# turn mm/dd/yy into a numerical value
@sortdata = @items[sort by_date $[..$#items]; # sort the items
print @sortdata;		# output

sub by_date {  $keys[$a] <=> $keys[$b] } # simple numerical comparison
			      
sub evaluate_dates {
# We cannot compare dates lexicographically, so we must do it "numerically".
# To convert mm/dd/yy into a number, we simply consider the date to be
# a quantity of days since day 0.  We just pretend there are 31 days in each
# month, and 365 days in each year.  Therefore # days = 
# day + (month * 31) + (year * 365).

    undef @keys;

    foreach $string (@items)
    {
	$_ = $string;
	local($month, $day, $year) = /\s*(\d\d?)\/(\d\d?)\/(\d\d)/;
	local($value) = $day + ($month * 31) + ($year * 365);
	push(@keys, $value);
    }
}
