#!/usr/bin/perl
#  Copyright 2001-2023 Leslie Richardson

#  This file is part of Open Admin for Schools.

#  Open Admin for Schools is free software; you can redistribute it 
#  and/or modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2 of 
#  the License, or (at your option) any later version.

my %lex = ('Main' => 'Main',
	   'Timetable' => 'Timetable',
	   'Edit' => 'Edit',
	   'Terms' => 'Terms',
	   'Update' => 'Update',
	   'Term' => 'Term',
	   'Day' => 'Day',
	   'Per' => 'Per',
	   'Subject-Section' => 'Subject-Section',
	   'Period' => 'Period',
	   'Record' => 'Record',
	   'Backings' => 'Backings',
	   'Add' => 'Add',
	   'Additional' => 'Additional',
	   'Adding' => 'Adding',
	   'Missing' => 'Missing',
	   'Continue' => 'Continue',
	   'Delete' => 'Delete',
	   'Contact' => 'Contact',
	   'Separate With Spaces' => 'Separate With Spaces',
	   'Error' => 'Error',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Staff' => 'Staff',
	   'Not Found' => 'Not Found',
	   'Configuration' => 'Configuration',
	   'Record Exists' => 'Record Exists',
	   'Course' => 'Course',
	   'Skipping' => 'Skipping',


	   );

# max number of backed classes per cycle. 
#(control display and entry)
my $maxbackings = 12; 

use DBI;
use CGI;

my $self = "ttEdit.pl";


my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $currdate = "$year-$month-$time[3]";

# Set prepath for config file:
my $prepath = '../..';
eval require "$prepath/etc/admin.conf";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}


my $q = new CGI;
my %arr = $q->Vars;

my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);


print $q->header( -charset, $charset );


# print page header.
my $title = "$lex{Edit} Teacher $lex{Timetable}";

print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">
$chartype\n</head><body>\n};

print qq{[ <a href="$homepage">$lex{Main}</a> | <a href="$schpage">$lex{Timetable}</a> ]\n};

print qq{<h1>$title</h1>\n};


if ( not $arr{page} ) {
    showStartPage();

} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    setTimetable();

} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    updateRecords();

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    printBackingsForm(); # $arr{userid}, $arr{terms} );

} elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    addBackings();
    
} elsif ( $arr{page} == 5 ) {
    delete $arr{page};
    deleteErrors();
}

#----------------
sub deleteErrors {
#----------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

    my ($userid, $currterm) = ( $arr{userid}, $arr{currterm});
    delete $arr{userid};
    delete $arr{currterm};

    my $sth1 = $dbh->prepare("select * from schedat where id = ?");
    my $sth = $dbh->prepare("delete from schedat where id = ?");

    foreach my $id ( sort keys %arr ) {
	# Load the record, then delete
	$sth1->execute($id);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
	my $ref = $sth1->fetchrow_hashref;
	my %r = %$ref;
	
	$sth->execute($id);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
	print qq{<div>Error $r{subjsec} / Term $r{term} Deleted</div>\n};
    }

    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="1">\n};
    print qq{<input type="hidden" name="staff" value="$userid">\n};
    print qq{<input type="hidden" name="term" value="$currterm">\n};
    print qq{<input type="submit" value="Continue to Set Timetable">\n};
    print qq{</form>\n};
    
    print qq{</body></html>\n};
    
    exit;
}



