#!/usr/local/bin/perl

# Where_is.pl	by Carlos A. Pero
# 10/14 hacked on by Ducky Sherwood
#
# Script to take in building abbreviation and room number, parse, locate
# map file, and read in coordinates.
#
# Based upon CGI code:
# Form-mail.pl, by Reuven M. Lerner (reuven"the-tech.mit.edu).
# ------------------------------------------------------------
# Required files:
#
# where_is	(gd binary)
# ------------------------------------------------------------

# Set variables

$BINDIR = "/var/info/www/httpd/cgi-bin";
$DOCROOT = "/var/info/www/docs";
$NAVROOT = "$DOCROOT/navigation";
$TMPDIR = "$NAVROOT/tmp";
$SHORTTMP = "/navigation/tmp";
$CAMPUSMAP = "north_campus";
$MAPDIR= "$NAVROOT/maps";
$GIFDIR = "$NAVROOT/floorplans";
$HTMLDIR = "$NAVROOT/floorplans";
$ISMAPDIR = "$NAVROOT/ismaps";
$PID = getppid;

# Print out a content-type for HTTP/1.0 compatibility
print "Content-type: text/html\n\n";

# Need to clean up old tmp files
if (! opendir(TMP, $TMPDIR) ) {
	print "<title>Error</title>\n";
	print "<h1>Error</h1>\n";
	print "Could not read directory $TMPDIR.\n";
	die;
	}
@oldfiles =  readdir(TMP);
foreach $oldgif (@oldfiles) {
	# This *should* be easier - see about putting everything on one line...
	# If there are any .gifs lying around that are more than a 
	# day old, zap them.
	if (-f "$TMPDIR/$oldgif") {
		if ((-M "$TMPDIR/$oldgif") > .002)  {
			unlink("$TMPDIR/$oldgif");
			}
		}
        }


# Kludgy-hack
&initBuilding;


# Get the input
if ($ENV{'REQUEST_METHOD'} eq "POST") {
	read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
	}
else {
	$buffer = $ENV{'QUERY_STRING'};
	}
	

# Split the name-value pairs
@pairs = split(/&/, $buffer);

foreach $pair (@pairs)
{
    ($name, $value) = split(/=/, $pair);

    # Un-Webify plus signs and %-encoding
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    # Stop people from using subshells to execute commands
    # Not a big deal when using sendmail, but very important
    # when using UCB mail (aka mailx).
    # $value =~ s/~!/ ~!/g; 

	# Strip out any bad, bad characters
	$value =~ s/[!;\/]//g;

    # Uncomment for debugging purposes
    # print "$name is $value<P>";

	if ($name eq "bldg") {
		$bldg = $value;
		}
	elsif ($name eq "room") {
		$room = $value;
		}

}

if (!$bldg) {
	print "Content-type: text/html\n\n";
	print "<title>Error</title>";
	print "<h1>Error</h1>";
	print "<hr>Sorry, no building was specified.  Try again.\n";
	}

# The options on the pulldown menu on the north campus page
# have to be spelled out fully, sigh.  This checks to see
# if it is a short name or a long name, or neither
if (!$longbldg{$bldg}) {
	foreach $key (keys %longbldg) {
		if ($longbldg{$key} eq $bldg) {
			$bldg = $key;
			break;
			}
		}
	if (!$bldg) {
		print "Content-type: text/html\n\n";
		print "<title>Error</title>";
		print "<h1>Error</h1>";
		print "<hr>Sorry, that building was not recognized.  Try again.\n";
		}
	}

# Construct filename template (i.e.  tb.1f )
# If there is a room, then this is a floorplan, otherwise it
# is a building on the campus map
if ($room) {
	# We need to deal with basement floors, since they
	# are not usually listed as "014".
	($digitroom = $room) =~ s/[a-z]//ig;	# turn e.g. 308A into 308
	if ($digitroom < 100) {
		$FLOOR = "b";
		}
	else {
		$FLOOR = substr($room, 0, 1);
		}
	$FILENAME = "$bldg.$FLOOR"."f";
	}
else {
	$FILENAME = "$CAMPUSMAP";
	}


# Open mapfile, and push lines into array
open (MAPFILE, "$ISMAPDIR/$FILENAME.ismap") || die "Cannot find file $ISMAPDIR/$FILENAME.ismap!\n";
while (<MAPFILE>) {
	chop;
	$foo = $_;
	# $foo = s/\s*/ /g;	# not sure if this is needed; just being safe
	($type, $line) = split(/ /, $foo);
	push (@lines, $line);
}
close (MAPFILE);

