#!/usr/bin/perl

#------------------------------------------------------------------------
# Author: C. Edward Chow
# Date:   16 Oct. 1998
# Draft:  1.0
# Simple Perl script to grade midterm 
#------------------------------------------------------------------------

use CGI qw(:standard);

$examine=param('examine'); # consist of class, semester, midterm/final
$studentLogin=param('studentLogin');
$graderLogin=param('graderLogin');
$graderPasswd=param('graderPasswd');
print header();
# extract class from $examine
$class=substr($examine, 0, 5);
$semester=substr($examine, 5, 1);
$year=substr($examine, 6, 4);
$term=substr($examine, 10, length($examine)-10);

print "examine=$examine, graderLogin=$graderLogin<br>";

$found=0;
open(IN, "$class\/grader.txt");
while (<IN>) {
   chomp();
	$grader = $_;
   if ($graderLogin eq $grader) {
       print "Grader $grader in the list<br>";
		 $found=1;
   }
}
if ($found == 0) { print "grader not in list<br>"; exit; }
close(IN);
open(IN, "list.txt");
$found = 0;
while (<IN>) {
    if (/$graderLogin/) {
        @fields = split(/:/);
        $encryptedPasswd = $fields[1];
        $fullname = $fields[5];
        $found = 1;
        last;
    }
}
if ($found == 0) {
    print "Grader not exist in password file!";
    die;
}
$try = 1;
if (crypt($graderPasswd, $encryptedPasswd) eq $encryptedPasswd) {
     print "Grader password correct<BR>\n";
} else {
   print header();
        print "Grader password not correct!";
      die;
}
close(IN);

$found = 0;
while(<$class\/$examine\/*>){
   if (/$studentLogin/) {
                chomp($filename=$_);
                print "studentLogin=$studentLogin, filename=$filename\n";
      $found = 1;
      last;
   }
}
if ($found == 0) {
   print start_html();
   print "$login $examine file not found";
   print end_html();
   die;
} else {
  print "student answer filename=$filename\n";
}
open(ANSWER, "$class\/$examine\/answer.txt");
<ANSWER>; # skip title line
while (<ANSWER>) {
   chomp;
	@field=split(/\s/);
	if ($field[0] ne "examine" &&
	    $field[0] ne "login" &&
		 $field[0] ne "name" &&
		 $field[0] ne "passwd" &&
		 $field[0] ne "phoneno") {
	   $point{$field[0]}=$field[1];
		$value = $field[2];
       $value =~ tr/+/ /;
       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	   $answers{$field[0]}=$value;
   	# print "key=$field[0], point=$field[1], answers=$field[2]<br>";
	}
}
close(ANSWER);
$multichoiceGrade = 0;
$noMultichoice = 0;
open(STUDENTANSWER, "$filename");
while (<STUDENTANSWER>) {
   @nvpairs = split(/&/);
   foreach $pair (@nvpairs) {
       ($name, $value) = split(/=/, $pair);
   
       $value =~ tr/+/ /;
       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
       #print "name=$name, value=$value<br>";
       $studentAnswers{$name} = $value;
		 if ($point{$name} == 1) {
			 $multichoice++;
		    if ($studentAnswers{$name} eq $answers{$name}) {
		       $multichoiceGrade+=1; $correct{$name}=$answers{$name};
			 } else {
			    $correct{$name}="wrong";
			    #print "<font color=red>$studentAnswers{$name} ne $answers{$name}?, $correct answer=$answers{$name}</font><br>";
			 }
		 }
   }
}
close(STUDENTANSWER);
open(EXAM, "$class\/$examine\/g$examine.html");
print "open EXAM file $class\/$examine\/g$examine.html<br>";
while (<EXAM>) {
   if (/<TITLE/) {
      print "\t<TITLE>retrieve/grade $examine</TITLE>\n";
   }
   if (/<BODY/) {
      print $_;
      print "Retrieve from $filename:<P>";
   }
   if (/<FORM/i) {
      s/action="([^"]+)\"/action=\"\/cgi-bin\/chow\/grade\/gradeSubmit.pl\"/;
      print $_;
      print "<input type=hidden name=studentLogin value=$studentLogin>";
      print "<input type=hidden name=graderLogin value=$graderLogin>";
      print "<input type=hidden name=graderPasswd value=$graderPasswd>";
   } elsif (/<INPUT/i) {
      /name=\"([^"]+)\"/;
      $key = $1;
      #$key =~ tr/_/\./;  # why we would like to translate _ to .
      #print "key=$key, answer=$studentAnswers{$key}<BR>\n";
		if (/type=\"radio\"/ || /type=text/) {
       if ($studentAnswers{$key} eq "Yes") {
         s/(value=\"Yes\")/\1 checked/;
			
       } elsif ($studentAnswers{$key} eq "No") {
         s/(value=\"No\")/\1 checked/;
       } elsif ($studentAnswers{$key} ne Null) {
         s/name=/value=\"$studentAnswers{$key}\" name=/;
       }
		}
      if (/name=grade/) {
          print "<P>MultiChoice Grades: <input type=text value=$multichoice name=multichoice> points.<br>";
      }
		# it is tricky that No is in a separate line, need improvment
      if (/type=\"radio\"/ && /No<\/font/ && $correct{$key} eq "wrong") {
         $keymark= $key ."mark";
         s/No<\/font/No  <font color=red>Wrong! <input type=hidden name=$keymark value=\"wrong\"><\/font> <\/font/;
      }
		if (/type=submit/) {
		   # skeip submit and </form> tag, need to include multichoice input
		} else {
         print $_;
		}
   } elsif (/<TEXTAREA/i) {
      /name=\"([^"]+)\"/;
      $key = $1;
      $gradeKey=$1."grade";
      $commentKey=$1."comment";
      $key =~ tr/_/\./;
      #print "key=$key, answer=$studentAnswers{$key}<BR>\n";
      s/<\/tex/$studentAnswers{$key}<\/tex/;  # require </textarea> at the same line
      print $_;
      print "<P>grade (5pts):<input name=$gradeKey type=text value=5>";
      print "<P>comment<BR><textarea name=$commentKey cols=80 rows=10>$answers{$key}</textarea>";
   } elsif (/<\/body>/ || /<\/html>/ || /<\/form>/ ) {
	   # skip these add them after multichoice input tag
   } else {
      print $_;
   }
}
print "<p>No. of Multichoice questions  is $multichoice.<br>";
print "<p>Multichoice Grade is $multichoiceGrade.<br>";
print "<input type=hidden name=multichoicegrade value=$multichoiceGrade>\n";
print "<input type=submit name=submit value=submit>\n";
print "</form></body></html>";
close(EXAM);
