#!/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.

my %lex = ('Main' => 'Main',
	   'Error' => 'Error',
	   'Add' => 'Add',
	   'Scores' => 'Scores',
	   'Common Math Assessment' => 'Common Math Assessment',

	   'Student' => 'Student',
	   'Continue' => 'Continue',
	   'Save' => 'Save',
	   'Date' => 'Date',
	   'No User Id' => 'No User Id',
	   'No Password' => 'No Password',
	   'Please Log In' => 'Please Log In',
	   'Grade' => 'Grade',
	   'Homeroom' => 'Homeroom',
	   'Select' => 'Select',
	   'Record' => 'Record',
	   'Skipping' => 'Skipping',
	   'Students' => 'Students',
	   'Test' => 'Test',
	   'Missing Value' => 'Missing Value',
	   'Score' => 'Score',
	   'Record Exists' => 'Record Exists',
	   'Added' => 'Added',

	   'Select by' => 'Select by',
	   'Or' => 'Or',
	   'Updated' => 'Updated',

	   'Check' => 'Check',
	   'Next Page' => 'Next Page',
	   
	   );

use DBI;
use CGI;
use CGI::Session;
use Time::JulianDay;


my %exceptions = ( 'moved' => 'Moved', 'attendance' => 'Persistent Absences', 
  'altprog' => 'Alternate Program', 'other' => 'Other' );
my @exceptions = ( 'moved', 'attendance', 'altprog', 'other');

my $self = 'ilangAdd.pl';


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

my @time = localtime(time);
my $year = $time[5] + 1900;
my $month = $time[4] + 1;
my $day = $time[3];
if ( length $month == 1 ) { $month = '0'. $month; }
if ( length $day == 1 ) { $day = '0'. $day; }
my $currdate = "$year-$month-$day";

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


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


# Session Setup Here
my $session = new CGI::Session("driver:mysql;serializer:FreezeThaw",
 undef,{Handle => $dbh}) or die CGI::Session->errstr;

# Get/Set  Session Values (a defined userid means it was passed)
if ( $arr{userid} ){ # we want to login, passed userid/password pair.

    # Check password/userid against database (-1 no user, -2 wrong password);
    my $error = checkPassword($arr{userid}, $arr{password});
    if ($error == -1){ print $q->header( -charset, $charset ); print qq{<h3>$lex{'No User Id'}</h3>}; }
    if ($error == -2){ print $q->header( -charset, $charset ); print qq{<h3>$lex{'No Password'}</h3>}; }

    $cookietime = checkCookieTime( $arr{duration} );

    # Set values for userid and logged_in in session
    $session->param( 'logged_in','1');
    $session->expire( 'logged_in', $cookietime );
    $session->param( 'userid',$arr{userid} );
    $session->param( 'duration',$cookietime );

    $userid = $arr{userid};


} else { # check logged_in value in session

    if ( not $session->param('logged_in') ){
	$userid = $session->param('userid');
        print $q->header( -charset, $charset );
	print qq{<form action="../tlogin.pl" method="post" style="display:inline;">\n};
	print qq{<input type="hidden" name="userid" value="$userid">\n};
	print qq{<input type="hidden" name="script" value="ilang/$self">\n};
	print qq{<input type="submit" value="$lex{'Please Log In'}">\n};
	print qq{</form></body></html>\n};
        exit;
    }
    # Ok, we have a login. Values below we have in environment.

    $userid = $session->param('userid');
    $duration = $session->param('duration');

    if ( not ($duration =~ /\+/)) { # if not in +20m format, do so.
	$duration = checkCookieTime( $duration );
    }

    $session->expire('logged_in', $duration );


} # End of check for logged_in value

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

# Session Setup End

# Page Header
my $title = qq{$lex{Add} Indigenous Language $lex{Scores}};

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

if ( not $arr{page} ) {
    print qq{<link rel="stylesheet" type="text/css" media="all" };
    print qq{href="/js/calendar-blue.css" title="blue">\n};
    print qq{<script type="text/javascript" src="/js/calendar.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/lang/calendar-en.js"></script>\n};
    print qq{<script type="text/javascript" src="/js/calendar-setup.js"></script>\n};
}


