#!/usr/local/bin/perl

# Script for on-line appointment scheduling for Reg Day.
use CGI qw(:all);
$name=param("name");
chomp($name);
$time=param("time");
chomp($time);

#########################
#remove advisee from list
#########################

#open and read advisee file
open(ADVISEES, "/c/deacon/WWW/advisees.txt");
$count = 0;

while(<ADVISEES>){
    $students[$count] = $_;    
    $count++;
}
close(ADVISEES);

$studentCount = $count;


###################
#read the schedule
###################
open(SCHEDULE, "/c/deacon/WWW/schedule_Leiserson.txt") ||
     die "Couldn't open file /c/deacon/WWW/schedule_Leiserson.txt";

$count=0;
while(<SCHEDULE>){
    $appointments[$count]=$_;    
    $count++;
}
$appointments[$count]="END";
close(SCHEDULE);

#######################################
#find time slot and enter advisees name
#######################################
$status=0;
$count=0;
while($appointments[$count] ne "END"){
    @junk = split(" ", $appointments[$count]);    
    if($junk[0] eq $time){
	if($junk[1] ne ""){
	  $status=1; 
        } else { 
          $status=2; 
          $appointments[$count]="$time $name\n"; 
        }
    }  
    $count++;
}

if($status eq 2) {
 #write advisee list without current advisee
 open(ADVISEES, ">/c/deacon/WWW/advisees.txt") ||
     die "Couldn't open file /pub/www/cgi-bin/RegDay/advisees.txt";

$count=0;

while($count<$studentCount){
        chomp $students[$count];
    if($students[$count] ne $name){
        print ADVISEES  "$students[$count]\n";
    }
    $count++;
}
close(ADVISEES);
}
#######################
#write the new schedule
#######################
open(NEWSCHEDULE, ">/c/deacon/WWW/schedule_Leiserson.txt") ||
     die "Couldn't open file /c/deacon/WWW/schedule_Leiserson.txt";

$count=0;
while($appointments[$count] ne "END"){
      print NEWSCHEDULE "$appointments[$count]";
    $count++;
}
close(NEWSCHEDULE);

####################
#return confirmation
####################
print "Content-type: text/html \n\n";
print "<html>\n"; 
print "<head><title>Registration Day Fall 2000</title></head>\n";
print "<body>\n";
print "<center><BR>";
print "<H3>";
print "Professor Charles Leiserson<br>";
print "Fall 2000<BR>";
print "Registration Day<BR>";
print "Tuesday, September 5, 2000<BR>";
print "</H3>";
print "<br><BR><BR>";
print "</center>";

if($status eq 1) {
print " Dear $name, <br>";
print " That time slot is taken, please hit back then reload and try again."; 
} 

if($status eq 2) {
print "<font size=6> Thank you, $name!</font> <p>";
print "<font size=4>We look foward to seeing you in <b>10-421</b> at <b>$time</b>.</font> <p>";
print "<font size=2>If you have any questions, problems, or need to change your appointment, please contact Leigh at deacon\@mit.edu or 617-253-2322.</font>";
} 

if($status eq 0) {
print "There was an error processing your request. please contact deacon\@mit.edu";
}
print "</body></html>";     


