#!/s/perl/bin/perl
# $Id: sort_phd_info.pl,v 1.1 1995/06/30 21:09:48 bates Exp bates $

###
### sort the entries in the phd_info database
###

require 5.000;			# This uses perl 5.000 constructions

$dbName = "phd_info";		# declare the database

				# Define the sorting order with a
				# subroutine.  Note the use of <=> for
				# numerical fields and cmp for text
				# fields.  The field names come from
				# the $dbName.form file.
				# The variable names $a and $b are magic.
sub byfields {
    $grd = $a->{'grad-yr'} <=> $b->{'grad-yr'};	# compare graduation year
    return ($grd) unless $grd == 0; # return if years are different, otherwise
    $a->{'lastname'} cmp $b->{'lastname'} # compare last names
}

$DIR = '/p/stat/Data/admin/';	# Set the directory
$FSEP = "\t";			# separate fields by tabs

###
### Don't change things after here unless you are prepared to debug it
### yourself.                           DMB. 95/06/30
###

die '$dbName must be defined to use the sort!\n'
    unless $dbName;

$DB = $DIR . $dbName;		# Name of database
$FORM = $DB . ".form";		# Name of emacs-lisp form definition
				# for database
open(FORM, "< $FORM") ||
    die ("Unable to open form file $FORM: $!\n");
undef $/; $form = <FORM>; $/ = "\n"; # slurp entire form file into a
				     # string
die "$FORM does not define the fields!\n"
    unless ($form =~ /\(forms-enumerate[^']*'\(([^\)]*)/);
@FIELDS = grep(!/^$/, split(/\s+/, $1));

rename($dbName, $dbName . ".bak") || # create a backup of the file
    die ("Unable to move $dbName to ${dbName}.bak: $!\n");
open(INPUT, "< $dbName.bak") ||
    die ("Unable to open $dbName.bak for input: $!\n");
open(OUTPUT, "> $dbName") ||
    die("Unable to open $dbName for output: $!\n");

$flen = $#FIELDS;

while (<INPUT>) {
    $rcount++;			# keep track of the record count
    @thisRec = split(/$FSEP/, $_);
    die "Record $rcount has $#thisRec fields.  It should have $flen.\n"
	unless $flen == $#thisRec;
    $thishash = {};
    for (@FIELDS) {
	$thishash->{$_} = shift(@thisRec);
    }
    push(@RECORDS, $thishash);
}
close(INPUT);

@SORTED = sort byfields @RECORDS;

for (@SORTED) {
    undef @rec;
    foreach $f (@FIELDS) {
	push(@rec, $_->{$f});
    }
    print OUTPUT join("\t", @rec);
}
