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

%lex = ('Main' => 'Main',
	'Error' => 'Error',
	'Continue' => 'Continue',
	'Select Format' => 'Select Format',
	'Separate with Spaces' => 'Separate with Spaces',
	'Name' => 'Name',
	'Group' => 'Group',
	'Grade' => 'Grade',
	'Homeroom' => 'Homeroom',
	'Select' => 'Select',
	'Sort by' => 'Sort by',
	'Select by' => 'Select by',
	'Student' => 'Student',
	'Select' => 'Select',
	'Checked' => 'Checked',
	'View/Download' => 'View/Download',
	'View Log File' => 'View Log File',
	'Labels' => 'Labels',
	'Font Size' => 'Font Size',
	'No Page Found' => 'No Page Found',
	'Unable to open label file' => 'Unable to open label file',
	'Year End Marks' => 'Year End Marks',
	'Mark based on' => 'Mark based on',
	'Average' => 'Average',
	'of Terms' => 'of Terms',
	'Term' => 'Term',
	'Final' => 'Final',
	'Staff' => 'Staff',

);

my $self = 'labels.pl';

# used to force a grid onto labels
my $showGrid = 0;

use DBI;
use CGI;
use Cwd;
use Number::Format qw(round);

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

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

eval  require "../lib/libmeta.pl";
if ( $@ ) {
    print $lex{Error}. " $@<br>\n";
    die $lex{Error}. " $@\n";
}

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;

# setup for teacher site, if called from there.
if ( getcwd() =~ /tcgi/ ){ # we are in tcgi
    $css = $tchcss;
    $homepage = $tchpage;
    $downloaddir = $tchdownloaddir;
    $webdownloaddir = $tchwebdownloaddir;
}


# Display top of page
my $title = qq{OA $lex{Labels}};
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{<h1>$title</h1>\n};


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

# Show start page if only beginning.
if ( not $arr{page} ) {
    showStartPage();

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

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

} elsif ( $arr{page} eq 'Mark1' ) { # Mark printing
    delete $arr{page};
    showGradeMarkMethod();

} elsif ( $arr{page} eq 'Mark2' ) { # print Mark Labels for Cume Folders
    delete $arr{page};
    printMarkLabels();

} elsif ( $arr{page} eq 'Family1' ) { # print Family Labels for delivery
    delete $arr{page};
    printFamily();

} else {
    print $lex{Error};
    print qq{ $lex{'No Page Found'}</body></html>\n};
}


