#!/usr/athena/bin/perl

$infile  = "/afs/sipb/user/nocturne/city/CITIES.TXT";
$outfile = "/afs/sipb/user/nocturne/city/citycode.pl";

%list = ();
$maxlen = 0;

open(IN, ("<" . $infile));

$in = <IN>;

# Look to see if we've hit real data yet
until ($in =~ /^[A-Z]{3} [A-Z]{2} \d/) {
    $in = <IN>;
}

$list{$code} = $city;

while (($in = <IN>) ne "") {
    $in =~ tr/A-Z/a-z/;
    chop($in);
    $in =~ /^([a-z0-9]{3}) .*\d (\D+)$/;
    $code = $1;
    $city = $2;
    if (length($city) > $maxlen) {
	$maxlen = length($city);
    }

    if (defined($list{$code})) {
	print "Multiple city names for $code: $list{$code}, $city\n";
	print "Warning: the code does not handle this situation.\n\n";
    }

    $list{$code} = $city;
} 

close(IN);

open(OUT, (">" . $outfile));
# open(OUT, ">&STDOUT");

print OUT "# this is a city file, generated by parsecity.pl .\n\n";
print OUT "package citycode;\n\n";
print OUT "sub citycode_assoc_array {\n(\n";

$donefirst = 0;
foreach $key (sort(keys(%list))) {
    if ($key ne "") {
	if ($donefirst) {
	    print OUT ",\n";
	} else {
	    $donefirst = 1;
	}
	print OUT ("    \"" . $list{$key} . "\",");
	print OUT (" " x ($maxlen - length($list{$key})));
	print OUT ("\"$key\"");
    }
}

print OUT ");\n}\n\n1;\n";
close OUT;
