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

#  This file is part of Open Admin for Schools.

# Remove right column for Michael. Original rpttranscript is still present.


my %lex = ('Report' => 'Report',
	   'Main' => 'Main',
	   'Transcript' => 'Transcript',
	   'Transcripts' => 'Transcripts',
	   'Edit' => 'Edit',
	   'Transcript of Marks' => 'Transcript of Marks',
	   'No Quality Score for' => 'No Quality Score for',
	   'Report Card' => 'Report Card',
	   'Term' => 'Term',
	   'Credits Earned' => 'Credits Earned',
	   'Credits Attempted' => 'Credits Attempted',
	   'Reqd' => 'Reqd',
	   'Earned' => 'Earned',
	   'Total' => 'Total',
	   'Approved by' => 'Approved by',
	   'Transcript is official when sealed' => 'Transcript is official when sealed',
	   'Phone' => 'Phone',
	   'Email' => 'Email',
	   'Requirements Complete' => 'Requirements Complete',
	   'Printed' => 'Printed',
	   'No Records Found' => 'No Records Found',
	   'No Records Selected' => 'No Records Selected',
	   'Entry Error' => 'Entry Error',
	   'No Student(s) Found' => 'No Student(s) Found',
	   'Graduation~Requirements' => 'Graduation~Requirements',
	   'Semester GPA' => 'Year GPA',
	   'Cum GPA' => 'Cum GPA',
	   'Diploma Awarded on' => 'Graduation date',
	   'View/Download' => 'View/Download',
	   'View Log File' => 'View Log File',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'DOB' => 'DOB',
	   'Lastname/Lastname,Firstname/Initials/StudentNumber' => 
	     'Lastname/Lastname,Firstname/Initials/StudentNumber',
	   'Select Student' => 'Select Student',
	   'Select Group' => 'Select Group',
	   'Continue' => 'Continue',
	   'Code' => 'Code',
	   'Subject' => 'Subject',
	   'Credit' => 'Credit',
	   'Area' => 'Area',
	   'Error' => 'Error',
	   'Letter' => 'Letter',
	   'Legal' => 'Legal',
	   'A4' => 'A4',
	   'Paper Size' => 'Paper Size',
	   'Not Found' => 'Not Found',

	   );

my $self = 'rpttranscript.pl';

# Configuration Format Variables
my $blockwidth = '90mm'; # 3.7in
my $col1 = '15mm'; # '0.60in';
my $col2 = '37mm'; # '1.45in';
my $col3 = '12mm'; #'0.47in';
my $col4 = '24mm'; #'0.94in';

$grayscale = '1.00';
my $maxlines = 35; # begin splitting into separate tables after this...

my $voffset = '-25mm';
my $hoffset = '-12mm';


use DBI;
use CGI;
use Number::Format qw(:subs);


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


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


# filter latex function
eval require "../../lib/liblatex.pl";
if ( $@ ) {
    print $lex{Error}. ": $@<br>\n";
    die $lex{Error}. ": $@\n";
}

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

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



# Get transcript values from configuration system
my $sth = $dbh->prepare("select datavalue from conf_system where filename = 'transcript'");
$sth->execute;
while (	my $datavalue = $sth->fetchrow ) {
    eval $datavalue;
    if ( $@ ) {
	print "$lex{Error}: $@<br>\n";
	die "$lex{Error}: $@\n";
    }
}


# Set Paper Size, text width and height
my ( $papersize, $textwidth, $textheight );


if ( $arr{papersize} eq $lex{Legal} ) {
    $papersize = 'legalpaper';
    $textwidth = $g_legalpaper_textwidth;
    $textheight = $g_legalpaper_textheight;
} elsif ( $arr{papersize} eq $lex{A4} ) {
    $papersize = 'a4paper';
    $textwidth = $g_a4paper_textwidth;
    $textheight = $g_a4paper_textheight;
} else {  # default to Letter paper.
    $papersize = 'letterpaper';
    $textwidth = $g_letterpaper_textwidth;
    $textheight = $g_letterpaper_textheight;
}
 
# print qq{Papersize: $papersize  TW: $textwidth  TH: $textheight<br>\n};

my $fmt = new Number::Format(-decimal_fill => '1', -decimal_digits => '2');

my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, 
    $iddst) = localtime(time);
$year = $year + 1900;
$mon++;
$wday++;
my $currdate = "$dow[$wday], $month[$mon] $mday, $year";


my $shortname = "transcript$$";
my $filename = "$shortname.tex";
my $logfile = "pdflog$$.txt";

if ( not $arr{page} ) { 
    $offset = 2; 
} elsif ( $arr{page} == 1 ) {
    $offset = 1;
}

my $title = "$lex{Transcript} $lex{Report}";

