#!/usr/bin/perl
#  Copyright 2001-2022 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.

#  Description: Grade based subject enrollment. List all the students
#   for all the subjects in that grade. Deselect those that you don't
#   have in those subjects.

my %lex = ('Main' => 'Main',
	   'Report Card' => 'Report Card',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Continue' => 'Continue',
	   'Show Withdrawn Students' => 'Show Withdrawn Students',
	   'Course Enrollments' => 'Course Enrollments',
	   'Add' => 'Add',
	   'Checked' => 'Checked',
	   'Blank=All' => 'Blank=All',
	   'Separate with Spaces' => 'Separate with Spaces',
	   'Starts with' => 'Starts with',
	   'Terms' => 'Terms',
	   'Start' => 'Start',
	   'End' => 'End',
	   'Student' => 'Student',
	   'Selection' => 'Selection',
	   'Grades' => 'Grades',
	   'Starts with' => 'Starts with',
	   'Courses' => 'Courses',
	   'Students' => 'Students',
	   'Record(s) Stored' => 'Record(s) Stored',
	   'Record Exists' => 'Record Exists',
	   'Contact' => 'Contact',
	   'Error' => 'Error',
	   'Checked' => 'Checked',
	   'Term' => 'Term',
	   'Not Found' => 'Not Found',
	   'Skip' => 'Skip',
	   'and' => 'and',
	   'Or' => 'Or',
	   'Name' => 'Name',
	   'Student Number' => 'Student Number',
	   'Next Page' => 'Next Page',
	   'Sort by' => 'Sort by',
	   'Mdl' => 'Mdl',
	   'Save' => 'Save',
	   'Course' => 'Course',

	   );

my $self = 'enroladdall.pl';

use DBI;
use CGI;

eval require "../../etc/admin.conf.root";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

my $dbtype = 'mysql';
my $dsn = "DBI:$dbtype:dbname=$dbase";
my $dbh = DBI->connect($dsn,$user,$password);
$dbh->{mysql_enable_utf8} = 1;

# Load Configuration Variables;
my $sth = $dbh->prepare("select id, datavalue from conf_system where filename = 'admin'");
$sth->execute;
if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
while (	my ($id, $datavalue) = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}