# Find line with building name and room number
if ($room) {
	@match = grep(/bldg=$bldg/ && /room=$room/, @lines);
	}
else {
	@match= grep(/buildings\/$bldg.top.html/, @lines);
	}

# Parse out coordinates
if ($room) {
	($foo, $coords) = split(/$room/, $match[0]);
	}
else {
	($foo, $coords) = split(/$bldg.top.html/, $match[0]);
	}
$coords =~ s/^\s*//;
($coord1, $coord2) = split(/\s/, $coords);

# Do calculations for gd binary
($x1, $y1) = split(/,/, $coord1);
($x2, $y2) = split(/,/, $coord2);

$cx = int(($x1+$x2)/2);
$cy = int(($y1+$y2)/2);
$dx = $x2 - $x1;
$dy = $y2 - $y1;
if ($dy > $dx) {
	$wh = 1.2* int($dy);
	}
else {
	$wh = 1.2* int($dx);
	}


if ($room) {
	# print "exec:\n\t$BINDIR/where_is.gd $GIFDIR/$FILENAME $TMPDIR/$PID $cx $cy $wh";
	`$BINDIR/where_is.gd $GIFDIR/$FILENAME $TMPDIR/$PID $cx $cy $wh`; 
	
	# Print a title and initial heading
	print "<Head><Title>Location of Room $room in $longbldg{$bldg}</Title></Head>\n";
	print "<Body><H1>Location of Room $room in $longbldg{$bldg}</H1>\n";
	print "<P>\n";
	print "<a href=/cgi-bin/imagemap/tb_".$FLOOR."f>\n";
	print "<IMG SRC=\"$SHORTTMP/$PID.gif\" ismap></a><p>\n";
	
	print "<a href=/cgi-bin/where_is?bldg=$bldg>Where am I on campus?</a><br>\n";
	print "<p>Go to <a href=/navigation/buildings/$bldg.top.html>$longbldg{$bldg}</a> main information page<br>\n";
	print "Go to <a href=/navigation/maps/north_campus.html>Campus Map</a><br>\n";
	}
else {
	# print a title and initial heading
	# print "exec: $BINDIR/where_is.gd $MAPDIR/$FILENAME $TMPDIR/$PID $cx $cy $wh\n"; 
	`$BINDIR/where_is.gd $MAPDIR/$FILENAME $TMPDIR/$PID $cx $cy $wh`; 
	print "<Head><Title>Location of $longbldg{$bldg}</Title></Head>\n";
	print "<Body><H1>Location of $longbldg{$bldg}</H1>\n";
	print "Click on any building that is in blue to get further information\n";
	print "about that building, or select it with the menubar below to see\n";
	print " where it is on the map.  (Don't forget to click on \"Locate\"!)\n";

	&writeLocatorMenu;
	print "<P>\n";
	print "<a href=/cgi-bin/imagemap/$CAMPUSMAP>\n";
	print "<IMG SRC=\"$SHORTTMP/$PID.gif\" ismap></a><p>\n";
	
	}
print "Go to <a href=http://www.cen.uiuc.edu/COE-Info/coe.top.html>College of Engineering Home Page</a><br>\n";
print "Go to <a href=http://www.uiuc.edu/>University of Illinois Home Page</a><br>\n";
print "<hr>\n";
print "This page was made possible in part by a grant from <a href=http://sundance.cso.\n";
print "uiuc.edu/index.html>CCSO</a>.\n";

print "<H5>On-the-fly graphics by Carlos A. Pero (c-pero@uiuc.edu)\n";
print "using the <a href=http://siva.cshl.org/gd/gd.html>gd 1.0</a> library</h5>\n";
print "<P>";
print "Surrounding text by\n";
print "<a href=ftp://ftp.netcom.com/pub/ducky/ducky.home.html><i>ducky@uiuc.edu</i></a>,\n";
print "maintained by\n";
print "<a href=ftp://ftp.netcom.com/pub/ducky/ducky.home.html><i>ducky@uiuc.edu</i></a>.\n";

# Hmmmmmmmmm these don't work...
# unlink("$TMPDIR/$PID.gif");
# `sleep 100; rm $TMPDIR/$PID.gif &`;