#----------------
sub showStartPage {
#----------------


    my %teachers;
    my $sth = $dbh->prepare("select distinct teacher from subject 
			    where teacher is not NULL and teacher != '' ");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr;}
    while ( my $tch = $sth->fetchrow ) {
	$teachers{$tch} = 1;
    }

    # Get Teachers Name
    my %noname;
    $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    
    my (%sort, %teachername);
    foreach my $userid (  sort keys %teachers ) {
	$sth->execute($userid);
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname) = $sth->fetchrow;
	if (not $lastname ) { # skip
	    $noname{$userid} = 1;
	    next;
	}
	
	$sort{"$lastname$firstname$userid"} = $userid;
	$teachername{$userid} = "$lastname, $firstname ($userid)";
    }

    
    # Start Form
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="1">\n};

    print qq{<div style="padding:0.4em;">$lex{Staff} };
    print qq{ <select name="staff"><option value=""></option>\n};
    foreach my $key ( sort keys %sort ) {
	my $userid = $sort{$key};
	my $name = $teachername{$userid};
	print qq{<option value="$userid">$name</option>\n}; 
    }
    print qq{</select></div>\n};

    if ( %noname ) {
	my $nameless = join(',',keys %noname);
	print qq{<div style="font-weight:bold;">No Names for teacher userid };
	print qq{<span style="color:red;">$nameless</span> from course masters. Please reset</div>\n};
    }

    
=head
    print qq{<div style="padding:0.4em;">$lex{Term} };
    print qq{<select name="term"><option value=""></option>\n};
    foreach my $trm (@terms){
	print qq{<option>$trm</option>\n};
    }
    print qq{</select></div>\n};


    print qq{<p>A <b>term</b> is a period of time with tests at the end.</p>\n};

    print qq{<p style="width:40%;">The terms are the
    periods of time these entries in a timetable are valid. In a K-6
    school with 3 terms for the year, the answer is all 3 terms. In a
    high school with 2 semesters and 2 terms in each semester, the
    first semester timetable entries would be for term 1 and 2 while
    the second semester would be term 3 and 4.</p>\n};
=cut
    
    print qq{<p><input type="submit" value="$lex{Continue}"></p>};
    print qq{</form>\n};

    print qq{</body></html>\n};

    exit;

} # end of showStartPage