# Load subjects to skip for moodle table.
my $sth = $dbh->prepare("select id, datavalue from conf_system 
  where dataname = ?");
foreach my $val ( 'r_SupressSubject','r_AdditionalComments' ) {
    $sth->execute( $val );
    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
    while (	my ($id, $datavalue) = $sth->fetchrow ) {
	eval $datavalue;
	if ( $@ ) {
	    print "$lex{Error}: $@<br>\n";
	    die "$lex{Error}: $@\n";
	}
    }
}

my $q = new CGI;
print $q->header( -charset, $charset ); 
my %arr = $q->Vars;

my $grade = $arr{grade};
my $checked = $arr{checked};


# Print Page Header
my $title = "$lex{Add} $lex{'Course Enrollments'}";
print qq{$doctype\n<html><head><title>$title</title>\n};
print qq{<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{$chartype\n</head><body style="margin:1em;">\n};

print qq{[ <a href="$homepage">$lex{Main}</a> |\n};
print qq{<a href="$reppage">$lex{'Report Card'}</a> ]\n};

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

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

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

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

} elsif ( $arr{page} == 3 ) {
    delete $arr{page};
    writeRecords();
}


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

    my @homerooms;
    my $sth = $dbh->prepare("select distinct homeroom from student 
			    where homeroom is not NULL and homeroom != ''");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $hr  = $sth->fetchrow ) {
	push @homerooms, $hr;
    }
    @homerooms = sort {$a <=> $b} @homerooms;

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

    print qq{<table border="0" cellpadding="7" cellspacing="0" };
    print qq{style="border:1px solid gray; margin-bottom:1em;">\n};
    print qq{<tr><th colspan="2" style="font-size:120%;">$lex{Student} $lex{Selection}</th></tr>\n};

    print qq{<tr><td class="la" colspan="2" style="border-bottom:1px solid gray;">\n};
    print qq{<div style="font-size:110%;font-weight:bold;">};
    print qq{Select Students with one of the following methods</div>\n};

    # Homeroom
    print qq{<ul><li style="margin:0.5em 0;">$lex{Homeroom} };
    print qq{<select name="homeroom"><option value=""></option>\n};
    foreach my $hr ( @homerooms ) { print qq{<option>$hr</option>} }
    print qq{</select></li>\n};
    
    # Grade
    print qq{<li style="margin:0.5em 0;">$lex{Grades} };
    print qq{<input type="text" name="grades" style="width:20ch;">\n};
    print qq{$lex{'Separate with Spaces'}</li>};
    
    # Student Number
    print qq{<li style="margin:0.5em 0;">Local Student Number };
    print qq{<input type="text" name="studnum" style="width:6ch;"></li>\n};
    print qq{</ul>\n};

    print qq{</td></tr>\n\n};
    
    
    print qq{<tr><td class="bla" colspan="2">};
    print qq{$lex{'Next Page'} $lex{Checked}? };
    print qq{<input type="checkbox" name="studcheck" value="CHECKED" checked="checked"></td></tr>\n};

    print qq{<tr><td class="bla" colspan="2">$lex{'Show Withdrawn Students'}\n};
    print qq{ <input type="checkbox" name="showwithdrawn" value="1">};
    print qq{</td></tr>\n};

    print qq{</table>\n};

    

    # Now Course Selection.
    print qq{<table border="0" cellpadding="7" cellspacing="0" };
    print qq{style="border:1px solid gray;margin-bottom:1em;">\n};
    print qq{<tr><th colspan="2" style="font-size:120%;">$lex{Course} $lex{Selection}</th></tr>\n};


    # Search for Courses by Grade
    print qq{<tr><td class="la" colspan="2">};
    print qq{<div style="font-size:110%;font-weight:bold;">};
    print qq{Select Courses with one of the following methods</div>\n};
    
    print qq{<ul><li style="margin:0.5em 0;">$lex{Grades} };
    print qq{<input type="text" name="grade" style="width:12ch;"> };
    print qq{Separate multiple grades with Spaces</li>\n};

    # Search by Course Name (Description)
    print qq{<li style="margin:0.5em 0;">Course Name $lex{'Starts with'}};
    print qq{ <input type="text" name="subjname" style="width:16ch;"></li>\n};
    
    # Search for Courses by Term
    print qq{<li style="margin:0.5em 0;">Start-End $lex{Terms}\n};
    print qq{<input type="text" name="term" style="width:12ch;"> 3-4 6-8\n};
    print qq{$lex{'Separate with Spaces'}</li>\n};

    print qq{</ul>\n};

    # Section Filter
    print qq{<div style="width:40em;"><b>Filter by Section</b> \n};
    print qq{<input type="text" name="section" style="width:10ch;"><br>\n};
    print qq{<i>Normally blank</i>. Only show courses with these sections };
    print qq{from grades above. <i>Separate multiple sections with Spaces</i></div>\n};
    
    # Next Page Checked for Courses.
    print qq{<p><b>$lex{'Next Page'} $lex{Checked}?</b>\n}; 
    print qq{<input type="checkbox" name="subjcheck" value="CHECKED" checked="checked"></p>\n};
    
    print qq{</td></tr></table>\n};

    print qq{<p><input type="submit" value="$lex{Continue}"></p>\n};
    
    print qq{</form></body></html>\n};

    exit;

}