###############################################################################
# Arg - Big Dumb Kludgy-Hack until I can figure out how to include things over here
###############################################################################
sub initBuilding  {
	$longbldg{"edge"} = "The Void at the Edge of the Universe";
	$longbldg{"ala"} = "Aero Lab A";
	$longbldg{"astronomy"} = "Astronomy Building";
	$longbldg{"beckman"} = "Beckman Institute";
	$longbldg{"bfiedl"} = "Field - for EERL Replacement";
	$longbldg{"ceram"} = "Ceramics Building";
	$longbldg{"cerl"} = "Computer-Based Education Research Laboratory";
	$longbldg{"csrl"} = "Computer and Systems Research Laboratory";
	$longbldg{"dcl"} = "Digital Computer Laboratory";
	$longbldg{"ehall"} = "Engineering Hall";
	$longbldg{"equad"} = "Engineering Quadrangle";
	$longbldg{"esb"} = "Engineering Systems Building";
	$longbldg{"everitt"} = "Everitt Laboratory";
	$longbldg{"grainger"} = "Grainger Library and Information Center";
	$longbldg{"kenny"} = "Kenny Gymnasium";
	$longbldg{"kenny-annex"} = "Kenny Gymnasium Annex";
	$longbldg{"loomis"} = "Loomis Laboratory of Physics";
	$longbldg{"meb"} = "Mechanical Engineering Building";
	$longbldg{"mel"} = "Mechanical Engineering Laboratory";
	$longbldg{"mmb"} = "Metallurgy and Mining Building";
	$longbldg{"mrl"} = "Seitz Materials Research Laboratory";
	$longbldg{"nel"} = "Nuclear Engineering Laboratory";
	$longbldg{"newmark"} = "Newmark Civil Engineering Building";
	$longbldg{"nrl"} = "Nuclear Radiation Laboratory";
	$longbldg{"parking"} = "Springfield Parking Lot";
	$longbldg{"phys1"} = "Physics House 1";
	$longbldg{"phys2"} = "Physics House 2";
	$longbldg{"talbot"} = "Talbot Laboratory";
	$longbldg{"tb"} = "Transportation Building";
	$longbldg{"tennis"} = "Tennis Courts";
	$longbldg{"uni"} = "University High School";
	$longbldg{"microel"} = "Microelectronics Laboratory";
	$longbldg{"super"} = "Superconductivity Research Laboratory";
	$longbldg{"warehouse"} = "Warehouse";
	$longbldg{"wrighttrailers"} = "Wright Street Trailers";
	$longbldg{"safety"} = "Public Safety";
	$longbldg{"h2o"} = "Hydrosystems Laboratory";
	$longbldg{"kiln"} = "Kiln House";
	$longbldg{"union"} = "Illini Union";

	}
###############################################################################
# Write out the locator menu
###############################################################################
sub writeLocatorMenu {
	print "<form method=\"GET\" action=\"http://www.uiuc.edu/cgi-bin/where_is\">\n";
	print "<input type=\"submit\" value=\"Locate \">\n";
	print "<select name=\"bldg\">\n";
	print "<option>Transportation Building (most complete)\n";
	print "<option>Beckman Institute\n";
	print "<option>Ceramics Building\n";
	print "<option>Computer and Systems Research Laboratory\n";
	print "<option>Digital Computer Laboratory\n";
	print "<option>Engineering Hall\n";
	print "<option>Engineering Research Laboratory\n";
	print "<option>Engineering Systems Building\n";
	print "<option>Everitt Laboratory\n";
	print "<option>Grainger Library and Information Center\n";
	print "<option>Hydrosystems Laboratory\n";
	print "<option>Illini Union\n";
	print "<option>Kenny Gymnasium\n";
	print "<option>Kiln House\n";
	print "<option>Loomis Laboratory of Physics\n";
	print "<option>Mechanical Engineering Building\n";
	print "<option>Mechanical Engineering Laboratory\n";
	print "<option>Metallurgy and Mining Building\n";
	print "<option>Microelectronics Laboratory\n";
	print "<option>Newmark Civil Engineering Building\n";
	print "<option>Nuclear Engineering Laboratory\n";
	print "<option>Nuclear Radiation Laboratory\n";
	print "<option>Public Safety\n";
	print "<option>Seitz Materials Research Laboratory\n";
	print "<option>Superconductivity Research Laboratory\n";
	print "<option>Talbot Laboratory\n";
	print "<option>Tennis Courts\n";
	print "<option>University High School\n";
	print "</select>\n";
	print "on campus map<p>\n";
	}