#--------------
sub printFamily {
#--------------

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

    my $groupFld = $g_FamilyGroupLinkList[0];
    print qq{<h3>Using Default Family Grouping - $groupFld</h3>\n};

    # A field to give a family name rather than an appended list of lastnames a/b/c.
    my $altNameField = $g_FamilyGroupNameField;

    
    # Currently only using 5163 2" x 4" format
    my $shortname = "Fam1Labels$$";
    my $filename = "$shortname.tex";

    open(TEX,">", $filename) || die "Can't open tex file";


    # my $fontsize = $arr{fontsize}. 'pt'; # set below
    # delete $arr{fontsize};

    my $papersize;
    if ( $defaultpapersize ) {
	$papersize = $defaultpapersize;
    } else {
	$papersize = 'letterpaper';
    }


    $fontsize = '12pt';
    print TEX "\\documentclass[$fontsize]{article}\n";
    print TEX "\\usepackage{geometry}\n\\geometry{$papersize}\n";
    print TEX "\\usepackage{inputenc}\n";
    print TEX "\\usepackage{courier}\n"; # was luximono
    print TEX "$a_latex_header\n";
    #print TEX "\\renewcommand{\\familydefault}{\\sfdefault}\n";
    print TEX "\\usepackage[newdimens]{labels}\n";

    # This printing is now done by printLabelFormat() below (this is Avery label format)
    $format = '5163';
    printLabelFormat(*TEX, $format );

    print TEX "\\LabelInfotrue\n";
#    if ( $showGrid ) {
	print TEX "\\LabelGridtrue\n";
#    }   
    print TEX "\\begin{document}\\begin{labels}\n";

    
    # ------Start of family selections------------------------

    # Find all family groups. 
    my $sth = $dbh->prepare("select distinct $groupFld from student 
     where $groupFld != '' and $groupFld is not null");
    $sth->execute;
    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }

    my @groupFields;
    while ( my $fld = $sth->fetchrow ) {
	push @groupFields, $fld; #
    }

    
    # Find all blank/null grouped students.
    my $sth = $dbh->prepare("select studnum from student 
			    where $groupFld = '' or $groupFld is null 
			    order by grade,homeroom,lastname, firstname");
    $sth->execute;
    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
    my @nogroup;
    while ( my $sn = $sth->fetchrow ) {
	push @nogroup, $sn;
    }


    # Now get family groupings by field chosen
    # family groupings are in %family hash with {groupFld} -> @studnum array.

    my (@family, %familysize,%familyname,%altfamilyname, %busroute);
    my $sth = $dbh->prepare("select lastname, firstname, studnum, $altNameField, busroute from student 
			    where $groupFld = ? order by lastname, firstname");

    
    foreach my $gfield ( @groupFields ) {

	$sth->execute( $gfield );
	if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }

	my ( %familynames, %bus);
    
	# All of these people have the same group name
	while ( my $ref = $sth->fetchrow_hashref ) {

	    my %r = %$ref;
	    foreach my $key ( keys  %r ) {
		# print qq{K:$key Val:$r{$key}<br>\n};
		( $r{$key} ) = latex_filter(( $r{$key} ));
	    }

	    
	    # add to altfamilyname hash if they have one.
	    if ( $r{$altNameField} ) {
		$altfamilyname{$gfield} = $r{$altNameField};
	    }
	
	    
	    $familynames{ $r{lastname} } = 1; # all lastnames into a hash.
	    $bus{$r{busroute}} = 1;

	    # family{$gfield}[ studnums ];
	    if ( @{$family{$gfield}} ) { # that family already has studnums.
		push @{$family{$gfield}}, $r{studnum};
	    } else {
		$family{$gfield} = [ $r{studnum} ];
	    }
	}
	
	my $famname = join('/', keys %familynames);
	$familyname{$gfield} = $famname;

	my $buses = join('/', keys %bus);
	$busroute{$gfield} = $buses;
	
	my $childcount = scalar @{ $family{$gfield} };
	$familysize{$childcount}{$famname}{$gfield} = $gfield;

    }


    print qq{<h3>Family List Report</h3>\n};


    my $sth = $dbh->prepare("select * from student where studnum = ?");

    my $first = 1;
    foreach my $childcount ( sort {$b <=> $a}  keys %familysize ) {
	if ( $childcount < 3 ) { last; } # skip families with 1 or 2 students
	
	foreach my $famname ( sort keys %{ $familysize{$childcount} } ) {
	    foreach my $gfield ( sort keys %{ $familysize{$childcount}{$famname} } ) {

		if ( $first ) {
		    $first = 0;
		} else {
		    print TEX "\n\n"; # blank line to start new label.
		}


		my $famname;
		if ( $altfamilyname{$gfield} ) {
		    $famname = $altfamilyname{$gfield};
		} else {
		    $famname = $familyname{$gfield};
		}
		
		# this is the label printing section.
		
		print TEX "{\\bf\\Large $famname}\n";
		print TEX "{\\bf Bus - $busroute{$gfield}}\n";
		
		my $studcount;
		foreach my $studnum ( @{ $family{$gfield} } ) {
		    
		    if ( $studcount > 5 ) { # new label with same family name.
			print TEX "\n\n"; # blank line to start new label.
			print TEX "{\\bf\\Large $famname}\n";
			print TEX "{\\bf Bus - $busroute{$gfield}}\n";			
			$studcount = 0;
		    }
		    
		    $sth->execute($studnum);
		    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
		    # my ($lastname, $firstname, $homeroom, $grade, $house ) = $sth->fetchrow;
		    my $ref = $sth->fetchrow_hashref;
		    my %r = %$ref;

		    print TEX "$r{firstname} $r{lastname} HR-$r{homeroom}/GR-$r{grade}\n";

		    $studcount++;
		    
		} # student loop end
	    
	    } # gfield loop end
	} # famname loop end

    } # childcount end


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

    
    #----------------------------------------------
    # Now do the smaller families, 1 or 2 students
    # ---------------------------------------------

    # Currently only using 5163 2" x 4" format
    my $shortname2 = "Fam2Labels$$";
    my $filename2 = "$shortname2.tex";

    open(TEX,">", $filename2) || die "Can't open tex file";

    my $papersize;
    if ( $defaultpapersize ) {
	$papersize = $defaultpapersize;
    } else {
	$papersize = 'letterpaper';
    }


    $fontsize = '12pt';
    print TEX "\\documentclass[$fontsize]{article}\n";
    print TEX "\\usepackage{geometry}\n\\geometry{$papersize}\n";
    print TEX "\\usepackage{inputenc}\n";
    print TEX "\\usepackage{courier}\n"; # was luximono
    print TEX "$a_latex_header\n";
    #print TEX "\\renewcommand{\\familydefault}{\\sfdefault}\n";
    print TEX "\\usepackage[newdimens]{labels}\n";

    # This printing is now done by printLabelFormat() below (this is Avery label format)
    $format = '5162';
    printLabelFormat(*TEX, $format );

    print TEX "\\LabelInfotrue\n";
    # Can Turn this OFF
    print TEX "\\LabelGridtrue\n";


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


    my $sth = $dbh->prepare("select lastname, firstname, homeroom, grade, house from student 
      where studnum = ?");

    my $first = 1;
    foreach my $childcount ( sort {$b <=> $a}  keys %familysize ) {
	if ( $childcount > 2 ) { next; } # skip families with 3 or more students
	
	# foreach my $phone ( sort keys %{ $familysize{$childcount} } ) {
	foreach my $famname ( sort keys %{ $familysize{$childcount} } ) {
	    foreach my $gfield ( sort keys %{ $familysize{$childcount}{$famname} } ) {
		
		if ( $first ) {
		    $first = 0;
		} else {
		    print TEX "\n\n"; # blank line to start new label.
		}

		my $famname;
		if ( $altfamilyname{$gfield} ) {
		    $famname = $altfamilyname{$gfield};
		} else {
		    $famname = $familyname{$gfield};
		}

		# this is the label printing section.
		print TEX "{\\bf\\Large $famname}\n";
		print TEX "{\\bf Bus $busroute{$gfield}}\n";
		
		my $studcount;
		foreach my $studnum ( @{ $family{$gfield} } ) {
		    $sth->execute($studnum);
		    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
		    my ($lastname, $firstname, $homeroom, $grade, $house ) = $sth->fetchrow;

		    print TEX "$firstname $lastname HR-$homeroom/GR-$grade\n";
		    $studcount++;

		
		} # student loop end
	    
	    
	    } # gfield loop end
	} # famname loop end

    } # childcount end

    print TEX "\\end{labels}\n\\end{document}\n";        
    close TEX;
    # End of the small Families generation.
    #----------------------------------------------

    # Big Families
    system("$pdflatex $filename >pdflog$$.txt");
    system("mv $shortname.pdf $downloaddir");
    system("mv pdflog$$.txt $downloaddir");
    system("rm -f $shortname.*");

    print qq{<div style="width:40ch;border: 1px solid gray;padding:0.5em;font-size:120%;};
    print qq{margin:1em;float:left;">\n};
    print qq{<a href="$webdownloaddir/$shortname.pdf" style="font-weight:bold;">};
    print qq{$lex{'View/Download'} $lex{Labels}<br>};
    print qq{3 or more in family. 5163 labels</a>\n};
    print qq{<p>[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{<a href="$webdownloaddir/pdflog$$.txt">$lex{'View Log File'}</a> ]</div>\n};

    
    # Small Families
    system("$pdflatex $filename2 > pdflog2$$.txt");
    system("mv $shortname2.pdf $downloaddir");
    system("mv pdflog2$$.txt $downloaddir");
    system("rm -f $shortname2.*");

    print qq{<div style="width:40ch;border: 1px solid gray;padding:0.5em;font-size:120%;};
    print qq{margin:1em;float:left;">\n};
    
    print qq{<a href="$webdownloaddir/$shortname2.pdf" style="font-weight:bold;">};
    print qq{$lex{'View/Download'} $lex{Labels}<br>};
    print qq{1 or 2 students in family. 5162 Labels</a>\n};
    print qq{<p>[ <a href="$homepage">$lex{Main}</a> |\n};
    print qq{<a href="$webdownloaddir/pdflog2$$.txt">$lex{'View Log File'}</a> ]</p>\n};

    print qq{</div>\n};
    print qq{<br clear="left">\n};
    

    # No Group List
    if ( @nogroup ) {
	print qq{<table border="1" cellpadding="3" cellspacing="0" style="margin-bottom:1em;">\n};
	print qq{<caption style="font-weight:bold;">Students without a Family Group value</caption>\n};
	print qq{<tr><th>$lex{Name}</th><th>$lex{Homeroom}</th><th>$lex{Grade}</th></tr>\n};

	my $sth = $dbh->prepare("select lastname, firstname, homeroom, grade from student 
          where studnum = ?");

	for my $studnum ( @nogroup ) {

	    $sth->execute( $studnum );
	    if ($DBI::errstr) {print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname, $homeroom, $grade ) = $sth->fetchrow;	

	    print qq{<tr><td><b>$lastname</b>, $firstname ($studnum)</td>\n};
	    print qq{<td class="cn">$homeroom</td><td class="cn">$grade</td></tr>\n};

	}
    
	print qq{</table>\n};
    } # end of no group

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

    exit;

} # end of printFamily



#--------------
sub printLabels {
#--------------

    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }
    
    my $labelfile =  $arr{format};
    $labelfile = "../template/label/". $labelfile;
    delete $arr{format};
    
    # Get fontsize
    my $fontsize = $arr{fontsize}. 'pt';
    delete $arr{fontsize};
    
    # foreach my $key ( sort keys %arr ) { print qq{K:$key V:$arr{$key}<br>\n}; }

    
    # read file and get description
    unless (open (FH,"<", $labelfile)) {
	print $lex{'Unable to open label file'}. ": $!\n";
	die $lex{'Unable to open label file'}. ": $!\n";
    }
    my $desc = <FH>;
    my $formatline = <FH>;
    chomp $formatline;
    my ( $format, $barcode, $table ) = split(',', $formatline);

    if ( not $table ) {
	print qq{<h3>Table value not found. Second line, third element of file.</h3>\n};
	# print qq{</body></html>\n};
	# exit;
	print qq{<div>Defaulting to student table</div>\n};
	$table = 'student';
    }
    
    # Now slurp in rest of file
    my $layout;
    { local $/; $layout = <FH>; close FH;}

#  We don't care, since we load all fields.
#    while ( $layout =~ m{\<\#(.*?)\#\>}g ) {
#        $fields .= $1.',';
#    }
#    chop $fields; # remove trailing comma

    # Create hash to store homeroom -> teacher name;
    my %homeroomTeacher;
    my $sth2 = $dbh->prepare("select lastname, firstname from staff where userid = ?");
    
    if ( $table eq 'student' ) { # then load staff for special vars: homeroomTeacher
	my $sth1 = $dbh->prepare("select field_value, userid from staff_multi 
	    where field_name = 'homeroom'");
	$sth1->execute;
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while (	my ($homeroom, $userid) = $sth1->fetchrow ) {
	
	    # Get Staff Name;
	    $sth2->execute($userid);
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my ($lastname, $firstname) = $sth2->fetchrow;
	    
	    $homeroomTeacher{$homeroom} = qq{$firstname $lastname};
	}
    }


    
    my $sql;
    if ( $table eq 'staff' ) {
	$sql = "select * from staff where userid = ?";
    } else {
	$sql = "select * from student where studnum = ?";
    }
    #print qq{SQL: $sql<br>\n};
    my $sth = $dbh->prepare( $sql );

    
    my $shortname = "MLabels$$";
    my $filename = "$shortname.tex";

    open(TEX,">", $filename) || die "Can't open tex file";


    #my $papersize = lc( $arr{papersize} ). 'paper';
    if ( $defaultpapersize ) {
	$papersize = $defaultpapersize;
    } else {
	$papersize = 'letterpaper';
    }

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

    print TEX "\\documentclass[$fontsize]{article}\n";
    print TEX "\\usepackage{geometry}\n\\geometry{$papersize}\n";
    print TEX "\\usepackage{inputenc}\n";
    print TEX "$a_latex_header\n";
    print TEX "\\renewcommand{\\familydefault}{\\sfdefault}\n";
    print TEX "\\usepackage[newdimens]{labels}\n";

    if ( $barcode ) {
	print TEX "\\input{$cgidir/../template/label/code39.tex}\n";
    }

    printLabelFormat(*TEX, $format );

    print TEX "\\LabelInfotrue\n";
    if ( $showGrid ) {
	print TEX "\\LabelGridtrue\n";
    }   
    print TEX "\\begin{document}\\begin{labels}\n";


    my $sth1 = $dbh->prepare("select field_value from staff_multi 
      where field_name = ? and userid = ?");


    # Loop through all students or staff, printing their label.
    foreach my $key ( sort keys %arr ) {
 
	#print qq{K:$key V:$arr{$key}<br>\n}; # dud is sorting order
	my ($dud, $studnum) = split(':', $key);


	# Get values for this student/staff
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;

	# Add homeroomTeacher to the ref;
	my $homeroom = $ref->{homeroom};
	if ( $homeroom ) {
	    $ref->{homeroomTeacher} = $homeroomTeacher{$homeroom};
	}

	# Add in Staff Values: Grade, Homeroom, Position.
	if ( $table eq 'staff' ) {

	    foreach my $field ( 'grade', 'homeroom', 'position' ) {
		$sth1->execute( $field, $studnum );
		my $storage;
		while ( my $val = $sth1->fetchrow ) {
		    $storage .= $val. ' ';
		}
		$ref->{$field} = $storage;
	    }
	}


	# Latex Filter values
	foreach my $key ( keys  %{$ref} ) {
	    # print qq{K:$key Val:$ref->{$key}<br>\n};
	    ( $ref->{$key} ) = latex_filter(( $ref->{$key} ));
	    if ( $table eq 'staff' and $key eq 'userid') { # uppercase
		$ref->{$key} = uc( $ref->{$key} );
	    }
	}

	my $newlayout = $layout;
	# Now put in field values into layout block
	$newlayout =~ s{\<\#(.*?)\#\>}
	          { exists($ref->{$1}) 
		  ? $ref->{$1} 
	          : $1
		  }gsex;

	$newlayout =~ s/\n\s*\n/\n/g; # strip blank lines (or lines with whitespace only)

 	print TEX $newlayout. "\n\n";

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

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

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

    exit;

} # end of printLabels();



#-----------------
sub selectStudents {
#-----------------

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

    # Read in label file to see if staff being asked for.
    my $labelfile = $arr{format};
    $path = "../template/label";
    $labelfile = qq{$path/$labelfile};

    unless ( open (FH,"<$labelfile")) {
	print qq{Unable to open label file: $!\n};
	die "Unable to open label file: $!\n";
    }

    my $desc = <FH>;
    my $formatline = <FH>;
    chomp $formatline;
    my ( $format, $barcode, $table ) = split(',', $formatline);
    # $format is the avery code number.

    # print heading and start 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="format" value="$arr{format}">\n};
    print qq{<input type="hidden" name="fontsize" value="$arr{fontsize}">\n};

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

    print qq{<table cellpadding="3" cellspacing="0" border="0" };
    print qq{style="border:1px solid gray;padding:0.5em;">\n};

    if ( $table eq 'staff' ) {

	print qq{<tr><th>$lex{Select}</th><th>$lex{Staff}</th></tr>};

	my $sth = $dbh->prepare("select userid, lastname, firstname from staff 
          order by lastname, firstname");
	$sth->execute;
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my ( $userid, $lastname, $firstname ) = $sth->fetchrow ) {
	    $sortfield = $lastname. $firstname;
	    $sortfield =~ s/://g; # remove any colons;
	    
	    print qq{<tr><td align="center"><input type="checkbox" name="$sortfield:$userid" };
	    print qq{value="1" $arr{checked}></td>\n};
	    print qq{<td align="left"><b>$lastname</b>, $firstname ($userid)</td></tr>\n};
	}


    } else { # Normal Student select

	print qq{<tr><th>$lex{Select}</th><th>$lex{Student}</th><th>};
	print qq{$lex{Grade}</th><th>$lex{Homeroom}</th></tr>\n};

	my @groups = split /\s+/, $arr{groupValue};
	my $firstgroup = $dbh->quote ( shift @groups );
	#print qq{FG: $firstgroup<br>\n};

	my $group;
	if ( $arr{groupType} eq $lex{Grade} ) {
	    $group = 'grade';
	} else {
	    $group = 'homeroom';
	}

	my $select;
	$select = "where $group = $firstgroup";

	for my $grp ( @groups ) {
	    $grp = $dbh->quote( $grp );
	    $select .= " or $group = $grp";
	}
	#print qq{Select: $select<br>\n};

	my $sortorder;
	my $sortflag;
	if ( $arr{sortorder} eq $lex{Group} ) {
	    $sortorder = "order by $group, lastname, firstname";
	    $sortflag = 1;
	} else {
	    $sortorder = 'order by lastname, firstname';
	}

	my $sth = $dbh->prepare("select lastname, firstname, studnum, grade, homeroom 
         from student $select $sortorder");
	$sth->execute;
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while (my ($lastname, $firstname, $studnum, $grade, $homeroom) = $sth->fetchrow ) {

	    if ( $sortflag ) {
		if ( $group eq 'grade' ) {
		    $sortfield = $grade. $lastname. $firstname;
		} else {
		    $sortfield = $homeroom. $lastname. $firstname;
		}
	    } else {
		$sortfield = $lastname. $firstname;
	    }
	    $sortfield =~ s/://g; # remove any colons; used for sorting in next page (label sort order)
	    
	    print qq{<tr><td class="cn"><input type="checkbox" name="$sortfield:$studnum" };
	    print qq{value="1" $arr{checked}></td>\n};
	    print qq{<td class="la"><b>$lastname</b>, $firstname ($studnum)</td>\n};
	    print qq{<td class="cn">$grade</td><td class="cn">$homeroom</td>\n};
	    print qq{</tr>\n};
	}

    } # End of Student Area.

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

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

    exit;

}



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

    # print heading and start form.

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

    # Open the Label Templates
    $path = "../template/label";
    my @files = glob($path."/*.label");
    
    my (%desc, @labels);

    for my $labelfile ( @files ) {

	# read each label file and get description
	unless (open (FH,"<", $labelfile)) {
	    print qq{Unable to open label file: $!\n};
	    die "Unable to open label file: $!\n";
	}
	my $desc = <FH>;
	chomp $desc;
	$desc =~ s/\[//g; #strip any opening square labels
	$desc =~ s/^#//;
	$desc =~ s/&nbsp;/ /g;
	my $formatline = <FH>;
	my ( $format, $barcode, $table ) = split /,/, $formatline;
	$labelfile =~ s/^.*\///;
	$desc{$labelfile} = qq{$desc  $labelfile};
	# print "File:$labelfile<br>\n";
	push @labels, $labelfile;
	
    }


    print qq{<tr><td class="bra">$lex{'Select Format'}\n};
    print qq{</td><td><select name="format">\n};
    foreach my $labelfile ( @labels ) {
	print qq{<option value="$labelfile">$desc{$labelfile}</option>\n};
    }
    print qq{</select></td></tr>\n};


    print qq{<tr><td class="bra">$lex{'Sort by'}\n};
    print qq{</td><td><select name="sortorder"><option>$lex{Name}</option>\n};
    print qq{<option>$lex{Group}</option>};
    print qq{</select></td></tr>\n};


    print qq{<tr><td class="bra">$lex{'Select by'}\n};
    print qq{</td><td><select name="groupType"><option>$lex{Grade}</option>\n};
    print qq{<option>$lex{Homeroom}</option></select>\n};
    print qq{<input type="text" name="groupValue" size="12"> };
    print qq{$lex{'Separate with Spaces'}</td></tr>\n};


    print qq{<tr><td class="bra">$lex{'Font Size'}\n};
    print qq{</td><td><select name="fontsize"><option>12</option><option>11</option>\n};
    print qq{<option>10</option></select></td></tr>\n};


    print qq{<tr><td class="bra">Check Next Page</td>\n};
    print qq{<td class="la"><input type="checkbox" name="checked" };
    print qq{value="checked" checked="checked"></td></tr>\n};

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

    # Year End Marks Labels
    print qq{<div style="border:1px solid gray;padding:1em;margin:1em;width:20em;">\n};
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="Mark1">\n};
    print qq{<input type="submit" value="$lex{'Year End Marks'}">\n};
    print qq{</form> For sticking onto Cume Folder Records</div>\n};


    # Family Labels (for delivery to homes)
    print qq{<div style="border:1px solid gray;padding:1em;margin:1em;width:20em;">\n};
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="Family1">\n};
    print qq{<input type="submit" value="Family Labels">\n};
    print qq{</form> For sticking onto packages for home delivery. Based on 5163 labels (2x5)\n};
    print qq{for families of 3 or more students and 5162 (2x7) for smaller families.</div>\n};

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

    exit;


}


#----------------------
sub showGradeMarkMethod {
#----------------------

    # print heading and start form.
    print qq{<h1>$lex{'Year End Marks'}</h1>\n};
    
    print qq{<form action="$self" method="post">\n};
    print qq{<input type="hidden" name="page" value="Mark2">\n};
    print qq{<table cellpadding="3" cellspacing="3" border="0">\n};

    print qq{<tr><th>$lex{'Mark based on'}</th><th>$lex{Final}<br>$lex{Term}</th>\n};;
    print qq{<th>$lex{Average}<br>$lex{'of Terms'}</th></tr>\n};


    # Get all grades in school
    my $sth = $dbh->prepare("select distinct grade from student
      where grade != '' order by grade");
    $sth->execute;
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
    while ( my $grade = $sth->fetchrow ) {
	print qq{<tr><td class="ra">$lex{Grade} $grade</td><td class="cn">};
	# Input values are either F - Final Term (best) or A - Average of Terms(not so good).
	print qq{<input type="radio" name="$grade" value="F" checked="checked"></td>\n};
	print qq{<td align="center"><input type="radio" name="$grade" value="A">};
	print qq{</td></tr>\n};
    }


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

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

    exit;
}



#-----------------
sub printMarkLabels {
#-----------------

    use Number::Format qw(round);

    # load this to get the $additionalcomments value, to filter out this subject.
    eval require "../etc/repcard.conf";
    if ( $@ ) {
	print $lex{Error}. " $@<br>\n";
	die $lex{Error}. " $@\n";
    }

    # Currently only using 5161 1" x 4" format with monospaced fonts and 3 colums
    my $subjectSize = 13;
    my $markSize = 3;


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


    my $shortname = "MLabels$$";
    my $filename = "$shortname.tex";

    open(TEX,">$filename") || die "Can't open tex file";



    my $fontsize = $arr{fontsize}. 'pt';
    delete $arr{fontsize};
    if ( $defaultpapersize ) {
	$papersize = $defaultpapersize;
    } else {
	$papersize = 'letterpaper';
    }


    $fontsize = '10pt';
    print TEX "\\documentclass[$fontsize]{article}\n";
    print TEX "\\usepackage{geometry}\n\\geometry{$papersize}\n";
    print TEX "\\usepackage{inputenc}\n";
    print TEX "\\usepackage{courier}\n"; # was luximono
    print TEX "$a_latex_header\n";
    #print TEX "\\renewcommand{\\familydefault}{\\sfdefault}\n";
    print TEX "\\usepackage[newdimens]{labels}\n";

    # This printing is now done by printLabelFormat() below (this is Avery label format)
    #print TEX "\\LabelRows=10\n\\LabelCols=3\n";
    #print TEX "\\LeftPageMargin=4.2mm\n\\RightPageMargin=4.2mm\n";
    #print TEX "\\TopPageMargin=12.7mm\n\\BottomPageMargin=12.7mm\n";
    #print TEX "\\InterLabelColumn=2.1mm\n\\InterLabelRow=0mm\n";
    #print TEX "\\LeftLabelBorder=4mm\n\\RightLabelBorder=4mm\n";
    #print TEX "\\TopLabelBorder=2mm\n\\BottomLabelBorder=2mm\n";

    $format = '5161';
    printLabelFormat(*TEX, $format );

    print TEX "\\LabelInfotrue\n";
#    if ( $showGrid ) {
	print TEX "\\LabelGridtrue\n";
#    }   
    print TEX "\\begin{document}\n";
    #print TEX "\\begin{labels}\n";

    # prepare to select students by grade
    my $sth = $dbh->prepare("select lastname, firstname, studnum from student 
     where grade = ? order by lastname, firstname" );

    my $sth1 = $dbh->prepare("select distinct subjcode from eval where studnum = ?");
    my $sth2 = $dbh->prepare("select description, smdesc, startrptperiod, endrptperiod
      from subject where subjsec = ?");
    my $sth3 = $dbh->prepare("select $r_MarkField from eval 
      where subjcode = ? and studnum = ? and term = ?");

    # Loop through each grade, getting student and his/her grades to print on label.
    foreach my $grade ( sort keys %arr ) {
	my $method = $arr{$grade};

	$sth->execute($grade);
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	while ( my ( $lastname, $firstname, $studnum ) = $sth->fetchrow ) {

	    
	    my ( %subjectValue, %subjectSort, %subjectName );
 	    # Get subjsec values for this student
	    $sth1->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

	    my $subjcount; # count number of subjects

	    while ( my $subjsec = $sth1->fetchrow ) {
		# Get subject values
		$sth2->execute( $subjsec );
		if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		my ($description, $smdesc, $startterm, $endterm) = $sth2->fetchrow;
		if ( $description eq $additionalcomments ) { next; } # skip
		# $additionalcomments are defined in repcard.conf;

		$subjcount++;

		# Get eval value(s); one or all. 
		my $mark;
		if ( $method eq 'F' ) { # Final term for average
		    $sth3->execute( $subjsec, $studnum, $endterm );
		    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
		    $mark = $sth3->fetchrow;

		} else { # method eq 'A' - find average value;
		    my ($termcount, $total);
		    for my $trm ( $startterm..$endterm ) {
			$sth3->execute( $subjsec, $studnum, $trm );
			if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
			my $val = $sth3->fetchrow;
			$total =+ $val;
			$termcount++;
		    }
		    if ( $termcount ) { # can't divide by 0.
			$mark = round(0, $total / $termcount);
		    } else {
			$mark = 0;
		    }
		}
		
		# Now put values in storage;
		my $desc;
		if ( $smdesc ) {
		    $desc = $smdesc;
		} else {
		    $desc = substr $description, 0, 10; # limit to 10 chars.
		}

		$subjectValue{$subjsec} = round( $mark, $markSize );
		$subjectSort{"$desc:$subjsec"} = $subjsec;
		$subjectName{$subjsec} = round( $desc, $subjectSize );

	    } # Now done all subjects for this student;

	    if ( not $subjcount ) { next; } # next student; skip this student.

	    # Set the label.
	    print TEX "\\addresslabel[\\ttfamily]{%\n";
	    print TEX "$firstname $lastname - $schoolyear \\\\ \n";

	    my $count = 0;
	    for my $key ( sort keys %subjectSort ) {
		my $subjsec = $subjectSort{$key};
		my $mark = $subjectValue{$subjsec};
		my $desc = round( $subjectName{$subjsec}, $subjectSize );

		print TEX $mark . '-'. $desc;
		$count++;
		if ( $count % 4 == 0 ) { # new row
		    print TEX "\\\\ \n";
		}

	    }
	    
	    while ( $count % 4 != 0 ) {
		my $index = $count % 4;
		#print $index. ' ';
		if ( $index == 3 ) {
		    print TEX "$index \\\\ \n\n";
		}
		$count++;
	    }

	    print TEX "\n } \n";


	} # End of this Student


    } # End of Grades
    



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

    # Solve download location issues with cgi vs tcgi..
    # Get current dir so know what CSS to display;
    #if (getcwd() =~ /tcgi/){ # we are in tcgi
    #    $downloaddir = $tchdownloaddir;
    #    $webdownloaddir = $tchwebdownloaddir;
    #}

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

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

    exit;

} # end of printLabels();

# End of Print Mark Labels




#-------------------
sub printLabelFormat {
#-------------------

    # Get file handle and avery format number.
    my $fh = shift;
    my $format = shift;
  
    if ( $format == '5160' ) {
	# print qq{Inside 5160};
	$f{LabelRows} = '10';
	$f{LabelCols} = '3';
	$f{LeftPageMargin} = '4.2mm';
	$f{RightPageMargin} = '4.2mm';
	$f{TopPageMargin} = '12.7mm';
	$f{BottomPageMargin} = '12.7mm';

	$f{InterLabelColumn} = '2.1mm';
	$f{InterLabelRow} = '0mm';

	$f{LeftLabelBorder} = '4mm';
	$f{RightLabelBorder} = '4mm';
	$f{TopLabelBorder} = '2mm';
	$f{BottomLabelBorder} = '2mm';

    } elsif ( $format == '5161' ) {

	#print qq{Inside 5161};
	$f{LabelRows} = '10';
	$f{LabelCols} = '2';
	$f{LeftPageMargin} = '5mm';
	$f{RightPageMargin} = '4mm';
	$f{TopPageMargin} = '13mm';
	$f{BottomPageMargin} = '13mm';

	$f{InterLabelColumn} = '5mm';
	$f{InterLabelRow} = '0mm';

	$f{LeftLabelBorder} = '3mm';
	$f{RightLabelBorder} = '3mm';
	$f{TopLabelBorder} = '2mm';
	$f{BottomLabelBorder} = '2mm';

    } elsif ( $format == '5162' ) {

	#print qq{Inside 5162};
	$f{LabelRows} = '7';
	$f{LabelCols} = '2';
	$f{LeftPageMargin} = '5mm';
	$f{RightPageMargin} = '4mm';
	$f{TopPageMargin} = '21mm';
	$f{BottomPageMargin} = '21mm';

	$f{InterLabelColumn} = '0mm';
	$f{InterLabelRow} = '0mm';

	$f{LeftLabelBorder} = '3mm';
	$f{RightLabelBorder} = '3mm';
	$f{TopLabelBorder} = '2mm';
	$f{BottomLabelBorder} = '2mm';

    } elsif ( $format == '5163' ) {

	#print qq{Inside 5163};
	$f{LabelRows} = '5';
	$f{LabelCols} = '2';
	$f{LeftPageMargin} = '5mm';
	$f{RightPageMargin} = '4mm';
	$f{TopPageMargin} = '13mm';
	$f{BottomPageMargin} = '13mm';

	$f{InterLabelColumn} = '5mm';
	$f{InterLabelRow} = '0mm';

	$f{LeftLabelBorder} = '3mm';
	$f{RightLabelBorder} = '3mm';
	$f{TopLabelBorder} = '2mm';
	$f{BottomLabelBorder} = '2mm';

    } elsif ( $format == '5267' ) {

	#print qq{Inside 5267};
	$f{LabelRows} = '20';
	$f{LabelCols} = '4';
	$f{LeftPageMargin} = '5mm';
	$f{RightPageMargin} = '4mm';
	$f{TopPageMargin} = '13mm';
	$f{BottomPageMargin} = '13mm';

	$f{InterLabelColumn} = '5mm';
	$f{InterLabelRow} = '0mm';

	$f{LeftLabelBorder} = '3mm';
	$f{RightLabelBorder} = '3mm';
	$f{TopLabelBorder} = '2mm';
	$f{BottomLabelBorder} = '2mm';

    }

    
    # print format using passed file handle
    foreach my $key ( keys %f ) {
	print $fh "\\$key = $f{$key}\n";
    }

    return;

}