#-----------------
sub selectGroups { # select groups of students and subjects to enrol.
#-----------------

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

    my %sortedstudents;

    my $table = 'student'; # overridden to studentall if show withdrawn selected.
    if ( $arr{showwithdrawn} ) { # change to both student tables.
	$table = 'studentall';
    }
    
    my $studcheck = $arr{studcheck};
    my $subjcheck = $arr{subjcheck};

    my (@students, %students);


    if ( $arr{grades} ) {
	my $sth = $dbh->prepare("select lastname, firstname, studnum, grade from $table
          where grade = ? order by lastname, firstname");

	my @grades = split(/\s+/, $arr{grades});
	
	foreach my $grade ( @grades ) {
	    $sth->execute( $grade );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    while ( my ( $lastname, $firstname, $studnum, $grade ) = $sth->fetchrow ) {
		push @students, $studnum;
		$students{$studnum} = "$lastname, $firstname ($grade)";
	    }
	}

    } elsif ( $arr{homeroom} ) {
	my $sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom from $table
          where homeroom = ? order by grade, lastname, firstname");
	$sth->execute( $arr{homeroom} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ( $lastname, $firstname, $studnum, $grade, $homeroom ) = $sth->fetchrow ) {
	    push @students, $studnum;
	    $students{$studnum} = "$lastname, $firstname ($grade $homeroom)";
	}

    } elsif ( $arr{studnum} ) {
	
	my $sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom from $table
          where studnum = ?");
	$sth->execute( $arr{studnum} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ( $lastname, $firstname, $studnum, $grade, $homeroom ) = $sth->fetchrow ) {
	    push @students, $studnum;
	    $students{$studnum} = "$lastname, $firstname ($grade $homeroom)";
	}
	
    } else {
	print qq{<h3>No Students Selected</h3>\n};
	print qq{</body></html>\n};
	exit;
    }

    
    # All students now in @students and %students;
    # print "Students", @students, "<br>\n";

    

    # Now do Course Selection.
    my ( @subjects_name, %subjects_name);

    # Search by description if any...
    if ( $arr{subjname} ) { 

	# Find all subjects with this name.
	my $sth = $dbh->prepare("select description, subjsec from subject 
             where description like ? order by description");
	
	$desc = $arr{subjname}. '%';
	$sth->execute( $desc );
	if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }

	while ( my ( $description, $subjsec ) = $sth->fetchrow ) {
	    my ($code, $section) = split('-', $subjsec);
	    if ( $arr{section} and $arr{section} ne $section ) { next; }
	    $description =~ s/://g; # strip any colons
	    push @subjects_name, $subjsec;
	    $subjects_name{$subjsec} = $description;
	}
	
    }


    # Search by grades, if any.
    my ( @subjects_grade, %subjects_grade);

    if ( $arr{grade} ) { 
	my @grades = split /\s+/, $arr{grade};
	
	# load sections, if any.
	my @sections;
	if  ( $arr{section} ) { 
	    @sections = split /\s+/, $arr{section};
	}

#	print "Grades:@grades  Sections:@sections<br>\n";

	
	my %sort;
	foreach my $gr (sort  @grades ) {
	    # Find all courses in this grade...
	    my $sth;
	    if ( $arr{section} ) {
		foreach my $section ( @sections ) {
		    $sth = $dbh->prepare("select description, subjsec from subject 
					 where grade = ? and section = ? order by description");
		    $sth->execute( $gr, $section );
		    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		    
		    while ( my ( $description, $subjsec ) = $sth->fetchrow ) {
			$description =~ s/://g; # strip any colons
		        $sort{"$description$subjsec"} = $subjsec;
			$subjects_grade{$subjsec} = $description;
		    }
		}
		    
	    } else { # no section selector
		$sth = $dbh->prepare("select description, subjsec from subject 
				     where grade = ? order by description");
		$sth->execute( $gr );
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		
		while ( my ( $description, $subjsec ) = $sth->fetchrow ) {
		    $description =~ s/://g; # strip any colons
		    $sort{"$description$subjsec"} = $subjsec;
		    $subjects_grade{$subjsec} = $description;
		}
		
	    }

	    # populate @subjects_grade array for ordering of courses
	    foreach my $key ( sort keys %sort ) {
		push @subjects_grade, $sort{$key};
	    }

#	    print "Subjects Grade: @subjsects_grade<br>", %sort, "<br>\n";
	    
	    
	} # end of grade loop
    } # end of if grade


    # Find all subjects for these terms
    my ( @subjects_term, %subjects_term);
    
    if ( $arr{term} ) {

	my $sth = $dbh->prepare("select description, subjsec from subject 
         where startrptperiod = ? and endrptperiod = ? order by description");
	
	if ( $arr{section} ) {
	    $sth = $dbh->prepare("select description, subjsec from subject 
				 where startrptperiod = ? and endrptperiod = ? and 
				 section = '$arr{section}' order by description");
	}

	
	my @termgroups = split(/\s+/, $arr{term});
	foreach my $val ( @termgroups ) {
	    my ( $start, $end ) = split '-', $val;
	    $sth->execute( $start, $end );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    
	    while ( my ( $description, $subjsec ) = $sth->fetchrow ) {
		$description =~ s/://g; # strip any colons
		push @subjects_term, $subjsec;
		$subjects_term{$subjsec} = $description;
	    }
	}
    }
    
    # Now should have @subjects and %subjects populated.
    # print "Subjects:",  @subjects_term, "<br>\n";


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

    # Get Checkbox state (for next page for select particular subject-student enrol).
    print qq{<p class="la"><span style="border:1px solid gray;margin:1em 2em;padding:1em;">};
    print qq{$lex{'Next Page'} $lex{Checked}?\n};
    print qq{ <input type="checkbox" name="checked" value="CHECKED" checked="checked"></span></p>\n};


    # Print Student Information.
    print qq{<table cellpadding="3" cellspacing="0" border="1" };
    print qq{style="float:left;margin:1em;">\n};

    print qq{<tr><td class="cn">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};

    my $class = 'blue';
    
    foreach my $studnum ( @students ){  #loop through students

	# Manage Class value.
	if ( not $arr{sortbyname}  ) {
	    my ($dud, $grp) = split(/\(/, $students{$studnum});
	    chop $grp; # remove trailing parens.
	    $oldgrp = $currgrp;
	    $currgrp = $grp;
	    if ( $currgrp ne $oldgrp ) { # switch colors;
		if ( $class eq 'blue' ) { $class = 'gray'; } else { $class = 'blue'; }
	    }
	}

	print qq{<tr class="$class"><td>};
	print qq{<input type="checkbox" name="$students{$studnum}:ST:$studnum" };
	print qq{value="1" $studcheck>\n};
	print qq{ $students{$studnum}</td></tr>\n};

    }

    print qq{<tr><td class="cn">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table>\n};


    # Print Course Information, now
    print qq{<table cellpadding="3" cellspacing="0" border="1" };
    print qq{style="float:left;margin:1em;">\n};

    print qq{<tr><td class="cn">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};

    $sth1 = $dbh->prepare("select lastname,firstname from staff where userid = ?");

    
    $sth = $dbh->prepare("select startrptperiod, endrptperiod, teacher from subject 
      where subjsec = ?");

    if ( @subjects_name ) {
	print qq{<tr><th>$lex{Name} $arr{subjname}</th></tr>\n};
	foreach my $subjsec ( @subjects_name ){  # loop through subjects by Name

	    $sth->execute( $subjsec );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $startterm, $endterm, $teacher ) = $sth->fetchrow;

	    $sth1->execute( $teacher );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname ) = $sth1->fetchrow;
	
	    print qq{<tr class="gray"><td>};
	    print qq{<input type="checkbox" name="$subjects_name{$subjsec}:SU:$subjsec" };
	    print qq{value="1" $subjcheck>\n};
	    print qq{ $subjects_name{$subjsec} ($subjsec) $firstname $lastname ($teacher) - $lex{Terms} $startterm\-$endterm</td></tr>\n};
	}
    }

    if ( @subjects_grade ) {
	print qq{<tr><th>$lex{Grades} $arr{grade}</th></tr>\n};
	foreach my $subjsec ( @subjects_grade ){  # loop through subjects by Name

	    $sth->execute( $subjsec );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $startterm, $endterm, $teacher ) = $sth->fetchrow;

	    $sth1->execute( $teacher );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname ) = $sth1->fetchrow;

	    
	    print qq{<tr class="gray"><td>};
	    print qq{<input type="checkbox" name="$subjects_grade{$subjsec}:SU:$subjsec" };
	    print qq{value="1" $subjcheck>\n};
	    print qq{ $subjects_grade{$subjsec} ($subjsec) $firstname $lastname ($teacher) $lex{Terms} };
	    print qq{ $startterm\-$endterm</td></tr>\n};
	}
    }


    if ( @subjects_term ) {
	print qq{<tr><th>$lex{Terms} $arr{term}</th></tr>\n};
	foreach my $subjsec ( @subjects_term ){  # loop through subjects by Name

	    $sth->execute( $subjsec );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $startterm, $endterm, $teacher ) = $sth->fetchrow;

	    $sth1->execute( $teacher );
	    if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname ) = $sth1->fetchrow;

	    print qq{<tr class="gray"><td>};
	    print qq{<input type="checkbox" name="$subjects_term{$subjsec}:SU:$subjsec" };
	    print qq{value="1" $subjcheck>\n};
	    print qq{ $subjects_term{$subjsec} ($subjsec) $firstname $lastname ($teacher) $lex{Terms} };
	    print qq{ $startterm\-$endterm</td></tr>\n};
	}
    }


    print qq{<tr><td class="cn">};
    print qq{<input type="submit" value="$lex{Continue}"></td></tr>\n};
    print qq{</table></form></body></html>\n};

    exit;

}




#-----------------
sub selectSubjStud {
#-----------------

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

    # select Student-Subject enrollments - one student in one subject;
    my $checked = $arr{checked};
    delete $arr{checked};


    foreach my $key ( sort keys %arr) {
	my ($dud, $sigil, $value ) = split /:/, $key;
	if ( $sigil eq 'ST' ) {
	    push @students, $value; 
	} elsif ( $sigil eq 'SU' ) { 
	    push @subjects, $value; 
	} else { # problems!
	    print $lex{Error}. " $key<br>\n";
	}

    }

    # Find subject descriptions / student name
    my $sth = $dbh->prepare("select description from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");


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

    print qq{<div style="text-align:left;">\n};
    print qq{<input type="submit" value="$lex{Save}"></div>\n};

    foreach my $subjsec ( @subjects ) {

	# Get Subject Description
	$sth->execute( $subjsec );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $description = $sth->fetchrow;
	
	# Print Table Heading
	print qq{<table cellpadding="3" cellspacing="0" border="1" };
	print qq{style="float:left;margin:1em;">\n};
	print qq{<tr><th>$description ($subjsec)</th></tr>\n};

	foreach my $studnum ( @students ) {

	    # Get Student Name
	    $sth1->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ( $lastname, $firstname ) = $sth1->fetchrow;

	    # print a current table row
	    print qq{<tr><td>};
	    print qq{<input type="checkbox" name="$subjsec:$studnum" value="1" $checked>\n};
	    print qq{<b>$lastname,</b> $firstname</td>\n};

	}

	print qq{</table>\n};

    }

    print qq{<br clear="left">\n};
    print qq{<div style="text-align:left;"><input type="submit" value="$lex{Save}"></div>\n};

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

    exit;


} # end of selectSubjects



#---------------
sub writeRecords {
#---------------
    
    #foreach my $key (keys %arr) { print "K:$key V:$arr{$key}<br>\n"; }

    print qq{</h1>\n<table cellpadding="3" cellspacing="0" border="1">\n};
    print qq{<tr><th>$lex{Students}</th><th>$lex{Courses}</th>};
    print qq{<th>$lex{Terms}</th></tr>\n};

    my $sth = $dbh->prepare("select description, startrptperiod, endrptperiod 
     from subject where subjsec = ?");
    my $sth1 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    foreach my $key ( sort keys %arr ) {  # $key contains studnum:subjsec 

	my ( $subjsec, $studnum ) = split(/:/,$key);
       
	# Read the subject information
	$sth->execute( $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my ( $description, $startterm, $endterm ) = $sth->fetchrow;

	# Get Student Name
	$sth1->execute( $studnum );
	if ( $DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname ) = $sth1->fetchrow;
	if ( not $lastname ) { 
	    $lastname = qq{<span style="color:red;">$lex{'Not Found'}</span>}; 
	}

	# Check for the existence of the same record(s),
	# one for each term for each student in each subject.
	my ( $term, %terms );

	$sth2 = $dbh->prepare("select term from eval
          where subjcode = ? and studnum = ? order by term");
	$sth2->execute( $subjsec, $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr;}


	# Put existing term records in the 'terms' hash; check for dups.
	while ( my $term = $sth2->fetchrow ) {
	    if ( $terms{$term} ) {
		print "$lex{'Record Exists'} $lex{Term}: $term ". 
		print " $description ($subjsec) - $lastname, $firstname ($studnum).<br>\n";
		# miss steak? next;
	    } else { # add to hash.
		$terms{$term} = 1;
	    }
	}

	# print line for this record.
	print "<tr><td><b>$lastname</b>, $firstname ($studnum)</td>";
	print "<td>$description ($subjsec)</td>\n<td> ";


	# Loop through and check where term is missing...
	for ( my $i = $startterm; $i <=$endterm; $i++ ) {
	    if ( not $terms{$i} ){ # fill in holes!
		$sth3 = $dbh->prepare("insert into eval ( subjcode, studnum, term )
                  values ( ?, ?, ? )");
		$sth3->execute( $subjsec, $studnum, $i ); # $i is the term
		if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
		print " $i ";
	    } else { 
		print '('. $lex{Skip}. " $i) ";
	    }
	} # end of Terms Loop

	# Check and Insert into external table for Moodle (ext_moodle table)
	my $sth4 = $dbh->prepare("select count(*) from ext_moodle 
          where studnum = ? and subjsec = ?");
	$sth4->execute( $studnum, $subjsec );
	if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth4->fetchrow;
	
	# skip if member of %r_SupressSubject or AdditionalComments
	my ($tsubjsec, $dud) = split('-', $subjsec );
	my $skipflag;
	if ( $count or $r_SupressSubject{$tsubjsec} or $r_SupressSubject{$subjsec} or
	     $r_AdditionalComments{$tsubjsec} or $r_AdditionalComments{$subjsec} ) {
	    $skipflag = 1;
	}

	if ( not $skipflag ) {

	    my ($subjcode, $section) = split('-',$subjsec);
	    my $sth4 = $dbh->prepare("insert into ext_moodle (studnum, subjsec, subjcode, role)
              values ( ?, ?, ?, 'student' )");
	    $sth4->execute( $studnum, $subjsec, $subjcode );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    print qq{ $lex{Mdl} }; # short form for Moodle.

	} else {
	    print qq{ ($lex{Skip} $lex{Mdl})}; # short form for Moodle.
	}


	print qq{</td></tr>\n}; # end of printed row

	
    } # Next Student/Subject combination.

    if ( not $DBI::errstr ) {
	print qq{</table>\n};
	print qq{<h3>$lex{'Record(s) Stored'}</h3></p>\n};
    } else {
	print qq{</table><p>$lex{Error}: $DBI::errstr<br>\n};
	print qq{$lex{'Contact'}:$adminname <a href="mailto:$adminemail">$adminemail</a>\n};
    }

    print qq{<p>[ <a href="$reppage">$lex{'Report Card'}</a> ]\n};
    print qq{</p></body></html>\n};

    exit;

} # End of writeRecords