#---------------
sub setTimetable {
#---------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    # Passed: staff userid

    # check for required teacher
    if ( not $arr{staff}  ) {
	print qq{<h3>$lex{Staff} - $lex{'Not Found'}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # Check for DaysPerCycle value
    if ( not $g_DaysPerCycle ) {
	print qq{<h3>g_DaysPerCycle $lex{'Not Found'}</h3>\n};
	print qq{<h3 style="color:red;">$lex{Update} $lex{Configuration}</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    
    
    # Get Name
    my $userid = $arr{staff};
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth->execute( $userid );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname ) = $sth->fetchrow;

    
    # Find Courses from Course Master for this teacher and put into hash for selection. 
    $sth = $dbh->prepare("select * from subject where ( teacher = ? or teacher2 = ?)
			 and teacher is not NULL and teacher != '';");
    $sth->execute( $userid, $userid );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    my (%allcourses, %termcourse); # termcourse{term}{subjsec} = 1; %currcourses not needed
    # We now use start/end term values to loop over all terms.
    my $startterm = 1;
    my $endterm;
    # currcourses used for course selections in the current term.
    # allcourses used to check for errors where courses are set in wrong term.
    while ( my $ref = $sth->fetchrow_hashref ){
	my %r = %$ref;

	# Populate termcourse hash.
	foreach my $trm ( $r{startrptperiod}.. $r{endrptperiod} ) {
	    $termcourse{ $trm }{ $r{subjsec} } = $r{description};
	}


	if ( $r{endrptperiod} > $endterm ) { $endterm = $r{endrptperiod}; }
	
	$allcourses{ $r{subjsec} } = { start => $r{startrptperiod},
				       end => $r{endrptperiod},
				       desc => $r{description} };

	# skip if not current term for currcourses.
	#if ( $arr{term} < $r{startrptperiod} or $arr{term} > $r{endrptperiod} ) {
	#    next;
	#}
	
	# use truncated longer description if no small description.
	#if (not $r{smdesc} ){ $r{smdesc} = substr($r{description},0,8);} 
	#$currcourses{$r{subjsec}} = "$r{smdesc} ($r{subjsec}) T$r{startrptperiod}-$r{endrptperiod}";
    }

#    foreach my $term ( sort keys %termcourse ) {
#	print qq{Term $term<br>\n};
#	foreach my $subjsec ( sort keys %{ $termcourse{$term}} ) {
#	    print qq{$subjsec };
#	}
#	print qq{<br>\n};
#    }

    
    # Find maximum number of periods for table from schedat; We are editing so OK.
    $sth = $dbh->prepare("select max(period) from schedat");
    $sth->execute;
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my $maxPPD = $sth->fetchrow; # these are course periods, not necessarily attendance periods

    

    # Check this teacher/userid for any errors in current records.
    # Go through all the teachers courses and check if we have a record in schedat.
    # If so, then make sure it is in a term of the course, not outside.
    my $sth = $dbh->prepare("select * from schedat where subjsec = ?");
    my $first = 1;
    foreach my $subjsec ( keys %allcourses ) {
	$sth->execute($subjsec);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	while  ( my $tref = $sth->fetchrow_hashref ) {
	    my %t = %$tref; # %t is timetable record.
	    if ( $t{term} > $allcourses{$subjsec}{end} or
		 $t{term} < $allcourses{$subjsec}{start} ) {

		if ($first ) { # start form and set for page 3 delete.
		    print qq{<form action="$self" method="post" style="display:inline;">\n};
		    print qq{<input type="hidden" name="page" value="5">\n};
		    print qq{<input type="hidden" name="userid" value="$userid">\n};
		    # print qq{<input type="hidden" name="currterm" value="$arr{term}">\n};
		    print qq{<input type="submit" value="Delete Error Records">\n};
		    $first = 0;
		}

		print qq{<div>Delete? <input type="checkbox" name="$t{id}" value="1" checked>};
		print qq{Error: $allcourses{$subjsec}{desc}  ($subjsec) / Term $t{term} / };
		print qq{Day $t{day} / Period $t{period}</div>\n};
	    } # error record
	} # records loop
    } # courses loop
    
    if ( not $first ) { # we have errors
	print qq{<div><input type="submit" value="Delete Error Records"></div>\n};
	print qq{</form></body></html>\n};
	exit;
    }


    # Print Form Start
    print qq{<form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="userid" value="$userid">\n};
#    print qq{<input type="hidden" name="currterm" value="$arr{term}">\n};

    # print top section above table: Name
    print qq{<h3>$firstname $lastname</h3>\n}; # - $lex{Term} $arr{term}</h3>\n};

    print qq{<div><input type="submit" value="$lex{Update}"></div>\n};

    foreach my $term ( sort keys %termcourse ) {

	my %currcourses = %{ $termcourse{$term}};

#	print qq{Term $term<br>\n};
#	foreach my $subjsec ( sort keys %currcourses ) {
#	    print qq{$subjsec };
#	}
#	print qq{<br>\n};

	
	# Start Table
	print qq{<table cellpadding="3" cellspacing="0" border="1" };
	print qq{style="float:left;margin:0.5em;">\n};
	print qq{<caption style="font-weight:bold;font-size:120%;">Term $term</caption>\n};

	
	# Check for Course Entries outside of start/end term in subject(course) table for this teacher.
        
	my $days = $g_DaysPerCycle; # One for each Day.
	if ( $days eq 'w' or $days eq 'W' ) { $days = 5; } # weekly schedule.

	# Check for errors outside of the days per cycle.
	# Find maximum number of periods for table from schedat;
	$sth = $dbh->prepare("select max(day) from schedat");
	$sth->execute;
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $maxDays = $sth->fetchrow;
	if ( $maxDays > $days ) { # defined just above
	    print qq{<tr style="color:red;font-weight:bold;"><td colspan="3">};
	    print qq{Error: Day Value Outside of Defined Days: $maxDays</td>\n};
	    # Find the Errant Records
	    my $sth = $dbh->prepare("select * from schedat where day = ?");
	    $sth->execute( $maxDays );
	    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	    while ( my $ref = $sth->fetchrow_hashref ) {
		my %r = %$ref;
		print qq{<td>Day:$r{day} Period:$r{period} Course:$r{subjsec} Term:$r{term}</td>\n};
	    }
	    print qq{</tr>\n\n};
	    $days = $maxDays;
	}
    
        # print qq{Days:$days - $g_DaysPerCycle<br>\n};

	# Print Header
	print qq{<tr><th></th>};
	for my $d ( 1 .. $days ) { print qq{<th>$lex{Day} $d</th>}; }
	print qq{</tr>\n\n};

	for my $per ( 1..$maxPPD ){
	    print qq{<tr>};
	    for $d (0..$days){
		if ($d == 0){ 
		    print qq{<td style="width:6ch;"><b>$lex{Per} $per</b></td>};
		} else {
		    print qq{<td>};
		    my $id = "$per:$d";
		    prSelections($id, $term, \%currcourses );
		    print qq{</td>\n};
		}
	    }
	    print qq{</tr>\n\n};
	}

	my $span = $days + 1;
	print qq{</table>};
	

    } # next term
    
    print qq{<br clear="left"><p><input type="submit" value="$lex{Update}"></p>\n};
    
    print qq{</form></body></html>\n};

    exit;


} # end of setTimetable




#---------------
sub prSelections {  # print selection list for course array
#---------------

    my ($pid, $term, $ref ) = @_;

    my %courses = %$ref;
    my ($period,$day) = split(':', $pid );
    my $found;

#    print "PR Selections:<br>\n";
#    print qq{Courses:}, %courses,"<br>\n";
#    print qq{Period:$period Day:$day<br>\n};
    
    my %sort;
    foreach my $subjsec (keys %courses ) {  # $courses{subjsec} = desc;
	$sort{"$courses{$subjsec}$subjsec"} = $subjsec;
    }
        
    # find existing records for this period... (may be backings)
    $sth = $dbh->prepare("select id, subjsec from schedat 
			 where day = ? and period = ? and term = ?");
    $sth->execute($day,$period,$term);
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my ($id, $subjsec) = $sth->fetchrow ) {
	if ( $courses{$subjsec} ) { # this is a course that teacher teaches..
	    $found = 1;
	    print qq{<select name="$pid:$id:$term">\n};
	    my $currsubjsec = $subjsec;
	    print qq{<option value="$currsubjsec">$courses{$subjsec} ($currsubjsec)</option>\n};
	    foreach my $key ( sort keys %sort ){
		my $subjsec = $sort{$key};
		if ($subjsec eq $currsubjsec ) { next; } # skip repeat of course if current
		print qq{<option value="$subjsec">$courses{$subjsec} ($subjsec)</option>\n};
	    }
	    print qq{<option value=""></option></select>\n\n};
	}
    }

    
    if ( not $found ) { # no courses found... (no teacher courses in this period)
	print qq{<select name="$pid:-1:$term"><option value=""></option>\n};
	foreach my $key ( sort keys %sort ){
	    my $subjsec = $sort{$key};
	    print qq{<option value="$subjsec">$courses{$subjsec} ($subjsec)</option>};
	}
	print qq{</select>\n\n};
    }

}


#----------------
sub updateRecords { # update the records in schedat table.
#----------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

    my $userid =  $arr{userid};
    delete $arr{userid};

    # Check passed values
    # foreach my $key (sort keys %arr) { print qq{K:$key V:$arr{$key}<br>\n}; }

    # Setup for finding grade(s) of each subject (if any).
    my $sth = $dbh->prepare("select grade from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select subjsec from schedat where id = ?");
    my $sth2 = $dbh->prepare("select description from subject where subjsec = ?");

    foreach my $key ( sort keys %arr ) {

	my ( $period, $day, $id, $term ) = split(':', $key);
	my  $subjsec = $arr{$key};

	my $origsubjsec;
	if ( $id != -1 ) { # id exists
	    $sth1->execute($id);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    $origsubjsec = $sth1->fetchrow;
	}

	# print qq{ Subj:$subjsec Orig:$origsubjsec Day:$day Period:$period };
	# print qq{Id:$id Currtrm:$currterm<br>\n};

	if ( $id == -1 and $subjsec ) { # Add record since no id, but subjsec exists

	    $sth2->execute($subjsec);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $desc = $sth2->fetchrow;

	    print qq{<b>$lex{Record} $lex{Add}- $desc ($subjsec)</b> };
	    print qq{$lex{Term} $term\n};
	    print qq{$lex{Day} $day\n};
	    print qq{$lex{Period} $period<br>\n};

	    my $sth2 = $dbh->prepare("insert into schedat ( day,period,subjsec,term )
              values (?,?,?,?)");
	    $sth2->execute($day, $period, $subjsec, $term);
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	    
	} elsif ( $id != -1 and not $subjsec ) {  # Delete since id exists but no subject 

	    $sth2->execute($origsubjsec);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $desc = $sth2->fetchrow;
	    
	    print qq{<b>$lex{Record} $lex{Delete}- $desc ($origsubjsec)</b> };
	    print qq{$lex{Term} $term\n};
	    print qq{$lex{Day} $day\n};
	    print qq{$lex{Period} $period<br>\n};

	    my $sth2 = $dbh->prepare("delete from schedat where id = ?");
	    $sth2->execute( $id );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	} elsif ( $id != -1 and $subjsec and $origsubjsec ne $subjsec ) { # changed record, update

	    $sth2->execute($subjsec);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $desc = $sth2->fetchrow;
	    
	    print qq{<b>$lex{Record} $lex{Update}- $desc ($subjsec)</b> };
	    print qq{$lex{Term} $term \n};
	    print qq{$lex{Day} $day \n};
	    print qq{$lex{Period} $period<br>\n};

	    my $sth2 = $dbh->prepare("update schedat set subjsec = ? where id = ? ");
	    $sth2->execute( $subjsec, $id );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	}

    } # End of keys loop.

    print qq{<p>A <b>backing</b> is where more than one course is taught in the same };
    print qq{period, day, term by the same teacher.</p>\n};

    print qq{[ <form action="$self" method="post" style="display:inline;">\n};
    print qq{<input type="hidden" name="page" value="3">\n};
    print qq{<input type="hidden" name="userid" value="$userid">\n};
    
    print qq{<input type="submit" value="$lex{Add} $lex{Backings}">\n};
    print qq{</form>\n};

    print qq{ | <a href="$self">Edit Timetable</a>\n};
    
    print qq{ | <a href="$schpage">$lex{Timetable}</a> ] \n};
    print qq{</body></html>\n};

} # end of updateRecords



#--------------------
sub printBackingsForm {
#--------------------

    #print qq{<div>printBackingsForm</div>\n};
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    
    my $userid = $arr{userid};
    delete $arr{userid};
    
    
    # Get Teacher Name
    my $sth = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    $sth->execute($userid);
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    my ($lastname, $firstname) = $sth->fetchrow;

    
    # Load Courses for teacher.
    my $sth1 = $dbh->prepare("select count(distinct studnum) from eval where subjcode = ?");
    my %courses;
    
    my $sth = $dbh->prepare("select * from subject where teacher = ?");
    $sth->execute( $userid );
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
    while ( my $ref = $sth->fetchrow_hashref ){
	my %r = %$ref;

	$sth1->execute( $r{subjsec} );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my $ecount = $sth1->fetchrow;

	# use truncated longer description if no small description. 
	if (not $r{smdesc} ){ $r{smdesc} = substr($r{description},0,8);}

	$courses{ $r{subjsec} } = qq{$r{smdesc} ($r{subjsec}) Trm:$r{startrptperiod}-$r{endrptperiod} }.
	  qq{Enrolled:$ecount};
    }


    print qq{<h3>$firstname $lastname</h3>\n};

    print qq{<form action="$self" method="post" style="padding:1em;">\n};
    print qq{<input type="hidden" name="page" value="4">\n};

    print qq{<input type="submit" value="$lex{Add} $lex{Backings}">\n};
    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>Course</th><th>$lex{Term}</th><th>$lex{Day}</th>};
    print qq{<th>$lex{Period}</th></tr>\n};

    for my $rec (1..$maxbackings){
	print qq{<tr><td><select name="$rec"><option value=""></option>\n};
	foreach my $subjsec (sort keys %courses ) {
	    print qq{<option value="$subjsec">$courses{$subjsec}</option>};
	}
	print qq{</select></td>\n};
	print qq{<td><input type="text" name="t$rec" style="width:4ch;"></td>\n};
	print qq{<td><input type="text" name="d$rec" style="width:4ch;"></td>\n};
	print qq{<td><input type="text" name="p$rec" style="width:4ch;"></td>\n};
	print qq{</tr>\n};
    }
    
    print qq{</table>};
    print qq{<input type="submit" value="$lex{Add} $lex{Backings}">\n};
    print qq{</form></body></html>\n};

}


#--------------
sub addBackings {
#--------------

    # print qq{<div>addBackings</div>\n};
    # foreach my $key ( sort {$a <=> $b} keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

     
    print qq{<h1>$lex{Add} $lex{Backings}</h1>\n};


    my $sth = $dbh->prepare("select description from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select count(*) from schedat where day = ? and 
			     period = ? and subjsec = ? and term = ?");
    my $sth2 = $dbh->prepare("insert into schedat ( day, period, subjsec, term ) values (?,?,?,?)");

    foreach my $key (sort keys %arr ) {

	if ( $key =~ m/^(\d)/ and $arr{$key} ) { # no leading d/p/t and has a value.

	    #print qq{K:$key V:$arr{$key}<br>\n};

	    my $di = "d$1"; 
	    my $pi = "p$1";
	    my $ti = "t$1";

	    if ( not $arr{$di} or not $arr{$pi} or not $arr{$ti} ) {
		print qq{$lex{Missing} $lex{Period}/$lex{Day}/$lex{Term}<br>\n};
		next;
	    }

	    my $subjsec  = $arr{$key};

	    # Get Course Description
	    $sth->execute($subjsec);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $description = $sth->fetchrow;

	    # Check for existing values
	    $sth1->execute($arr{$di}, $arr{$pi}, $subjsec, $arr{$ti});
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $count = $sth1->fetchrow;

	    if ( $count ) { # record exists
		print qq{<div><b>$lex{'Record Exists'}!</b> $lex{Day}:$arr{$di} $lex{Per}:$arr{$pi} };
		print qq{$lex{Course}:$subjsec $lex{Term}:$arr{$ti}};
		print qq{ <b>$lex{Skipping}</div>\n};

	    } else { # insert the record
		print qq{<div style="font-weight:bold;font-size:110%;">};
		print qq{$lex{'Adding'} $description ($subjsec) - };
		print qq{$lex{Day} $arr{$di} / $lex{Period} $arr{$pi} / $lex{Term} $arr{$ti}</div>\n};
		
		$sth2->execute($arr{$di}, $arr{$pi}, $subjsec, $arr{$ti});
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    }

	} # End of IF 

    } # End of foreach key loop

    print qq{<p>[ <a href="$self">Edit Timetable</a> | \n};
    print qq{<a href="$schpage">$lex{Timetable}</a> ]</p>\n};
    print qq{</body></html>\n};

} # End of addBackings