print qq{$doctype\n<html><head><title>$title</title>
<link rel="stylesheet" href="$css" type="text/css">\n};
print qq{<link rel="stylesheet" type="text/css" media="all">\n};
print qq{$chartype\n</head><body style="padding:2em;" };
print qq{onload="document.forms[0].elements[$offset].focus()">\n};


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

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


if ( not $arr{page} ) {
    showStartPage();
    
} elsif ( $arr{page} == 1 ) {
    delete $arr{page};
    processSearch();
} elsif ( $arr{page} == 2 ) {
    delete $arr{page};
    delete $arr{papersize};

    printTranscriptsHTML();
    printTranscriptsPDF();
}




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

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

    print qq{<div style="border:1px solid gray;padding:1em; margin:0.5em; width:50%;">};
    print qq{$lex{'Lastname/Lastname,Firstname/Initials/StudentNumber'}<br>\n};
    print qq{<input type="submit" value="$lex{'Select Student'}">\n};
    print qq{<input type="text"  name="student" size="12"></div>\n};

    print qq{<div style="border:1px solid gray;padding:1em; margin:0.5em; width:50%;">};
    print qq{<input type="submit" value="$lex{'Select Group'}">\n};
    print qq{<select name="groupname"><option>$lex{Homeroom}</option>\n};
    print qq{<option>$lex{Grade}</option>\n};
    print qq{</select>\n};
    print qq{<input type="text" name="groupvalue" size="6"></div>\n};

    # Paper Size
    print qq{<div style="border:1px solid gray;padding:1em; margin:0.5em; width:50%;">};
    $defaultpapersize =~ s/paper//; # strip out word paper so lex works; from admin.conf
    my $defpaper = ucfirst( $defaultpapersize );
    print $lex{'Paper Size'};
    print qq{ <select name="papersize"><option>$lex{$defpaper}</option>\n};
    my @sizes = qw(Letter A4 Legal);
    foreach my $size ( @sizes ) {
	if ( $size eq $defpaper ) { next; }
	print qq{<option>$lex{$size}</option>};
    }
    print qq{</select></div></form>\n};
    print qq{</body></html>\n};

    exit;

}