print qq{$chartype\n</head><body style="padding:1em 2em;">\n};
print qq{[ <a href="$tchpage">$lex{Main}</a> ]\n};
print qq{<h1>$title</h1>\n};


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

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

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

}  elsif ( $arr{page} == 4 ) {
    delete $arr{page};
    writeExceptions();
}


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

    my (@homerooms, @grades );
    # Get 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;

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

    
    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};

    print qq{<tr><td class="bra">$lex{Test} $lex{Date}</td>\n};
    print qq{<td><input type="text" name="tdate" id="date" size="10" value="$currdate">\n};
    print qq{<button type="reset" id="start_trigger">...</button> yyyy-mm-dd\n};
    print qq{</td></tr>\n};


    print qq{<tr><td class="bra">Pretest or Posttest</td>};
    print qq{<td class="la"><select name="prepost"><option></option>\n};
    print qq{<option value="pretest">Pre-Test</option>};
    print qq{<option value="posttest">Post-Test</option></select></td></tr>\n};


    
    # Select Grade
    print qq{<tr><td colspan="2"><hr></td></tr>\n};
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Grade}</td>};
    print qq{<td><select name="grade"><option></option>\n};
    foreach my $gr ( @grades ) {
	print qq{<option>$gr</option>\n};
    }
    print qq{</select></td></tr>\n};

    # OR
    print qq{<tr><td></td><td class="bla" style="color:blue;">$lex{Or}</td></tr>\n};


    # Select Homeroom
    print qq{<tr><td class="bra">$lex{'Select by'} $lex{Homeroom}</td>};
    print qq{<td><select name="homeroom"><option></option>\n};
    foreach my $hr ( @homerooms ) {
	print qq{<option>$hr</option>\n};
    }
    print qq{</select></td></tr>\n};

    # Divider
    print qq{<tr><td colspan="2"><hr></td></tr>\n};


    # check next page?
    print qq{<tr><td class="bra">$lex{Check} $lex{'Next Page'}</td>\n};
    print qq{<td><input type="checkbox" name="chk" value="1" checked="checked">\n};
    print qq{</td></tr>\n};


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

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

    print qq{<script type="text/javascript">
     Calendar.setup({
        inputField     :    "date", // id of the input field
        ifFormat       :    "%Y-%m-%d", // format of the input field
        button         :    "start_trigger", // trigger for the calendar (button ID)
        singleClick    :    false,        // double-click mode
        step           :    1             // show all years in drop-down boxes 
    });
   </script>\n};

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

    exit;

} # end of showStartPage


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

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

    # Check for any Blanks
    foreach my $key ( 'prepost', 'tdate' ) {
	if ( not $arr{$key} ) {
	    print qq{<h3>$lex{'Missing Value'}: $key</h3>\n};
	    print qq{</body></html>\n};
	    exit;
	}
    }

    # Check Date format.
    my $err = checkDate( $arr{tdate} );
    if ( $err == 1 ) {
	print qq{<h3>$lex{Error}: Date Outside School Year: $arr{tdate}</h3>\n};
	print qq{</body></html>\n};
	exit;
	
    } elsif ( $err ) {
	print qq{<h3>Date Error: $err</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    my @tdate = split('-', $arr{tdate});
    my $tdatejd = julian_day( @tdate );
    my $dow = day_of_week( $tdatejd );
    $dow++; # since I'm stupid.
    my $weekday = $dow[$dow];
    my $tmonth = $tdate[1];
    
    my $checked;
    if ( $arr{chk} ) {
	$checked = 'CHECKED';
    }
    delete $arr{chk};
    
    
    my ($select, %grades, $group);
    if ( $arr{grade} ) {
	$select = 'where grade = ?';
	$grades{ $arr{grade} } = 1;
	
    } elsif ( $arr{homeroom}  ) {
	$select = 'where homeroom = ?';
	
	# Get the associated grade(s) for this homeroom
	my $sth = $dbh->prepare("select distinct grade from student where homeroom = ?");
	$sth->execute( $arr{homeroom} );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	while ( my $gr = $sth->fetchrow ) {
	    $grades{$gr} = 1;
	}
	
    } else { #error
	print qq{<h3>$lex{Error}: No Student Selection</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    if ( $arr{grade} ) {
	$group = $arr{grade};
    } else {
	$group = $arr{homeroom};
    }

    my $sth = $dbh->prepare("select * from student
     $select order by lastname, firstname");
    $sth->execute( $group );
    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }

    
    print qq{<div style="font-size:130%;"><b>$lex{Test} $lex{Date}</b> $weekday, $arr{tdate}</div>\n};

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


    # Score Month
    print qq{<div class="la" style="font-weight:bold;margin:1em 0;">};
    print qq{Select Scoring Month\n};
    print qq{<select name="scoremonth"><option value="$tmonth">$month[$tmonth]</option>\n};
    foreach my $monthval ( 9, 10, 11, 12, 1, 2, 3, 4, 5, 6 ) {
	if ( $monthval == $tmonth ) { next; }
	print qq{<option value="$monthval">$month[$monthval]</option>\n};
    }
    print qq{</select> Only one pretest/posttest per month allowed</div>\n};
    
    my $first = 1;

    
    # Student Loop
    while ( my  $ref = $sth->fetchrow_hashref ) {

	my %r = %$ref;

	if ( $first ) {
	    print qq{<div class="la"><input type="submit" value="$lex{Continue}"></div>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<tr><th>$lex{Student}</th><th>$lex{Grade}</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td class="la"><input type="checkbox" name="$r{studnum}" value="1" $checked> };
	print qq{<b>$r{lastname}</b>, $r{firstname}</td><td class="cn">$r{grade}</td></tr>\n};
    }

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

    exit;

} # end of selectStudent



#--------------
sub enterScores {
#--------------

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

    # Get School Year, we use $ey
    my ($sy, $ey) = split('-', $schoolyear);
    
    my $prepost = $arr{prepost};
    delete $arr{prepost};
    my $tdate = $arr{tdate};
    delete $arr{tdate};
    my $scoremonth = $arr{scoremonth};
    delete $arr{scoremonth};
    $scoremonth =~ s/^0//; # strip any leading zeros.
   
    # Anything left in %arr will be student numbers.

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

    if ( not %arr ) {
	print qq{<h3>$lex{Error}: No Student Selection</h3>\n};
	print qq{</body></html>\n};
	exit;
    }


    my (%sort, %student);
    my $sth = $dbh->prepare("select * from student where studnum = ?");
    foreach my $studnum  (keys %arr ) {
	$sth->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $ref = $sth->fetchrow_hashref;
	$student{$studnum} = $ref;
	my %r = %{ $ref };
	$sort{"$r{lastname}$r{firstname}$studnum"} = $studnum;
    }

    # Test Date
    print qq{<div style="font-size:130%;"><b>$lex{Test} $lex{Date}</b> $tdate</div>\n};

    # Score Month
    print qq{<div style="font-size:130%;"><b>Score Month</b> $month[$scoremonth]</div>\n};

    # Type
    print qq{<div style="font-size:130%;"><b>Type</b> $prepost</div>\n};

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

    print qq{<input type="hidden" name="tdate" value="$tdate">\n};
    print qq{<input type="hidden" name="prepost" value="$prepost">\n};
    print qq{<input type="hidden" name="scoremonth" value="$scoremonth">\n};
    

    my $first = 1;

    my $sth = $dbh->prepare("select score from cree_scores where studnum = ? and 
      scoremonth = ? and prepost = ?");
   
    
    # Student Loop
    foreach my $key ( sort keys %sort ) {
	my $studnum = $sort{$key};
	my %r = %{ $student{$studnum}};

	# Check for an existing record and get it's score
	$sth->execute( $studnum, $scoremonth, $prepost );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $score = $sth->fetchrow;
	# print "SN:$studnum Score:$score<br>\n";

	if ( $first ) {
	    print qq{<div class="la"><input class="btn-grn" type="submit" value="$lex{Save}"></div>\n};
	    print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
	    print qq{<caption style="font-weight:bold;font-size:120%;">};
	    print qq{Blank Scores will require exception reasons</caption>\n};
	    print qq{<tr><th>$lex{Student}</th><th>$lex{Grade}</th><th>$lex{Score}</th></tr>\n};
	    $first = 0;
	}

	print qq{<tr><td class="bra">$r{firstname} $r{lastname}</td><td class="cn">$r{grade}</td>\n};
	print qq{<td class="la">\n};
	print qq{<input type="text" name="$r{studnum}" value="$score" style="width:4em;"></td></tr>\n};

    }

    print qq{</table><div class="la"><input  class="btn-grn" type="submit" value="$lex{Save}"></div>\n};
    print qq{</form></body></html>\n};

    exit;

} # end of enterScores


#---------------
sub writeScores {
#---------------

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

    # Get School Year
    my ($sy, $ey) = split('-', $schoolyear);
    if ( not $ey ) { 
	print qq{<h3>School Year not correctly defined. Contact Office!</h3>\n};
	print qq{</body></html>\n};
	exit;
    }
    # $ey will be value stored in table (end year).

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

    
    my $sth1 = $dbh->prepare("select * from studentall where studnum = ?");
    
    my $sth2 = $dbh->prepare("insert into cree_scores
         ( studnum, treatynum, tdate, tauthor, tgrade, tage, tstamp, prepost, 
           scoremonth, score, schoolyear ) 
         values ( ?, ?, ?, ?, ?, ?, now(), ?, ?, ?, $ey )");

    
    foreach my $studnum ( keys %arr ) {

	$arr{$studnum} =~ s/\s+//g; # strip any spaces.
	
	my $score = $arr{$studnum};
	if ( $score =~ m/[a-zA-Z]/  or not $score ) { next; } 
        # skip any values with text or blank
	
	# Check for existing score for this student, this scoremonth, this pre/post, this school year
	my %scorepresent; # stores scores which are already present.
	my $sth = $dbh->prepare("select id from cree_scores 
           where studnum = ? and prepost = ? and scoremonth = ? and schoolyear = ?");
	$sth->execute( $studnum, $prepost, $scoremonth, $ey );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $id = $sth->fetchrow;
	if ( $id ) { $scorepresent{$studnum} = $id; }


	# Get Student Info
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $studref = $sth1->fetchrow_hashref;
	my %r = %$studref;

	my $age = calcAge( $r{birthdate}, $tdate );
	my $treatynum = $r{treaty};
	if ( not $treatynum ) { $treatynum = $r{provnum}; }

	
	# Insert or Update
	if ( $id ) { # we have a current record already

	    # update score
	    my $sth = $dbh->prepare("update cree_scores set score = ? where id = ?");
	    $sth->execute($score, $id );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }
	    print qq{<div style="font-weight:bold;">};
	    print qq{$r{firstname} $r{lastname} $lex{Score} $lex{Updated} };
	    print qq{to $score</div>\n};
		
	} else {  # insert a record

	    # Insert a record.
	    $sth2->execute( $studnum, $treatynum, $tdate, $userid, $r{grade}, $age, $prepost, 
				$scoremonth, $score );
	    if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	    print qq{<div style="font-weight:bold;">$r{firstname} $r{lastname} $lex{Score} };
	    print qq{$score $lex{Added}</div>\n};
	}

    } # end student loop


    # Add SSP Exceptions for some students
    my $first = 1;
    foreach my $studnum ( keys %arr ) {

	my $score = $arr{$studnum};
	if ( $score =~ m/[a-zA-Z]/  or not $score ) { 

	    # Get Student Info
	    $sth1->execute( $studnum );
	    if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	    my $ref = $sth1->fetchrow_hashref;
	    my %r = %$ref;

	    if ( $first ) {
		# Print Form Heading
		print qq{<form action="$self" method="post"> \n};
		print qq{<input type="hidden" name="page" value="4">\n};
		print qq{<input type="hidden" name="tdate" value="$tdate">\n};
		
		# Table
		print qq{<p></p><div class="la"><input type="submit" value="$lex{Save}"></div>\n};
		print qq{<table cellpadding="3" cellspacing="0" border="1">\n};
		print qq{<tr><th>$lex{Student}</th><th>Reasons for No Student Score</th></tr>\n};
		$first = 0;
	    }

	    print qq{<tr><td class="bra">$r{firstname} $r{lastname}</td>};
	    print qq{<td class="la">};
	    foreach my $key ( @exceptions ) {
		print qq{<input type="radio" name="EX:$studnum" value="$key">$exceptions{$key}<br>\n};
	    }
	    print qq{<span style="font-size:80%;">If Other, Please Specify</span>};
	    print qq{ <input type="text" size="60" name="OTHER:$studnum"></td></tr>\n};

	}
    }	    

    if ( not $first ) { 
	print qq{</table>\n};
	print qq{<div class="la"><input type="submit" value="$lex{Save}"></div>\n};
	print qq{</form>\n};
	
    } else { # display link options.
	print qq{<p>[ <a href="ilangView.pl">View iLang Scores</a> | \n};
	print qq{ <a href="ilangAdd.pl">Add iLang Scores</a> | \n};
	print qq{ <a href="$tchpage">$lex{Main}</a> ]</p>\n};
    }

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

    exit;

} # end of writeScores


#------------------
sub writeExceptions {
#------------------

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

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

    foreach my $key ( keys %arr ) {

	my ($type, $studnum ) = split(':', $key);

	if ( $type eq 'OTHER' ) { next; } # skip all 'Other' values.

	my $othercode = qq{OTHER:$studnum};
	my $reasonother = $arr{$othercode};
	my $reason = $arr{$key};


	# Check for existing record
	my $sth = $dbh->prepare("select count(*) from ssp_exceptions 
          where studnum = ? and tdate = ? and ssptype = ?");
	$sth->execute( $studnum, $tdate, 'cma' );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $count = $sth->fetchrow;

	# Get Student Info
	$sth1->execute( $studnum );
	if ($DBI::errstr){ print $DBI::errstr; die $DBI::errstr; }
	my $studref = $sth1->fetchrow_hashref;
	my %r = %$studref;

	if ( $count ) { # we've already written this record..
	    print qq{<div><b>$lex{'Record Exists'}</b>\n};
	    print qq{- $rec{firstname} $rec{lastname} ($studnum)};
	    print qq{<b>$lex{Test} $lex{Date}:</b> $tdate -<b>$lex{Skipping}</h3>\n};

	    next;
	}

	my $age = calcAge( $r{birthdate}, $tdate );
	my $treatynum = $r{treaty};
	if ( not $treatynum ) { $treatynum = $r{provnum}; }

	# Insert a record.
	$sth = $dbh->prepare("insert into ssp_exceptions
          ( studnum, treatynum, ssptype, tdate, tauthor, tgrade, tage, reasoncode, reasonother ) 
          values ( ?, ?, ?, ?, ?, ?, ?, ?, ? )");
	 $sth->execute( $studnum, $treatynum, 'cree', $tdate, $userid, $r{grade}, 
			$age, $reason, $reasonother );
        if ( $DBI::errstr ){ print $DBI::errstr; die $DBI::errstr; }

	print qq{<div>$r{firstname} $r{lastname} Exception $lex{Record} $lex{Added}</div>\n};

    }

    print qq{<p>[ <a href="$self">$title</a> |\n};
    print qq{<a href=\"$tchpage\">$lex{Main}</a> ]</p>\n};
    print qq{</body></html>\n};

    exit;

} # end of writeExceptions



#----------
sub calcAge {
#----------

    # Passed (birthdate, $currdate)
    my ( $birthdate, $currdate ) = @_;
    my ($byear,$bmonth,$bday) = split /-/,$birthdate;
    my ($cyear,$cmonth,$cday) = split /-/,$currdate;
    my $age = $cyear - $byear;
    my $month = $cmonth - $bmonth;
    #print "BD: $birthdate CD: $currdate Age: $age MO:$month<br>\n";

    if ($cmonth < $bmonth){
	$month = $month + 12;
	if ($cday < $bday){ $month--;}
	$age--;
    }
    elsif ($cmonth == $bmonth and $cday < $bday){
	$age--; 
	$month = 11;
    } elsif ($cmonth > $bmonth and $cday < $bday) {
	$month--;
    }

    if ( $age < 0 or $age > 100 ) { $age = 0; $month = 0; }

    return "$age:$month";

}


#------------
sub checkDate {
#------------

    use Time::JulianDay;
    
    my $date = shift;

    my ($y,$m,$d) = split('-',$date);
    
    if ( not $d ) { return 255; }  # wrong format.
    if ( $m > 12 or $m < 1 ) { return 255; }
    if ( $d > 31 or $d < 1 ) { return 255; }

    my $datejd = julian_day( $y, $m, $d );

    my $startjd = julian_day( split('-', $schoolstart ));
    my $endjd = julian_day( split('-', $schoolend ));
    
#    print "DATE:$date - $datejd Start:$schoolstart - $startjd  End:$schoolend - $endjd<br>\n";

    if ( $datejd > $endjd  or $datejd < $startjd ) {
	return 1; # different code for date outside of current year;
    }
    
    return 0;

}