#----------------
sub processSearch {
#----------------

    # Passed: student, group, select

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

    my @students = ();
    print qq{<p></p>\n};

    if ( $arr{student} ) { # We are looking for a single student...

	my $student = $arr{student};
    
	# Setup the Search
	if ($student =~ /\d+/) {  # we have a student number
	    push @students, $student;
	} else { # we have words hopefully with a comma
	    my ($lastname,$firstname)  = split /\,/, $student;
	    $firstname =~ s/^\s*//;
	    $lastname =~ s/^\s*//;
	    if ($lastname and $firstname){ # both entered.
		$sth = $dbh->prepare("select studnum from tscriptident 
                  where lastname = ? and firstname = ?");
		$sth->execute( $lastname, $firstname );
	    } elsif ($lastname and not $firstname){ # only lastname (no comma)
		if (length($lastname) == 2){ # search by initials: fi, li.
		    my $fi = substr($lastname,0,1). '%';
		    my $li = substr($lastname,1,1). '%';

		    $sth = $dbh->prepare("select studnum from tscriptident 
                     where lastname $sql{like} ? and firstname $sql{like} ?");
		    $sth->execute( $li, $fi );
		} else {
		    $sth = $dbh->prepare("select studnum from tscriptident 
                     where lastname = ? order by firstname");
		    $sth->execute( $lastname );
		}
	    } else { # print an error....
		print qq{<p><b>$lex{'Entry Error'}: $lex{'No Student(s) Found'}};
		print qq{</b></p>\n};
		print qq{</body></html>\n};
		exit;
	    }

	} # Last Else

   	if ( $sth ) { # if text we should have a statement handle (sth)
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    $rows = $sth->rows;
	    if ($rows < 1) { 
		print qq{<p><b>$lex{'No Student(s) Found'}</b></p>\n};
		print qq{</body></html>\n}; 
		exit;
	    }
    
	    while ( my $studnum = $sth->fetchrow ) {
		push @students, $studnum;
	    }
	}

    } elsif ( $arr{groupvalue} ) { # We have a group selected; select from student table

	my $select;
	if ( $arr{groupname} eq $lex{Grade} ) {
	    $select = 'where grade = ?';
	} elsif ( $arr{groupname} eq $lex{Homeroom} ) {
	    $select = 'where homeroom = ?';
	} else {
	    print $lex{'No Records Selected'};
	    print qq{</body></html>\n};
	    exit;
	}
	
	$sth = $dbh->prepare("select studnum from studentall $select 
          order by lastname, firstname");
	$sth->execute( $arr{groupvalue} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $studnum = $sth->fetchrow ) {
	    push @students, $studnum;
	}
    }

    if ( not @students ) {
	print $lex{'No Records Found'};
	print qq{</body></html>\n};
	exit;
    }


    # Now print the form...
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="2">\n};
    print qq{<input type="hidden" name="papersize" value="$arr{papersize}">\n};
    print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
   
    # display found students, if any...
    $sth1 = $dbh->prepare("select lastname, firstname from tscriptident where studnum = ?");
    $sth2 = $dbh->prepare("select lastname, firstname from studentall where studnum = ?");

    my $checked;
    if ( $arr{groupvalue} ) { # check group by default only.
	$checked = 'checked';
    }

    foreach my $studnum ( @students ) {

	$sth1->execute( $studnum );
	my ($lastname, $firstname) = $sth1->fetchrow;

	if ( not $lastname ) {
	    $sth2->execute( $studnum );
	    my ($lastname, $firstname) = $sth2->fetchrow;
	    print qq{<tr><td>$firstname $lastname ($studnum) <span style="color:red;">};
	    print qq{$lex{'Not Found'}</span></td><td></td></tr>};

	} else {
	    print qq{<tr><td>$firstname $lastname ($studnum)</td>};
	    print qq{<td><input type="checkbox" name="$studnum" value="1" $checked></td>};
	    print qq{</tr>\n};
	}
	
    }

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

    exit;

}


#-----------------------
sub printTranscriptsHTML {
#-----------------------

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

    if ( not %arr ){
	print qq{<p><b>$lex{'No Records Found'}</b></p>\n};
	print qq{</body></html>\n};
	exit;
    }


    my $sth = $dbh->prepare("select id, subjectcode, subjecttext, subjectarea, 
     score_mark, score_letter, schoolyear, credit, term, term_desc 
     from tscriptdata where studnum = ?
     order by schoolyear, term, subjecttext");
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    my $sth1 = $dbh->prepare("select lastname, firstname, birthdate 
     from tscriptident where studnum = ?");
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    # Main Loop - once for each student.
    foreach my $studnum ( keys %arr ) {

	# totalCredits include Pass/Fail Subjects
	my ($totalCredits, $totalGPQuality, $totalGPCredits); 

	# process transcript data
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }


	# Fetch Student's Info
	$sth1->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ($lastname, $firstname, $birthdate) = $sth1->fetchrow;

   
	print qq{<h1>$firstname $lastname ($studnum) - $birthdate</h1>\n};
	
	my $currdesc = -1;
	my $prevdesc;
	my $currschoolyear = -1;
	my $prevschoolyear;


	# Outer Table
	print qq{<table cellpadding="3" cellspacing="0" border="0">\n};
	print qq{<tr><td valign="top">\n};

	# Inner Table
	print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	print qq{<tr><th>$lex{Code}</th><th>$lex{Subject}</th><th>$lex{Area}</th>};
	print qq{<th>$lex{Credit}</th><th>$lex{Grade}</th></tr>\n};

	my $first = 1;
	my $colcounter = 1;
	my ( $semesterGPCredits, $semesterGPQuality, $semesterAttempts, $semesterCredits );


	# Loop through all transcript records.
	while ( my ( $id, $subjectcode, $subjecttext, $subjectarea, $score_mark, $score_letter, 
		     $schoolyear, $credit, $term, $term_desc ) = $sth->fetchrow ) {

	    $score_mark =~ s/%//; # strip percents.

	    $prevdesc = $currdesc;
	    $currdesc = $term_desc;
	    $prevschoolyear = $currschoolyear;
	    $currschoolyear = $schoolyear;


	    if ( $currdesc ne $prevdesc or $currschoolyear ne $prevschoolyear ) {
		if ( not $first ) {
		    my ($gpa, $cumgpa);
		    if ($semesterGPCredits) {
			$gpa = $fmt->format_number( $semesterGPQuality / $semesterGPCredits, 2 );
		    } else {
			$gpa = 0;
		    }

		    if ( $totalGPCredits ) {
			$cumgpa = $fmt->format_number( $totalGPQuality / $totalGPCredits, 2 );
		    } else {
			$cumgpa = 0;
		    }
		    my $gpa = $fmt->format_number( $gpa , 2);
		    my $cumgpa = $fmt->format_number( $cumgpa, 2);
		    
		    print qq{<tr style="background-color:#EEE;">};
		    print qq{<td colspan="5">$lex{'Semester GPA'}: $gpa\n};
		    print qq{$lex{'Cum GPA'}: $cumgpa</td></tr>\n};

		    $semesterAttempts = $fmt->format_number( $semesterAttempts, 2); # attempted
		    $semesterCredits = $fmt->format_number( $semesterCredits, 2);  # earned

		    print qq{<tr style="background-color:#CCF;">};
		    print qq{<td colspan="5">$lex{'Credits Attempted'} $semesterAttempts\n};
		    print qq{$lex{'Credits Earned'} $semesterCredits</td></tr>\n};
		    print qq{</table>\n};

		    if ( $colcounter % 2 ) {
			print qq{\n\n</td><td valign="top">\n}; # new cell...
		    } else {
			print qq{\n\n</td></tr>\n<tr><td>\n}; # new row
		    }
		    $colcounter++;	    

		    $semesterGPQuality = 0;
		    $semesterGPCredits = 0;
		    $semesterCredits = 0;
		    $semesterAttempts = 0;


		    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
		    print qq{<tr><th>$lex{Code}</th><th>$lex{Subject}};
		    print qq{</th><th>$lex{Area}</th><th>};
		    print qq{$lex{Credit}</th><th>$lex{Grade}</th></tr>\n};


		} else { 
		    $first = 0; 
		}

		print qq{<div style="font-weight:bold;font-size:140%;letter-spacing:0.1em;};
		print qq{text-align:center;">};
		print qq{$schoolyear - $lex{Term} $term - $currdesc</div>\n};

	    }


	    # letterToQual hash in transcript.conf; add up quality scores and credit counts.
	    # Check for missing Quality value in transcript.conf
	    if ( ( not defined $letterToQual{ $score_letter } ) and 
		 ($score_letter ne $passletter ) ) { # thus unknown score
		print qq{$lex{'No Quality Score for'} $score_letter<br>\n};
		next; # skip
	    }

	    # Update Attempts
	    $semesterAttempts += $credit;


	    # Now do Pass Letter settings.
	    my $quality = 0;
	    if ( $score_letter eq $passletter ) {
		$semesterCredits += $credit;
		$totalCredits += $credit;

	    } elsif ( $score_letter eq $failletter ) {
		# No additions to credits, GP credits increase to bring down avg.
		$totalGPCredits += $credit;
		$semesterGPCredits += $credit;

	    } else { # calculate passing grade settings.

		$quality = $letterToQual{ $score_letter };

#		if ( $quality ) { # if we have a nonzero value, add in difficulty score.
#		    $quality += $score_diff; # difficulty factor
#		}

		# Update Quality scores for weighted average.
		$semesterGPQuality += $quality * $credit;
		$totalGPQuality += $quality * $credit;

		# Update GP Credit totals for weighted average.
		$totalGPCredits += $credit;
		$semesterGPCredits += $credit;

		# Update the credits
		$semesterCredits += $credit;
		$totalCredits += $credit;

	    }


	    $credit = $fmt->format_number( $credit, 2);
            $score_mark = $fmt->format_number( $score_mark, 1, 1);

	    print qq{<tr><td>$subjectcode</td><td>$subjecttext</td><td>$subjectarea</td>};
	    print qq{<td>$credit</td>};
	    if ( $t_ShowMark ) { # from transcript.conf 
		print qq{<td>$score_mark ($quality)</td></tr>\n};
	    } else {
		print qq{<td>$score_letter ($quality)</td></tr>\n};
	    }
	    
	}  

	# Print the last GPA value...
	if ( not $first ) {

	    my ($gpa, $cumgpa);
	    if ($semesterGPCredits) {
		$gpa = $fmt->format_number( $semesterGPQuality / $semesterGPCredits, 2 );
	    } else {
		$gpa = 0;
	    }
	    if ( $totalGPCredits ) {
		$cumgpa = $fmt->format_number( $totalGPQuality / $totalGPCredits, 2 );
	    } else {
		$cumgpa = 0;
	    }
	    $gpa = $fmt->format_number( $gpa, 2 );
	    $cumgpa = $fmt->format_number( $cumgpa, 2 );


	    print qq{<tr style="background-color:#EEE;">};
	    print qq{<td colspan="5">$lex{'Semester GPA'}: $gpa\n};
	    print qq{$lex{'Cum GPA'}: $cumgpa</td></tr>\n};

	    $semesterAttempts = $fmt->format_number( $semesterAttempts, 2); # attempted
	    $semesterCredits = $fmt->format_number( $semesterCredits, 2);  # earned
	    
	    print qq{<tr style="background-color:#CCF;">};
	    print qq{<td colspan="5">$lex{'Credits Attempted'} $semesterAttempts\n};
	    print qq{$lex{'Credits Earned'} $semesterCredits</td></tr>\n};

	    $semesterGPQuality = 0;
	    $semesterGPCredits = 0;
	    $semesterCredits = 0;
	    $semesterAttempts = 0;

	}


	print qq{</table>\n}; # finish off last inner table.

	# Finish off outer table.
	print qq{<!-- Finish Off outer table  -->\n};
	if ( $colcounter % 2 ) {
	    print qq{\n</td><td></td></tr>\n};
	} else {
	    print qq{\n</td></tr>\n};
	}
	print qq{</table>\n};



    } # End of Main Student Loop

    print qq{</table><p></p>\n};



}

#--------------
sub prTexHeader {
#--------------

    # $papersize, $textwidth and $textheight set above.

    print TEX "\\documentclass[10pt,$papersize]{article}\n";
    print TEX "\\usepackage{ array, colortbl, multicol, helvet, pifont, fancyhdr, fontspec}\n";
#    print TEX "$a_latex_header\n";

    print TEX "\\setlength{\\textwidth}{$textwidth}\n \\setlength{\\textheight}{$textheight}\n";
    print TEX "\\setlength{\\hoffset}{$hoffset}\n\\setlength{\\voffset}{$voffset}\n";

    print TEX "\\setlength{\\evensidemargin}{0in}\n\\setlength{\\oddsidemargin}{0in}\n";
    #print TEX "\\setlength{\\extrarowheight}{2pt}\n
    print TEX "\\setlength{\\parindent}{0pt}\n";
    print TEX "\\setlength{\\topskip}{0pt}\n";
    print TEX "\\setlength{\\headsep}{6pt}\n";
    print TEX "\\renewcommand{\\familydefault}{\\sfdefault}\n";
    print TEX "\\pagestyle{fancy}\n \\rfoot{$lex{Printed}: $currdate }\n";
    print TEX "\\cfoot{ }\n";

    print TEX "\\begin{document}\n";

}



#----------------------
sub printTranscriptsPDF {
#----------------------

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

    my $pagecount = 1;

    if ( not %arr ){
	print qq{<p><b>$lex{'No Records Found'}</b></p>\n};
	print qq{</body></html>\n};
	halt;
    }


    # Setup Tex File 
    open(TEX,">$filename") || die "Cannot open tex file";
    prTexHeader(); # print TeX file header defaults.

    # Setup selects for transcript data and student name
    my $sth = $dbh->prepare("select id, subjectcode, subjecttext, score_mark, score_letter, 
     schoolyear, credit, term, term_desc from tscriptdata where studnum = ?
     order by schoolyear, term, subjecttext");
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

    # Get Student Name
    my $sth1 = $dbh->prepare("select lastname, firstname, middlename, birthdate, graddate
      from tscriptident where studnum = ?");
    if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }


    # Main Loop - once for each student.
    foreach my $studnum ( keys %arr ) {

	# totalCredits include Pass/Fail Subjects
	my ($totalCredits, $totalGPQuality, $totalGPCredits); 

	# process transcript data
	$sth->execute( $studnum );
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }

	# Fetch Student's Info
	$sth1->execute($studnum);
	if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
	my ( $lastname, $firstname, $middlename, $birthdate, $graddate ) = $sth1->fetchrow;
	$globalGradDate = $graddate;

	if ( $pagecount != 1 ) { # start a new page.
	    print TEX "\\newpage\n";
	}

	print TEX "\\setcounter{page}{1}\n";
	#print TEX "\\{$schoolname -- $schoolyear \\hfill ";
	print TEX "\\rhead{$firstname $middlename $lastname -- Page \\thepage}\n";


	# Print School Info
	print TEX "{\\Large $schoolname} \\hfill {\\Large ";
	print TEX  $lex{'Transcript of Marks'}. "} \\hfill ". $lex{Phone}. " $schoolphone \n\n";
	
	print TEX  "$schooladdr2, $schoolcity, $schoolprov $schoolpcode\\hfill ";
	print TEX $lex{Email}. " $returnaddress \n\n";
	print TEX "\n\\bigskip\n\n";

   
	# Print Student Info
	print TEX "{\\Large\\bf $firstname $middlename $lastname} ";
	print TEX "\\quad{\\it\\bf ". $lex{DOB}. ":} $birthdate";
	print TEX "\\quad \\quad{\\it\\bf ". $lex{'Diploma Awarded on'}. ":} $globalGradDate \n\n";

	print TEX "\\begin{tabular}[t]{|p{ $blockwidth }|p{ $blockwidth }|}\\hline\n";

	my $currdesc = -1;
	my $prevdesc;
	my $currschoolyear = -1;
	my $prevschoolyear;

	my $first = 1;
	my $colcounter = 1;
	my $colorcounter = 1;

	my ($linecounter, $blockcounter); # needed to count how far down until splitting the table.

	my ( $semesterGPCredits, $semesterGPQuality, $semesterAttempts, $semesterCredits );

	# Loop through all transcript records.
	while ( my ( $id, $subjectcode, $subjecttext, $score_mark, $score_letter, 
		     $schoolyear, $credit, $term, $term_desc ) = $sth->fetchrow ) {

	    $score_mark =~ s/%//; # strip percents.

	    # remove section text if value set in transcript.conf
	    if ( $t_TruncateSection ) {
		my ($tmp, @rest) = split /-/, $subjectcode;
		$subjectcode = $tmp;
	    }

	    $blockcounter++;

	    # LaTeX filter possible fields with problems for LaTeX.
	    ( $subjecttext ) = latex_filter( $subjecttext );
	    ( $score_mark ) = latex_filter( $score_mark );
	    ( $term_desc ) = latex_filter( $term_desc );
	    # In case... (  ) = latex_filter(  );

	    $prevdesc = $currdesc;
	    $currdesc = $term_desc;
	    $prevschoolyear = $currschoolyear;
	    $currschoolyear = $schoolyear;


	    # if starting a new block, finish current totals, end table, start a new table.
	    if ( $currdesc ne $prevdesc or $currschoolyear ne $prevschoolyear ) { 
		if ( not $first ) {

		    my ($gpa, $cumgpa);
		    if ($semesterGPCredits) {
			$gpa = $fmt->format_number( ($semesterGPQuality / $semesterGPCredits), 2 );
		    } else {
			$gpa = 0;
		    }
		    if ( $totalGPCredits ) {
			$cumgpa = $fmt->format_number( ($totalGPQuality / $totalGPCredits), 2 );
		    } else {
			$cumgpa = 0;
		    }

		    $gpa = $fmt->format_number( $gpa, 2 );
		    $cumgpa = $fmt->format_number( $cumgpa, 2 );


		    print TEX " \\multicolumn{4}{\@{}l}{\\rule{0pt}{10pt}\\it\\small ";
		    print TEX $lex{'Semester GPA'}. ": {\\bf $gpa} \\quad ";
		    print TEX $lex{'Cum GPA'}. ": {\\bf $cumgpa}}\\\\\n";

		    $semesterAttempts = $fmt->format_number( $semesterAttempts, 2 ); # attempted
		    $semesterCredits = $fmt->format_number( $semesterCredits, 2 );  # earned

		    print TEX " \\multicolumn{4}{\@{}l}{\\it\\small ". $lex{'Credits Attempted'};
		    print TEX ": {\\bf $semesterAttempts} \\quad ";
		    print TEX $lex{'Credits Earned'}. ": {\\bf $semesterCredits} }\\\\\n";

		    $semesterGPQuality = 0;
		    $semesterGPCredits = 0;
		    $semesterCredits = 0;
		    $semesterAttempts = 0;

		    print TEX "\\end{tabular}\n"; # end this (inner) table.
	    
		    if ( $colcounter % 2 ) {
			$blockCountA = $blockcounter;
			$blockcounter = 0;
			print TEX " & \n";
		    } else { # we are at the end of a block line
			print TEX " \\\\ \\hline\n";
			
			# Now add up the lines
			$blockCountB = $blockcounter;
			$blockcounter = 0;

			if ( $blockCountA > $blockCountB ) {
			    $linecounter += $blockCountA;
			} else {
			    $linecounter += $blockCountB;
			}
			$linecounter += 4; # add 4 for a new block
			#print qq{LC:Block $linecounter<br>\n";


			# Put in Split here for the 
			if ( $linecounter > $maxlines ) {
			    print TEX "\\end{tabular}";
			    if ( not $splitflag ) {
				# print Right Hand Column: Grad Requirements, etc.
				printRightColumn( $studnum );
				$splitflag = 0; # default 1. Changed to 0 to fix rightColumn
				$linecounter = 0;
			    } else {
				print TEX "\n";
			    }
			    
			    print TEX "\\begin{tabular}[t]{|p{ $blockwidth }|p{ $blockwidth }|}";
			    print TEX "\\hline\n";
			}
			# End of Splitter to fix formatting.

		    }
		    $colcounter++;
		    $colorcounter = 1;

		} else { 
		    $first = 0; 
		}

		# set tabular column layout for next block
		print TEX "\\begin{tabular}[t]{\@{\\hspace{1pt}}p{ $col1 }\@{\\hspace{2pt}}p{ $col2 }";
		print TEX "\@{\\hspace{5pt}}p{ $col3 }\@{\\hspace{1pt}}p{ $col4 }\@{\\hspace{1pt}}}\n";

		print TEX "\\multicolumn{4}{l}{\\rule{0pt}{12pt}\\bf $schoolyear - $currdesc}\\\\\n";
		print TEX "\\multicolumn{4}{\@{}l}{\\it\\small\ " . $lex{Code};
		print TEX " \\hspace{0.25in} ". $lex{Subject};
		print TEX " \\hspace{1.0in} ". $lex{Credit}. " \\hspace{0.1in} ".  $lex{Grade}. "}\\\\ \n";

	    }


	    # letterToQual hash in transcript.conf; add up quality scores and credit counts.
	    # Check for missing Quality value in transcript.conf
	    if ( not defined $letterToQual{ $score_letter } and $score_letter ne $passletter ) { 
		print qq{$lex{'No Quality Score for'} $score_letter<br>\n}; 
		next; # skip
	    }

	    # Update Attempts
	    $semesterAttempts += $credit;

	    my $quality = 0;
	    # Now do Pass Letter settings.
	    if ( $score_letter eq $passletter ) {
		$semesterCredits += $credit;
		$totalCredits += $credit;

	    } elsif ( $score_letter eq $failletter ) {
		# No additions to credits, GP credits increase to bring down avg.
		$totalGPCredits += $credit;
		$semesterGPCredits += $credit;

	    } else { # calculate passing grade settings.

		$quality = $letterToQual{ $score_letter };

#		if ( $quality ) { # if we have a nonzero value, add in difficulty score.
#		    $quality += $score_diff; # difficulty factor
#		}

		# Update Quality scores for weighted average.
		$semesterGPQuality += $quality * $credit;
		$totalGPQuality += $quality * $credit;

		# Update GP Credit totals for weighted average.
		$totalGPCredits += $credit;
		$semesterGPCredits += $credit;

		# Update the credits
		$semesterCredits += $credit;
		$totalCredits += $credit;

	    }


	    $credit = $fmt->format_number( $credit, 2);
	    $score_mark = $fmt->format_number( $score_mark, 1, 1);

	    if ( $colorcounter % 2 ) {
		print TEX "\\rowcolor[gray]{ $grayscale }\n";
	    }
	    $colorcounter ++;
	    print TEX "\\small $subjectcode& \\raggedright\\small $subjecttext & ";
	    print TEX "\\small $credit & \\small ";
	    if ( $t_ShowMark ) { # set in transcript.conf
		print TEX "$score_mark \\\\ \n";
	    } else {
		print TEX "$score_mark \\hfil $score_letter \\hfil ($quality) \\\\ \n";
	    }
	    
	}  


	# Print the last GPA value...
	if ( not $first ) {

	    my ($gpa, $cumgpa);
	    if ($semesterGPCredits) {
		$gpa = $fmt->format_number( ( $semesterGPQuality / $semesterGPCredits ), 4 );
	    } else {
		$gpa = 0;
	    }
	    if ( $totalGPCredits ) {
		$cumgpa = $fmt->format_number( ( $totalGPQuality / $totalGPCredits ), 4 );
	    } else {
		$cumgpa = 0;
	    }
	    $gpa = $fmt->format_number( $gpa, 2 );
	    $cumgpa = $fmt->format_number( $cumgpa, 2 );


	    print TEX " \\multicolumn{4}{\@{}l}{\\rule{0pt}{12pt}\\it\\small ";
	    print TEX $lex{'Semester GPA'}. ": {\\bf $gpa} \\quad ";
	    print TEX $lex{'Cum GPA'}. ": {\\bf $cumgpa}}\\\\\n";

	    $semesterAttempts = $fmt->format_number( $semesterAttempts, 2); # attempted
	    $semesterCredits = $fmt->format_number( $semesterCredits, 2);  # earned

	    print TEX " \\multicolumn{4}{\@{}l}{\\it\\small ". $lex{'Credits Attempted'};
	    print TEX ": {\\bf $semesterAttempts} \\quad ";
	    print TEX $lex{'Credits Earned'}. ": {\\bf $semesterCredits} }\\\\\n";

	    print TEX "\\end{tabular}\n";

	    $semesterGPQuality = 0;
	    $semesterGPCredits = 0;
	    $semesterCredits = 0;
	    $semesterAttempts = 0;

	}

	if ( $colcounter % 2 ) {
	    print TEX " & \n";
	} 
	
	print TEX "\\\\ \\hline\\end{tabular}\n";


	# print Right Hand Column: Grad Requirements, etc.
	if ( not $splitflag ) { # we haven't printed the right column yet...
	    printRightColumn( $studnum );
	}

	$pagecount++;

    } # End of Main Student Loop


    print TEX "\\end{document}\n";
    close TEX;

    system("$pdflatex $filename >$logfile");
    system("mv $shortname.pdf $downloaddir");
    system("mv $logfile $downloaddir");
    system("rm -f $shortname.*");

    print qq{<h1><a href="$webdownloaddir/$shortname.pdf">\n};
    print qq{$lex{'View/Download'} $lex{'Transcripts'} };
    print qq{</a></h1>\n[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{<a href="$webdownloaddir/$logfile">$lex{'View Log File'}};
    print qq{</a> ]\n};
    print qq{</body></html>\n};

    exit;


}


#-------------------
sub printRightColumn { # print the grad requirements, etc in right most col of pdf version
#-------------------

    print TEX "\n\n\n"; # added to prevent a third year block attempting to fit when right column removed.
    return; # to remove right column
    
    my $studnum = shift;

    # Now print the right hand column
    print TEX "\\raggedbottom\\parbox[t]{2in}{\n";

    my $requiredTotal;
    my $earnedTotal;

    my $sth4 = $dbh->prepare("select id, score_letter, credit from tscriptdata 
      where studnum = ? and subjectarea = ?");

    if ( %gradRequirements ) { # if none defined in transcript.conf, don't print.

	print TEX "\\vspace{0.3in}{\\bf\\small\\quad ";
	print TEX $lex{'Graduation~Requirements'}. "\n\n";
	print TEX "\\begin{tabular}{r\@{ \\hspace{4pt} }r\@{ \\hspace{4pt} }r\@{ \\hspace{2pt} }l}\n";
	print TEX "\\it\\bf\\small ". $lex{'Subject'}. q{ }. $lex{'Area'}. "& \\it\\bf\\small ";
	print TEX $lex{Reqd}. "& \\it\\bf\\small ". $lex{Earned}. "& \\\\ \\hline \n"; 

    
	foreach my $key (sort keys %gradRequirements ) {
	    if ( $gradRequirements{$key} ) { # Any 0 credit elective is supressed...

		# Find courses for this subject area.
		$sth4->execute($studnum, $key);
		if ( $DBI::errstr ) { print $DBI::errstr; die $DBI::errstr; }
		
		my $creditTotal = 0; # total credits for this area.
		while (my ( $id, $scoreletter, $credit ) = $sth4->fetchrow ) {
		    if ( $scoreletter ne $failletter ) {
			$creditTotal += $credit;
		    }
		}

		$earnedTotal += $creditTotal;
		$requiredTotal += $gradRequirements{$key};

		print TEX "\\it\\small $key & \\it\\small ";
		print TEX $fmt->format_number( $gradRequirements{$key}, 2 );
		print TEX "&\\it\\small ". $fmt->format_number( $creditTotal, 2);

		if ( $creditTotal >= $gradRequirements{$key} ) {
		    print TEX "& \\ding{52} ";
		} else {
		    print TEX "& ";
		}

		print TEX "\\\\ \n\n";

	    } # end of IF
	} # end of ForEach

	print TEX "\\hline\n"; # put in line separator between these 2 sections.


	# Now do the zero credit versions... normally only 'Other'.
	foreach my $key (sort keys %gradRequirements ) {
	    if (not $gradRequirements{$key} ) { # Any 0 credit elective
		
		# Find courses for this subject area.
		$sth4->execute($studnum, $key);
		if ($DBI::errstr) { print $DBI::errstr; die $DBI::errstr; }
		
		my $creditTotal = 0; # total credits for this area.
		while (my ( $id, $scoreletter, $credit ) = $sth4->fetchrow ) {
		    if ( $scoreletter ne $failletter ) {
			$creditTotal += $credit;
		    }
		}

		$earnedTotal += $creditTotal;
		$requiredTotal += $gradRequirements{$key};

		print TEX "\\it\\small $key & \\it\\small ";
		print TEX $fmt->format_number( $gradRequirements{$key}, 2 );
		print TEX "&\\it\\small ". $fmt->format_number( $creditTotal, 2). " \\\\ \n\n";

		# print TEX "\\it\\small $key & \\it\\small ";
		# print TEX $fmt->format_number( $gradRequirements{$key}, 2 );
		# print TEX "&\\it\\small  \\\\ \n\n";
	    }
	}

	print TEX "\\hline\n";
    
	print TEX "\\it\\scriptsize ". $lex{Total}. "& \\it\\scriptsize ";
	print TEX $fmt->format_number( $requiredTotal, 2 );
	print TEX "&\\it\\scriptsize ";
	print TEX $fmt->format_number( $earnedTotal, 2). " \\\\ \n\n";

	print TEX "\\end{tabular}} \n\n";


	print TEX "\\begin{center}\\it\\footnotesize \\ding{52} = ";
	print TEX $lex{'Requirements Complete'}. "\n\n";
	print TEX "{\\tiny $section1}\n";
	print TEX "\\end{center}\n";

	if ( $globalGradDate ) {
	    print TEX "\\vspace{0.5in}\n";
	    # Removed and replaced with below: print TEX "\\quad\\underline{\\hspace{2in}}\n\n";
	    print TEX  "\\quad\\small ". $lex{'Diploma Awarded on'}. " $globalGradDate\n\n";
	}

    } # end of If GradRequirements exist.

    print TEX "\\vspace{0.3in}\n";
    print TEX "\\quad\\underline{\\hspace{2in}}\n\n\\quad\\small ". $lex{'Approved by'}. "\n\n";

    print TEX "\\vspace{0.5in}\\begin{center}";
    print TEX $lex{'Transcript is official when sealed'}. "\\end{center}\n\n";

    print TEX "}\n\n\n"; # end of the right side... 3 CR at end are important.


} # End of printRightColumn
