--- loncom/homework/grades.pm	2003/03/23 08:10:30	1.75
+++ loncom/homework/grades.pm	2003/05/30 21:20:20	1.91
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # The LON-CAPA Grading handler
 #
-# $Id: grades.pm,v 1.75 2003/03/23 08:10:30 albertel Exp $
+# $Id: grades.pm,v 1.91 2003/05/30 21:20:20 albertel Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -46,6 +46,9 @@ use Apache::lonhomework;
 use Apache::loncoursedata;
 use Apache::lonmsg qw(:user_normal_msg);
 use Apache::Constants qw(:common);
+use String::Similarity;
+
+my %oldessays=();
 
 # ----- These first few routines are general use routines.----
 #
@@ -113,7 +116,7 @@ sub response_type {
 #--- Dumps the class list with usernames,list of sections,
 #--- section, ids and fullnames for each user.
 sub getclasslist {
-    my ($getsec,$hideexpired) = @_;
+    my ($getsec,$filterlist) = @_;
     my $classlist=&Apache::loncoursedata::get_classlist();
     # Bail out if we were unable to get the classlist
     return if (! defined($classlist));
@@ -124,11 +127,13 @@ sub getclasslist {
         # the following undefs are for 'domain', and 'username' respectively.
 	my (undef,undef,$end,$start,$id,$section,$fullname,$status)=
             @{$classlist->{$_}};
-	# still a student?
-	if (($hideexpired) && ($status ne 'Active')) {
-            delete ($classlist->{$_});
-            next;
-        }
+	# filter students according to status selected
+	if ($filterlist && $ENV{'form.status'} ne 'Any') {
+	    if ($ENV{'form.status'} ne $status) {
+		delete ($classlist->{$_});
+		next;
+	    }
+	}
 	$section = ($section ne '' ? $section : 'no');
 	if ($getsec eq 'all' || $getsec eq $section) {
             $sections{$section}++;
@@ -209,8 +214,7 @@ sub jscriptNform {
     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
-	'<input type="hidden" name="lastCmd" value="'.$ENV{'form.lastCmd'}.'" />'."\n".
-	'<input type="hidden" name="lastSec" value="'.$ENV{'form.lastSec'}.'" />'."\n".
+	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n".
 	'<input type="hidden" name="probTitle" value="'.$ENV{'form.probTitle'}.'" />'."\n".
 	'<input type="hidden" name="command" value="submission" />'."\n".
 	'<input type="hidden" name="student" value="" />'."\n".
@@ -220,6 +224,50 @@ sub jscriptNform {
 }
 
 #------------------ End of general use routines --------------------
+
+#
+# Find most similar essay
+#
+
+sub most_similar {
+    my ($uname,$udom,$uessay)=@_;
+
+# ignore spaces and punctuation
+
+    $uessay=~s/\W+/ /gs;
+
+# these will be returned. Do not care if not at least 50 percent similar
+    my $limit=0.6;
+    my $sname='';
+    my $sdom='';
+    my $scrsid='';
+    my $sessay='';
+# go through all essays ...
+    foreach my $tkey (keys %oldessays) {
+	my ($tname,$tdom,$tcrsid)=split(/\./,$tkey);
+# ... except the same student
+        if (($tname ne $uname) || ($tdom ne $udom)) {
+	    my $tessay=$oldessays{$tkey};
+            $tessay=~s/\W+/ /gs;
+# String similarity gives up if not even limit
+            my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
+# Found one
+            if ($tsimilar>$limit) {
+		$limit=$tsimilar;
+                $sname=$tname;
+                $sdom=$tdom;
+                $scrsid=$tcrsid;
+                $sessay=$oldessays{$tkey};
+            }
+        } 
+    }
+    if ($limit>0.6) {
+       return ($sname,$sdom,$scrsid,$sessay,$limit);
+    } else {
+       return ('','','','',0);
+    }
+}
+
 #-------------------------------------------------------------------
 
 #------------------------------------ Receipt Verification Routines
@@ -297,9 +345,11 @@ sub listStudents {
 	    '<td><b>Type: </b>'.$responsetype.'</td>'.
 	    '<td><b>Handgrade: </b>'.$handgrade.'</font></td></tr>';
     }
-    $result.='</table>';
+    $result.='</table>'."\n";
 
     my $viewgrade = $ENV{'form.handgrade'} eq 'yes' ? 'View/Grade' : 'View';
+    $ENV{'form.probTitle'} = $ENV{'form.probTitle'} eq '' ? 
+	&Apache::lonnet::gettitle($symb) : $ENV{'form.probTitle'};
 
     $result='<h3><font color="#339933">&nbsp;'.
 	$viewgrade.
@@ -340,8 +390,8 @@ LISTJAVASCRIPT
     my $checklastsub = $ENV{'form.handgrade'} eq 'yes' ? '' : 'checked';
 
     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'."\n".
-	'&nbsp;<b>View Problem: </b><input type="radio" name="vProb" value="no" /> no '."\n".
-	'<input type="radio" name="vProb" value="yes" checked /> one student '."\n".
+	'&nbsp;<b>View Problem: </b><input type="radio" name="vProb" value="no" checked /> no '."\n".
+	'<input type="radio" name="vProb" value="yes" /> one student '."\n".
 	'<input type="radio" name="vProb" value="all" /> all students <br />'."\n".
 	'&nbsp;<b>Submissions: </b>'."\n";
     if ($ENV{'form.handgrade'} eq 'yes') {
@@ -355,8 +405,7 @@ LISTJAVASCRIPT
 	'<input type="hidden" name="response"    value="'.$ENV{'form.response'}.'" />'."\n".
 	'<input type="hidden" name="handgrade"   value="'.$ENV{'form.handgrade'}.'" /><br />'."\n".
 	'<input type="hidden" name="showgrading" value="'.$ENV{'form.showgrading'}.'" /><br />'."\n".
-	'<input type="hidden" name="lastCmd"     value="'.$ENV{'form.lastCmd'}.'" />'."\n".
-	'<input type="hidden" name="lastSec"     value="'.$ENV{'form.lastSec'}.'" />'."\n".
+	'<input type="hidden" name="saveState"   value="'.$ENV{'form.saveState'}.'" />'."\n".
 	'<input type="hidden" name="probTitle"   value="'.$ENV{'form.probTitle'}.'" />'."\n".
 	'<input type="hidden" name="url"  value="'.$url.'" />'."\n".
 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
@@ -368,7 +417,7 @@ LISTJAVASCRIPT
 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
 	'value="'.$viewgrade.'" />'."\n";
  
-    my (undef,undef,$fullname) = &getclasslist($getsec,'0');
+    my (undef,undef,$fullname) = &getclasslist($getsec,$ENV{'form.showgrading'} eq 'yes' ? '1' : '0');
     
     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
 	'<table border="0"><tr bgcolor="#e6ffff">'.
@@ -626,13 +675,13 @@ SUBJAVASCRIPT
 #--- javascript for essay type problem --
 sub sub_page_kw_js {
     my $request = shift;
+    my $iconpath = $request->dir_config('lonIconsURL');
     $request->print(<<SUBJAVASCRIPT);
 <script type="text/javascript" language="javascript">
 
 //===================== Show list of keywords ====================
   function keywords(keyform) {
-    var keywds = keyform.value;
-    var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",keywds);
+    var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",keyform.value);
     if (nret==null) return;
     keyform.value = nret;
 
@@ -674,6 +723,12 @@ sub sub_page_kw_js {
   }
 
 //====================== Script for composing message ==============
+   // preload images
+   img1 = new Image();
+   img1.src = "$iconpath/mailbkgrd.gif";
+   img2 = new Image();
+   img2.src = "$iconpath/mailto.gif";
+
   function msgCenter(msgform,usrctr,fullname) {
     var Nmsg  = msgform.savemsgN.value;
     savedMsgHeader(Nmsg,usrctr,fullname);
@@ -701,91 +756,102 @@ sub sub_page_kw_js {
     return;
   }
 
+//  var pWin = null;
   function savedMsgHeader(Nmsg,usrctr,fullname) {
-    var height = 50*Nmsg+250;
+    var height = 70*Nmsg+250;
     var scrollbar = "no";
     if (height > 600) {
 	height = 600;
 	scrollbar = "yes";
     }
-/*    if (window.pWin)
-	window.pWin.close(); */
+//    if (window.pWin) {window.pWin.close(); window.pWin=null}
     pWin = window.open('', 'MessageCenter', 'toolbar=no,location=no,scrollbars='+scrollbar+',screenx=70,screeny=75,width=600,height='+height);
-    pWin.document.write("<html><head>");
-    pWin.document.write("<title>Message Central</title>");
-
-    pWin.document.write("<script language=javascript>");
-    pWin.document.write("function checkInput() {");
-    pWin.document.write("  opener.document.SCORE.msgsub.value = document.msgcenter.msgsub.value;");
-    pWin.document.write("  var nmsg   = opener.document.SCORE.savemsgN.value;");
-    pWin.document.write("  var usrctr = document.msgcenter.usrctr.value;");
-    pWin.document.write("  var newval = eval(\\"opener.document.SCORE.newmsg\\"+usrctr);");
-    pWin.document.write("  newval.value = document.msgcenter.newmsg.value;");
-
-    pWin.document.write("  var msgchk = \\"\\";");
-    pWin.document.write("  if (document.msgcenter.subchk.checked) {");
-    pWin.document.write("     msgchk = \\"msgsub,\\";");
-    pWin.document.write("  }");
-    pWin.document.write(   "for (var i=1; i<=nmsg; i++) {");
-    pWin.document.write("      var opnmsg = eval(\\"opener.document.SCORE.savemsg\\"+i);");
-    pWin.document.write("      var frmmsg = eval(\\"document.msgcenter.msg\\"+i);");
-    pWin.document.write("      opnmsg.value = frmmsg.value;");
-    pWin.document.write("      var chkbox = eval(\\"document.msgcenter.msgn\\"+i);");
-    pWin.document.write("      if (chkbox.checked) {");
-    pWin.document.write("         msgchk += \\"savemsg\\"+i+\\",\\";");
-    pWin.document.write("      }");
-    pWin.document.write("  }");
-    pWin.document.write("  if (document.msgcenter.newmsgchk.checked) {");
-    pWin.document.write("     msgchk += \\"newmsg\\"+usrctr;");
-    pWin.document.write("  }");
-    pWin.document.write("  var includemsg = eval(\\"opener.document.SCORE.includemsg\\"+usrctr);");
-    pWin.document.write("  includemsg.value = msgchk;");
-
-    pWin.document.write("  self.close()");
-
-    pWin.document.write("}");
-
-    pWin.document.write("<");
-    pWin.document.write("/script>");
-
-    pWin.document.write("</head><body bgcolor=white>");
-
-    pWin.document.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
-    pWin.document.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
-    pWin.document.write("<font color=\\"green\\" size=+1>&nbsp;Compose Message for \"+fullname+\"</font><br><br>");
-
-    pWin.document.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
-    pWin.document.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
-    pWin.document.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
+    pWin.focus();
+    pDoc = pWin.document;
+    pDoc.write("<html><head>");
+    pDoc.write("<title>Message Central</title>");
+
+    pDoc.write("<script language=javascript>");
+    pDoc.write("function checkInput() {");
+    pDoc.write("  opener.document.SCORE.msgsub.value = document.msgcenter.msgsub.value;");
+    pDoc.write("  var nmsg   = opener.document.SCORE.savemsgN.value;");
+    pDoc.write("  var usrctr = document.msgcenter.usrctr.value;");
+    pDoc.write("  var newval = eval(\\"opener.document.SCORE.newmsg\\"+usrctr);");
+    pDoc.write("  newval.value = document.msgcenter.newmsg.value;");
+
+    pDoc.write("  var msgchk = \\"\\";");
+    pDoc.write("  if (document.msgcenter.subchk.checked) {");
+    pDoc.write("     msgchk = \\"msgsub,\\";");
+    pDoc.write("  }");
+    pDoc.write("  var includemsg = 0;");
+    pDoc.write("  for (var i=1; i<=nmsg; i++) {");
+    pDoc.write("      var opnmsg = eval(\\"opener.document.SCORE.savemsg\\"+i);");
+    pDoc.write("      var frmmsg = eval(\\"document.msgcenter.msg\\"+i);");
+    pDoc.write("      opnmsg.value = frmmsg.value;");
+    pDoc.write("      var chkbox = eval(\\"document.msgcenter.msgn\\"+i);");
+    pDoc.write("      if (chkbox.checked) {");
+    pDoc.write("         msgchk += \\"savemsg\\"+i+\\",\\";");
+    pDoc.write("         includemsg = 1;");
+    pDoc.write("      }");
+    pDoc.write("  }");
+    pDoc.write("  if (document.msgcenter.newmsgchk.checked) {");
+    pDoc.write("     msgchk += \\"newmsg\\"+usrctr;");
+    pDoc.write("     includemsg = 1;");
+    pDoc.write("  }");
+    pDoc.write("  imgformname = eval(\\"opener.document.SCORE.mailicon\\"+usrctr);");
+    pDoc.write("  imgformname.src = \\"$iconpath/\\"+((includemsg) ? \\"mailto.gif\\" : \\"mailbkgrd.gif\\");");
+    pDoc.write("  var includemsg = eval(\\"opener.document.SCORE.includemsg\\"+usrctr);");
+    pDoc.write("  includemsg.value = msgchk;");
+
+    pDoc.write("  self.close()");
+
+    pDoc.write("}");
+
+    pDoc.write("<");
+    pDoc.write("/script>");
+
+    pDoc.write("</head><body bgcolor=white>");
+
+    pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
+    pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
+    pDoc.write("<font color=\\"green\\" size=+1>&nbsp;Compose Message for \"+fullname+\"</font><br><br>");
+
+    pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
+    pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
+    pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
 }
     function displaySubject(msg,shwsel) {
-    pWin.document.write("<tr bgcolor=\\"#ffffdd\\">");
-    pWin.document.write("<td>Subject</td>");
-    pWin.document.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
-    pWin.document.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
+    pDoc = pWin.document;
+    pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
+    pDoc.write("<td>Subject</td>");
+    pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
+    pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
 }
 
   function displaySavedMsg(ctr,msg,shwsel) {
-    pWin.document.write("<tr bgcolor=\\"#ffffdd\\">");
-    pWin.document.write("<td align=\\"center\\">"+ctr+"</td>");
-    pWin.document.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
-    pWin.document.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
+    pDoc = pWin.document;
+    pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
+    pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
+    pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
+    pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
 }
 
   function newMsg(newmsg,shwsel) {
-    pWin.document.write("<tr bgcolor=\\"#ffffdd\\">");
-    pWin.document.write("<td align=\\"center\\">New</td>");
-    pWin.document.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
-    pWin.document.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
+    pDoc = pWin.document;
+    pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
+    pDoc.write("<td align=\\"center\\">New</td>");
+    pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
+    pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
 }
 
   function msgTail() {
-    pWin.document.write("</table>");
-    pWin.document.write("</td></tr></table>&nbsp;");
-    pWin.document.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
-    pWin.document.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br><br>");
-    pWin.document.write("</form>");
-    pWin.document.write("</body></html>");
+    pDoc = pWin.document;
+    pDoc.write("</table>");
+    pDoc.write("</td></tr></table>&nbsp;");
+    pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
+    pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br><br>");
+    pDoc.write("</form>");
+    pDoc.write("</body></html>");
 }
 
 //====================== Script for keyword highlight options ==============
@@ -819,65 +885,70 @@ sub sub_page_kw_js {
     return;
   }
 
-
+//  var hwdWin = null;
   function highlightCentral() {
+//    if (window.hwdWin) window.hwdWin.close();
     hwdWin = window.open('', 'KeywordHighlightCentral', 'toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx=100,screeny=75');
-    hwdWin.document.write("<html><head>");
-    hwdWin.document.write("<title>Highlight Central</title>");
-
-    hwdWin.document.write("<script language=javascript>");
-    hwdWin.document.write("function updateChoice(flag) {");
-    hwdWin.document.write("  opener.document.SCORE.kwclr.value = radioSelection(document.hlCenter.kwdclr);");
-    hwdWin.document.write("  opener.document.SCORE.kwsize.value = radioSelection(document.hlCenter.kwdsize);");
-    hwdWin.document.write("  opener.document.SCORE.kwstyle.value = radioSelection(document.hlCenter.kwdstyle);");
-    hwdWin.document.write("  opener.document.SCORE.refresh.value = \\"on\\";");
-    hwdWin.document.write("  if (opener.document.SCORE.keywords.value!=\\"\\"){");
-    hwdWin.document.write("     opener.document.SCORE.submit();");
-    hwdWin.document.write("  }");
-    hwdWin.document.write("  self.close()");
-    hwdWin.document.write("}");
-
-    hwdWin.document.write("function radioSelection(radioButton) {");
-    hwdWin.document.write("    var selection=null;");
-    hwdWin.document.write("    for (var i=0; i<radioButton.length; i++) {");
-    hwdWin.document.write("        if (radioButton[i].checked) {");
-    hwdWin.document.write("            selection=radioButton[i].value;");
-    hwdWin.document.write("            return selection;");
-    hwdWin.document.write("        }");
-    hwdWin.document.write("    }");
-    hwdWin.document.write("}");
-
-    hwdWin.document.write("<");
-    hwdWin.document.write("/script>");
-
-    hwdWin.document.write("</head><body bgcolor=white>");
-
-    hwdWin.document.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
-    hwdWin.document.write("<font color=\\"green\\" size=+1>&nbsp;Keyword Highlight Options</font><br><br>");
-
-    hwdWin.document.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
-    hwdWin.document.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
-    hwdWin.document.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
+    hwdWin.focus();
+    var hDoc = hwdWin.document;
+    hDoc.write("<html><head>");
+    hDoc.write("<title>Highlight Central</title>");
+
+    hDoc.write("<script language=javascript>");
+    hDoc.write("function updateChoice(flag) {");
+    hDoc.write("  opener.document.SCORE.kwclr.value = radioSelection(document.hlCenter.kwdclr);");
+    hDoc.write("  opener.document.SCORE.kwsize.value = radioSelection(document.hlCenter.kwdsize);");
+    hDoc.write("  opener.document.SCORE.kwstyle.value = radioSelection(document.hlCenter.kwdstyle);");
+    hDoc.write("  opener.document.SCORE.refresh.value = \\"on\\";");
+    hDoc.write("  if (opener.document.SCORE.keywords.value!=\\"\\"){");
+    hDoc.write("     opener.document.SCORE.submit();");
+    hDoc.write("  }");
+    hDoc.write("  self.close()");
+    hDoc.write("}");
+
+    hDoc.write("function radioSelection(radioButton) {");
+    hDoc.write("    var selection=null;");
+    hDoc.write("    for (var i=0; i<radioButton.length; i++) {");
+    hDoc.write("        if (radioButton[i].checked) {");
+    hDoc.write("            selection=radioButton[i].value;");
+    hDoc.write("            return selection;");
+    hDoc.write("        }");
+    hDoc.write("    }");
+    hDoc.write("}");
+
+    hDoc.write("<");
+    hDoc.write("/script>");
+
+    hDoc.write("</head><body bgcolor=white>");
+
+    hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
+    hDoc.write("<font color=\\"green\\" size=+1>&nbsp;Keyword Highlight Options</font><br><br>");
+
+    hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
+    hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
+    hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
   }
 
   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
-    hwdWin.document.write("<tr bgcolor=\\"#ffffdd\\">");
-    hwdWin.document.write("<td align=\\"left\\">");
-    hwdWin.document.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
-    hwdWin.document.write("<td align=\\"left\\">");
-    hwdWin.document.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
-    hwdWin.document.write("<td align=\\"left\\">");
-    hwdWin.document.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
-    hwdWin.document.write("</tr>");
+    var hDoc = hwdWin.document;
+    hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
+    hDoc.write("<td align=\\"left\\">");
+    hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
+    hDoc.write("<td align=\\"left\\">");
+    hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
+    hDoc.write("<td align=\\"left\\">");
+    hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
+    hDoc.write("</tr>");
   }
 
   function highlightend() { 
-    hwdWin.document.write("</table>");
-    hwdWin.document.write("</td></tr></table>&nbsp;");
-    hwdWin.document.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
-    hwdWin.document.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br><br>");
-    hwdWin.document.write("</form>");
-    hwdWin.document.write("</body></html>");
+    var hDoc = hwdWin.document;
+    hDoc.write("</table>");
+    hDoc.write("</td></tr></table>&nbsp;");
+    hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
+    hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br><br>");
+    hDoc.write("</form>");
+    hDoc.write("</body></html>");
   }
 
 </script>
@@ -985,6 +1056,9 @@ sub submission {
     if ($counter == 0) {
 	&sub_page_js($request);
 	&sub_page_kw_js($request);
+	$ENV{'form.probTitle'} = $ENV{'form.probTitle'} eq '' ? 
+	    &Apache::lonnet::gettitle($symb) : $ENV{'form.probTitle'};
+
 	$request->print('<h3>&nbsp;<font color="#339933">Submission Record</font></h3>'."\n".
 			'<font size=+1>&nbsp;<b>Problem: </b>'.$ENV{'form.probTitle'}.'</font>'."\n");
 
@@ -1015,8 +1089,7 @@ sub submission {
 
 	$request->print('<form action="/adm/grades" method="post" name="SCORE">'."\n".
 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
-			'<input type="hidden" name="lastCmd"    value="'.$ENV{'form.lastCmd'}.'" />'."\n".
-			'<input type="hidden" name="lastSec"    value="'.$ENV{'form.lastSec'}.'" />'."\n".
+			'<input type="hidden" name="saveState"  value="'.$ENV{'form.saveState'}.'" />'."\n".
 			'<input type="hidden" name="probTitle"  value="'.$ENV{'form.probTitle'}.'" />'."\n".
 			'<input type="hidden" name="refresh"    value="off" />'."\n".
 			'<input type="hidden" name="symb"       value="'.$symb.'" />'."\n".
@@ -1040,13 +1113,18 @@ sub submission {
 	my ($cts,$prnmsg) = (1,'');
 	while ($cts <= $ENV{'form.savemsgN'}) {
 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
-		($keyhash{$symb.'_savemsg'.$cts} eq '' ? $ENV{'form.savemsg'.$cts} : $keyhash{$symb.'_savemsg'.$cts}).
+		($keyhash{$symb.'_savemsg'.$cts} eq '' ? 
+		 &Apache::lonfeedback::clear_out_html($ENV{'form.savemsg'.$cts}) :
+		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
 		'" />'."\n";
 	    $cts++;
 	}
 	$request->print($prnmsg);
 
 	if ($ENV{'form.handgrade'} eq 'yes' && $ENV{'form.showgrading'} eq 'yes') {
+#
+# Print out the keyword options line
+#
 	    $request->print(<<KEYWORDS);
 &nbsp;<b>Keyword Options:</b>&nbsp;
 <a href="javascript:keywords(document.SCORE.keywords)"; TARGET=_self>List</a>&nbsp; &nbsp;
@@ -1054,6 +1132,14 @@ sub submission {
  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
 <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
 KEYWORDS
+#
+# Load the other essays for similarity check
+#
+            my $essayurl=&Apache::lonnet::declutter($url);
+	    my ($adom,$aname,$apath)=($essayurl=~/^(\w+)\/(\w+)\/(.*)$/);
+	    $apath=&Apache::lonnet::escape($apath);
+	    $apath=~s/\W/\_/gs;
+	    %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
         }
     }
 
@@ -1080,7 +1166,6 @@ KEYWORDS
     my @col_fullnames;
     my ($classlist,$fullname);
     if ($ENV{'form.handgrade'} eq 'yes') {
-	my @col_list;
 	($classlist,undef,$fullname) = &getclasslist('all','0');
 	for (keys (%$handgrade)) {
 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
@@ -1089,50 +1174,46 @@ KEYWORDS
 	    next if ($ncol <= 0);
             s/\_/\./g;
             next if ($record{'resource.'.$_.'.collaborators'} eq '');
-            my (@collaborators) = split(/,?\s+/,
-                                   $record{'resource.'.$_.'.collaborators'});
-            my (@badcollaborators);
-            if (scalar(@collaborators) != 0) {
+            my @goodcollaborators = ();
+            my @badcollaborators  = ();
+	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
+		$_ =~ s/[\$\^\(\)]//g;
+		next if ($_ eq '');
+		my ($co_name,$co_dom) = split /\@|:/,$_;
+		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
+		next if ($co_name eq $uname && $co_dom eq $udom);
+		# Doing this grep allows 'fuzzy' specification
+		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
+		if (! scalar(@Matches)) {
+		    push @badcollaborators,$_;
+		} else {
+		    push @goodcollaborators, @Matches;
+		}
+	    }
+            if (scalar(@goodcollaborators) != 0) {
                 $result.='<b>Collaborators: </b>';
-                foreach my $collaborator (@collaborators) {
-                    my ($co_name,$co_dom) = split /\@|:/,$collaborator;
-                    $co_dom = $udom if (! defined($co_dom));
-                    next if ($co_name eq $uname && $co_dom eq $udom);
-                    # Doing this grep allows 'fuzzy' specification
-                    my @Matches = grep /^$co_name:$co_dom/i,
-                    keys %$classlist;
-                    if (! scalar(@Matches)) {
-                        push @badcollaborators,$collaborator;
-                        next;
-                    }
-                    push @col_list, @Matches;
-                    foreach (@Matches) {
-                        my ($lastname,$givenn) = split(/,/,$$fullname{$_});
-                        push @col_fullnames, $givenn.' '.$lastname;
-                        $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
-                    }
-                }
+                foreach (@goodcollaborators) {
+		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
+		    push @col_fullnames, $givenn.' '.$lastname;
+		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
+		}
                 $result.='<br />'."\n";
-                if (scalar(@badcollaborators) > 0) {
-                    $result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
-                    $result.='This student has submitted ';
-                    if (scalar(@badcollaborators) == 1) {
-                        $result .= 'an invalid collaborator';
-                    } else {
-                        $result .= 'invalid collaborators';
-                    }
-                    $result .= ': '.join(', ',@badcollaborators);
-                    
-                }
-                if (scalar(@collaborators > $ncol)) {
-                    $result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
-                    $result .= 'This student has sumbitted too many '.
-                        'collaborators.  Maximum is '.$ncol;
-                    $result .= '</td></tr></table>';
-                }
-                $result.='<input type="hidden" name="collaborator'.$counter.
-                    '" value="'.(join ':',@col_list).'" />'."\n";
-            }
+		$result.='<input type="hidden" name="collaborator'.$counter.
+		    '" value="'.(join ':',@goodcollaborators).'" />'."\n";
+	    }
+	    if (scalar(@badcollaborators) > 0) {
+		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
+		$result.='This student has submitted ';
+		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
+		$result .= ': '.join(', ',@badcollaborators);
+		$result .= '</td></tr></table>';
+	    }         
+	    if (scalar(@badcollaborators > $ncol)) {
+		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
+		$result .= 'This student has submitted too many '.
+		    'collaborators.  Maximum is '.$ncol.'.';
+		$result .= '</td></tr></table>';
+	    }
 	}
     }
     $request->print($result."\n");
@@ -1166,6 +1247,15 @@ KEYWORDS
 			my ($partid,$respid) = /^resource\.(\d+)\.(\d+)\.submission/;
 			if ($part eq ($partid.'_'.$respid)) {
 			    my ($ressub,$subval) = split(/:/,$_,2);
+# Similarity check
+                            my $similar='';
+                            my ($oname,$odom,$ocrsid,$oessay,$osim)=&most_similar($uname,$udom,$subval);
+                            if ($osim) {
+				$osim=int($osim*100.0);
+				$similar='<hr /><h3><font color="#FF0000">Essay is '.$osim.'% similar to an essay by '.&Apache::loncommon::plainname($oname,$odom).
+                                '</font></h3><blockquote><i>'.
+                                &keywords_highlight($oessay).'</i></blockquote><hr />';
+                            }
 			    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part '.
 				$partid.'</b> <font color="#999999">( ID '.$respid.
 				' )</font>&nbsp; &nbsp;'.
@@ -1173,8 +1263,8 @@ KEYWORDS
                                 '<a href="'.
                                 &Apache::lonnet::tokenwrapper($record{"resource.$partid.$respid.uploadedurl"}).
    '"><img src="/adm/lonIcons/unknown.gif" border=0"> File uploaded by student</a> <font color="red" size="1">Like all files provided by users, this file may contain virusses</font><br />':'').
-                                '<b>Answer: </b>'.
-				&keywords_highlight($subval).'</td></tr>'."\n"
+                                '<b>Answer: </b><blockquote>'.
+				&keywords_highlight($subval).'</blockquote><br />&nbsp;'.$similar.'</td></tr>'."\n"
 				if ($ENV{'form.lastSub'} eq 'lastonly' || 
 				    ($ENV{'form.lastSub'} eq 'hdgrade' && 
 				     $$handgrade{$part} =~ /:yes$/));
@@ -1212,10 +1302,13 @@ KEYWORDS
 	my $lastone = pop @col_fullnames;
 	$msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
     }
+    $msgfor =~ s/\'/\\'/g; #' stupid emacs
     $result.='<tr><td bgcolor="#ffffff">'."\n".
 	'&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
 	',\''.$msgfor.'\')"; TARGET=_self>'.
-	'Compose Message to student'.(scalar(@col_fullnames) >= 1 ? 's' : '').'</a>'.
+	'Compose Message to student'.(scalar(@col_fullnames) >= 1 ? 's' : '').'</a> &nbsp;'.
+	'<img src="'.$request->dir_config('lonIconsURL').
+	'/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
 	'<br />&nbsp;(Message will be sent when you click on Save & Next below.)'."\n" 
 	if ($ENV{'form.handgrade'} eq 'yes');
     $request->print($result);
@@ -1329,12 +1422,11 @@ sub processHandGrade {
 	my $ctr = 0;
 	while ($ctr < $ngrade) {
 	    my ($uname,$udom) = split(/:/,$ENV{'form.unamedom'.$ctr});
-	    my ($errorflag) = &saveHandGrade($request,$url,$symb,$uname,$udom,$ctr);
+	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$url,$symb,$uname,$udom,$ctr);
 	    if ($errorflag eq 'no_score') {
 		$ctr++;
 		next;
 	    }
-
 	    my $includemsg = $ENV{'form.includemsg'.$ctr};
 	    my ($subject,$message,$msgstatus) = ('','','');
 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
@@ -1343,7 +1435,11 @@ sub processHandGrade {
 		foreach (@msgnum) {
 		    $message.=$ENV{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
 		}
-		#$message =~ s/\s+/ /g;
+		$message =&Apache::lonfeedback::clear_out_html($message);
+		$message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
+		$message.=" for <a href=\"".
+		    &Apache::lonnet::clutter($url).
+		    "?symb=$symb\">$ENV{'form.probTitle'}</a>";
 		$msgstatus = &Apache::lonmsg::user_normal_msg ($uname,$udom,
 							       $ENV{'form.msgsub'},$message);
 	    }
@@ -1404,12 +1500,20 @@ sub processHandGrade {
 	 $ENV{'course.'.$ENV{'request.course.id'}.'.num'});
 
     # Called by Save & Refresh from Highlight Attribute Window
+    my (undef,undef,$fullname) = &getclasslist($ENV{'form.section'},'0');
     if ($ENV{'form.refresh'} eq 'on') {
-	my $ctr = 0;
-	$ENV{'form.NTSTU'}=$ngrade;
+	my ($ctr,$total) = (0,0);
 	while ($ctr < $ngrade) {
-	    ($ENV{'form.student'},$ENV{'form.userdom'}) = split(/:/,$ENV{'form.unamedom'.$ctr});
-	    &submission($request,$ctr,$ngrade-1);
+	    $total++ if  $ENV{'form.unamedom'.$ctr} ne '';
+	    $ctr++;
+	}
+	$ENV{'form.NTSTU'}=$ngrade;
+	$ctr = 0;
+	while ($ctr < $total) {
+	    my $processUser = $ENV{'form.unamedom'.$ctr};
+	    ($ENV{'form.student'},$ENV{'form.userdom'}) = split(/:/,$processUser);
+	    $ENV{'form.fullname'} = $$fullname{$processUser};
+	    &submission($request,$ctr,$total-1);
 	    $ctr++;
 	}
 	return '';
@@ -1425,7 +1529,6 @@ sub processHandGrade {
 	$laststu = $firststu if ($ctr > $ngrade);
     }
 
-    my (undef,undef,$fullname) = &getclasslist($ENV{'form.section'},'0');
     my (@parsedlist,@nextlist);
     my ($nextflg) = 0;
     foreach (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
@@ -1481,8 +1584,9 @@ sub processHandGrade {
 #---- Save the score and award for each student, if changed
 sub saveHandGrade {
     my ($request,$url,$symb,$stuname,$domain,$newflg,$submitter) = @_;
-    my %record=&Apache::lonnet::restore($symb,$ENV{'request.course.id'},$domain,$stuname);
-    my %newrecord;
+    my %record     = &Apache::lonnet::restore($symb,$ENV{'request.course.id'},$domain,$stuname);
+    my %newrecord  = ();
+    my ($pts,$wgt) = ('','');
     foreach (split(/:/,$ENV{'form.partlist'.$newflg})) {
 	if ($ENV{'form.GD_SEL'.$newflg.'_'.$_} eq 'excused') {
 	    if ($record{'resource.'.$_.'.solved'} ne 'excused') {
@@ -1492,11 +1596,11 @@ sub saveHandGrade {
 		}
 	    }
 	} else {
-	    my $pts = ($ENV{'form.GD_BOX'.$newflg.'_'.$_} ne '' ? 
-		       $ENV{'form.GD_BOX'.$newflg.'_'.$_} : 
-		       $ENV{'form.RADVAL'.$newflg.'_'.$_});
+	    $pts = ($ENV{'form.GD_BOX'.$newflg.'_'.$_} ne '' ? 
+		    $ENV{'form.GD_BOX'.$newflg.'_'.$_} : 
+		    $ENV{'form.RADVAL'.$newflg.'_'.$_});
 	    return 'no_score' if ($pts eq '' && $ENV{'form.GD_SEL'.$newflg.'_'.$_} eq '');
-	    my $wgt = $ENV{'form.WGT'.$newflg.'_'.$_} eq '' ? 1 : 
+	    $wgt = $ENV{'form.WGT'.$newflg.'_'.$_} eq '' ? 1 : 
 		$ENV{'form.WGT'.$newflg.'_'.$_};
 	    my $partial= $pts/$wgt;
 	    $newrecord{'resource.'.$_.'.awarded'}  = $partial 
@@ -1519,7 +1623,7 @@ sub saveHandGrade {
 	&Apache::lonnet::cstore(\%newrecord,$symb,
 				$ENV{'request.course.id'},$domain,$stuname);
     }
-    return '';
+    return '',$pts,$wgt;
 }
 
 #--------------------------------------------------------------------------------------
@@ -1715,8 +1819,7 @@ sub viewgrades {
 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 	'<input type="hidden" name="command" value="editgrades" />'."\n".
 	'<input type="hidden" name="section" value="'.$ENV{'form.section'}.'" />'."\n".
-	'<input type="hidden" name="lastCmd" value="'.$ENV{'form.lastCmd'}.'" />'."\n".
-	'<input type="hidden" name="lastSec" value="'.$ENV{'form.lastSec'}.'" />'."\n".
+	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n".
 	'<input type="hidden" name="probTitle" value="'.$ENV{'form.probTitle'}.'" />'."\n";
 
     $result.='<h3>Assign Common Grade To ';
@@ -1807,10 +1910,11 @@ sub viewgrades {
 
     #get info for each student
     #list all the students - with points and grade status
-    my (undef,undef,$fullname) = &getclasslist($ENV{'form.section'},'0');
+    my (undef,undef,$fullname) = &getclasslist($ENV{'form.section'},'1');
     my $ctr = 0;
     foreach (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
-	my ($uname,$udom) = split(/:/);
+	my $uname = $_;
+	$uname=~s/:/_/;
 	$result.='<input type="hidden" name="ctr'.$ctr.'" value="'.$uname.'" />'."\n";
 	$result.=&viewstudentgrade($url,$symb,$ENV{'request.course.id'},
 				   $_,$$fullname{$_},\@parts,\%weight);
@@ -1828,6 +1932,7 @@ sub viewgrades {
 sub viewstudentgrade {
     my ($url,$symb,$courseid,$student,$fullname,$parts,$weight) = @_;
     my ($uname,$udom) = split(/:/,$student);
+    $student=~s/:/_/;
     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
     my $result='<tr bgcolor="#ffffdd"><td>'.
 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
@@ -1839,19 +1944,19 @@ sub viewstudentgrade {
 	if ($type eq 'awarded') {
 	    my $pts = $score eq '' ? '' : $score*$$weight{$part};
 	    $result.='<input type="hidden" name="'.
-		'GD_'.$uname.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
+		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
 	    $result.='<td align="middle"><input type="text" name="'.
-		'GD_'.$uname.'_'.$part.'_awarded" '.
-		'onChange="javascript:changeSelect(\''.$part.'\',\''.$uname.
+		'GD_'.$student.'_'.$part.'_awarded" '.
+		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
 	} elsif ($type eq 'solved') {
 	    my ($status,$foo)=split(/_/,$score,2);
 	    $status = 'nothing' if ($status eq '');
-	    $result.='<input type="hidden" name="'.'GD_'.$uname.'_'.
+	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
 		$part.'_solved_s" value="'.$status.'" />'."\n";
 	    $result.='<td align="middle"><select name="'.
-		'GD_'.$uname.'_'.$part.'_solved" '.
-		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$uname.'\')" >'."\n";
+		'GD_'.$student.'_'.$part.'_solved" '.
+		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
 	    my $optsel = '<option selected="on"> </option><option>excused</option>'."\n";
 	    $optsel = '<option> </option><option selected="on">excused</option>'."\n"
 		if ($status eq 'excused');
@@ -1859,10 +1964,10 @@ sub viewstudentgrade {
 	    $result.="</select></td>\n";
 	} else {
 	    $result.='<input type="hidden" name="'.
-		'GD_'.$uname.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
+		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
 		    "\n";
 	    $result.='<td align="middle"><input type="text" name="'.
-		'GD_'.$uname.'_'.$part.'_'.$type.'" '.
+		'GD_'.$student.'_'.$part.'_'.$type.'" '.
 		'value="'.$score.'" size="4" /></td>'."\n";
 	}
     }
@@ -1882,7 +1987,7 @@ sub editgrades {
     $title.='<font size=+1><b>Section: </b>'.$ENV{'form.section'}.'</font>'."\n";
     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
     $result.= '<table border="0"><tr bgcolor="#deffff">'.
-	'<td rowspan=2><b>Username</b></td><td rowspan=2><b>Fullname</b></td>'."\n";
+	'<td rowspan=2><b>Username</b></td><td rowspan=2><b>Domain</b></td><td rowspan=2><b>Fullname</b></td>'."\n";
 
     my %scoreptr = (
 		    'correct'  =>'correct_by_override',
@@ -1933,13 +2038,13 @@ sub editgrades {
 
     for ($i=0; $i<$ENV{'form.total'}; $i++) {
 	my $user = $ENV{'form.ctr'.$i};
+	my ($uname,$udom)=split(/:/,$user);
 	my %newrecord;
 	my $updateflag = 0;
-	my @userdom = grep /^$user:/,keys %$classlist;
-	my (undef,$udom) = split(/:/,$userdom[0]);
 
-	$result .= '<tr bgcolor="#ffffde"><td>'.$user.'&nbsp;</td><td>'.
-	    $$fullname{$userdom[0]}.'&nbsp;</td>';
+	$result .= '<tr bgcolor="#ffffde"><td>'.$uname.'&nbsp;</td><td>'.
+	    $udom.'&nbsp;</td><td>'.
+		$$fullname{$user}.'&nbsp;</td>';
 	foreach (@partid) {
 	    my $old_aw    = $ENV{'form.GD_'.$user.'_'.$_.'_awarded_s'};
 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
@@ -1990,7 +2095,7 @@ sub editgrades {
 	if ($updateflag) {
 	    $count++;
 	    &Apache::lonnet::cstore(\%newrecord,$symb,$ENV{'request.course.id'},
-				    $udom,$user);
+				    $udom,$uname);
 	}
     }
     $result .= '</table></td></tr></table>'."\n".
@@ -2018,48 +2123,6 @@ sub split_part_type {
 #
 #-------------------------- Next few routines handles grading by csv upload
 #
-#--- Menu to upload a csv scores ---
-sub upcsvScores_form {
-    my ($request) = shift;
-    my ($symb,$url)=&get_symb_and_url($request);
-    if (!$symb) {return '';}
-    my $result =<<CSVFORMJS;
-<script type="text/javascript" language="javascript">
-    function checkUpload(formname) {
-	if (formname.upfile.value == "") {
-	    alert("Please use the browse button to select a file from your local directory.");
-	    return false;
-	}
-	formname.submit();
-	if (navigator.appName !="Netscape") {self.close()}; //if netscape if appears to close before submit!!!
-	    // any suggestion how to get around this??
-    }
-    </script>
-CSVFORMJS
-    $ENV{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
-    $result.='<table width=100% border=0><tr><td bgcolor=#777777>'."\n";
-    $result.='<table width=100% border=0><tr bgcolor="#e6ffff"><td>'."\n";
-    $result.='&nbsp;<b>Specify a file containing the class scores for problem - '.$ENV{'form.probTitle'}.
-	'.</b></td></tr>'."\n";
-    $result.='<tr bgcolor=#ffffe6><td>'."\n";
-    my $upfile_select=&Apache::loncommon::upfile_select_html();
-    $result.=<<ENDUPFORM;
-<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload" target="LONcatInfo">
-<input type="hidden" name="symb" value="$symb" />
-<input type="hidden" name="url" value="$url" />
-<input type="hidden" name="command" value="csvuploadmap" />
-<input type="hidden" name="probTitle" value="$ENV{'form.probTitle'}" />
-$upfile_select
-<br /><input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scores" />&nbsp;
-<input type="button" value="Cancel" onClick="self.close()">
-
-</form>
-ENDUPFORM
-    $result.='</td></tr></table>'."\n";
-    $result.='</td></tr></table>'."\n";
-    return $result;
-}
-
 #--- Javascript to handle csv upload
 sub csvupload_javascript_reverse_associate {
   return(<<ENDPICK);
@@ -2175,8 +2238,7 @@ to this page if the data selected is ins
                                        value="$ENV{'form.upfile_associate'}" />
 <input type="hidden" name="symb"       value="$symb" />
 <input type="hidden" name="url"        value="$url" />
-<input type="hidden" name="lastCmd"    value="$ENV{'form.lastCmd'}" />
-<input type="hidden" name="lastSec"    value="$ENV{'form.lastSec'}" />
+<input type="hidden" name="saveState"  value="$ENV{'form.saveState'}" />
 <input type="hidden" name="probTitle"  value="$ENV{'form.probTitle'}" />
 <input type="hidden" name="command"    value="csvuploadassign" />
 <hr />
@@ -2214,6 +2276,48 @@ sub csvuploadmap_footer {
 ENDPICK
 }
 
+sub upcsvScores_form {
+    my ($request) = shift;
+    my ($symb,$url)=&get_symb_and_url($request);
+    if (!$symb) {return '';}
+    my $result =<<CSVFORMJS;
+<script type="text/javascript" language="javascript">
+    function checkUpload(formname) {
+	if (formname.upfile.value == "") {
+	    alert("Please use the browse button to select a file from your local directory.");
+	    return false;
+	}
+	formname.submit();
+    }
+    </script>
+CSVFORMJS
+    $ENV{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
+    $result.='<br /><table width=100% border=0><tr><td bgcolor="#777777">'."\n";
+    $result.='<table width=100% border=0><tr bgcolor="#e6ffff"><td>'."\n";
+    $result.='&nbsp;<b>Specify a file containing the class scores for problem - '.$ENV{'form.probTitle'}.
+	'.</b></td></tr>'."\n";
+    $result.='<tr bgcolor=#ffffe6><td>'."\n";
+    my $upfile_select=&Apache::loncommon::upfile_select_html();
+    $result.=<<ENDUPFORM;
+<form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload" target="LONcatInfo">
+<input type="hidden" name="symb" value="$symb" />
+<input type="hidden" name="url" value="$url" />
+<input type="hidden" name="command" value="csvuploadmap" />
+<input type="hidden" name="probTitle" value="$ENV{'form.probTitle'}" />
+<input type="hidden" name="saveState"  value="$ENV{'form.saveState'}" />
+$upfile_select
+<br /><input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scores" />
+
+</form>
+ENDUPFORM
+    $result.='</td></tr></table>'."\n";
+    $result.='</td></tr></table><br /><br />'."\n";
+    $result.=&show_grading_menu_form($symb,$url);
+
+    return $result;
+}
+
+
 sub csvuploadmap {
     my ($request)= @_;
     my ($symb,$url)=&get_symb_and_url($request);
@@ -2323,8 +2427,7 @@ sub pickStudentPage {
 <script type="text/javascript" language="javascript">
 
 function checkPickOne(formname) {
-    var user = radioSelection(formname.student);
-    if (user == null) {
+    if (radioSelection(formname.student) == null) {
 	alert("Please select the student you wish to grade.");
 	return;
     }
@@ -2336,20 +2439,28 @@ function checkPickOne(formname) {
 
 function radioSelection(radioButton) {
     var selection=null;
-    for (var i=0; i<radioButton.length; i++) {
-        if (radioButton[i].checked) {
-            return radioButton[i].value;
-        }
+    if (radioButton.length > 1) {
+	for (var i=0; i<radioButton.length; i++) {
+	    if (radioButton[i].checked) {
+		return radioButton[i].value;
+	    }
+	}
+    } else {
+	if (radioButton.checked) return radioButton.value;
     }
     return selection;
 }
-
+    
 function pullDownSelection(selectOne) {
-    var selection=null;
-    for (var i=0; i<selectOne.length; i++) {
-        if (selectOne[i].selected) {
-            return selectOne[i].value;
-        }
+    var selection="";
+    if (selectOne.length > 1) {
+	for (var i=0; i<selectOne.length; i++) {
+	    if (selectOne[i].selected) {
+		return selectOne[i].value;
+	    }
+	}
+    } else {
+	if (selectOne.selected) return selectOne.value;
     }
 }
 </script>
@@ -2363,7 +2474,7 @@ LISTJAVASCRIPT
     my $result='<h3><font color="#339933">&nbsp;'.
 	'Manual Grading by Page or Sequence</font></h3>';
 
-    $result.='<form action="/adm/grades" method="post" name="displayPage">'."<br>\n";
+    $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
     my ($titles,$symbx) = &getSymbMap($request);
     my ($curpage,$type,$mapId) = ($symb =~ /(.*?\.(page|sequence))___(\d+)___/); 
@@ -2397,16 +2508,15 @@ LISTJAVASCRIPT
     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
 	'<input type="hidden" name="command" value="displayPage" />'."\n".
 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
-	'<input type="hidden" name="symb"    value="'.$symb.'" />'."<br><br>\n".
-	'<input type="hidden" name="lastCmd" value="'.$ENV{'form.lastCmd'}.'" />'."\n".
-	'<input type="hidden" name="lastSec" value="'.$ENV{'form.lastSec'}.'" />'."\n";
+	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
+	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."<br />\n";
 
-    $result.='<br />&nbsp;<input type="button" '.
+    $result.='&nbsp;<input type="button" '.
 	'onClick="javascript:checkPickOne(this.form);"value="Submit" /><br />'."\n";
 
     $request->print($result);
 
-    my $studentTable.='&nbsp;<b>Select a Student you wish to grade</b><br>'.
+    my $studentTable.='&nbsp;<b>Select a student you wish to grade</b><br>'.
 	'<table border="0"><tr><td bgcolor="#777777">'.
 	'<table border="0"><tr bgcolor="#e6ffff">'.
 	'<td><b>&nbsp;Fullname <font color="#999999">(username)</font></b></td>'.
@@ -2414,7 +2524,7 @@ LISTJAVASCRIPT
 	'<td><b>&nbsp;Fullname <font color="#999999">(username)</font></b></td>'.
 	'<td><b>&nbsp;Fullname <font color="#999999">(username)</font></b></td></tr>';
  
-    my (undef,undef,$fullname) = &getclasslist($getsec,'0');
+    my (undef,undef,$fullname) = &getclasslist($getsec,'1');
     my $ptr = 1;
     foreach my $student (sort {lc($$fullname{$a}) cmp lc($$fullname{$b}) } keys %$fullname) {
 	my ($uname,$udom) = split(/:/,$student);
@@ -2439,8 +2549,7 @@ LISTJAVASCRIPT
 
 sub getSymbMap {
     my ($request) = @_;
-    my $navmap = Apache::lonnavmaps::navmap-> new($request,
-						  $ENV{'request.course.fn'}.'.db',
+    my $navmap = Apache::lonnavmaps::navmap-> new($ENV{'request.course.fn'}.'.db',
 						  $ENV{'request.course.fn'}.'_parms.db',1, 1);
 
     my $res = $navmap->firstResource(); # temp resource to access constants
@@ -2505,7 +2614,7 @@ sub displayPage {
     my $cnum      = $ENV{"course.$ENV{'request.course.id'}.num"};
     my $getsec    = $ENV{'form.section'} eq '' ? 'all' : $ENV{'form.section'};
     my $pageTitle = $ENV{'form.page'};
-    my (undef,undef,$fullname) = &getclasslist($getsec,'0');
+    my (undef,undef,$fullname) = &getclasslist($getsec,'1');
     my ($uname,$udom) = split(/:/,$ENV{'form.student'});
 
     my $result='<h3><font color="#339933">&nbsp;'.$ENV{'form.title'}.'</font></h3>';
@@ -2515,8 +2624,7 @@ sub displayPage {
     &sub_page_js($request);
     $request->print($result);
 
-    my $navmap = Apache::lonnavmaps::navmap-> new($request,
-						  $ENV{'request.course.fn'}.'.db',
+    my $navmap = Apache::lonnavmaps::navmap-> new($ENV{'request.course.fn'}.'.db',
 						  $ENV{'request.course.fn'}.'_parms.db',1, 1);
     my ($mapUrl, $id, $resUrl) = split(/___/, $ENV{'form.page'});
     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
@@ -2531,8 +2639,7 @@ sub displayPage {
 	'<input type="hidden" name="title"   value="'.$ENV{'form.title'}.'" />'."\n".
 	'<input type="hidden" name="url"     value="'.$url.'" />'."\n".
 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
-	'<input type="hidden" name="lastCmd" value="'.$ENV{'form.lastCmd'}.'" />'."\n".
-	'<input type="hidden" name="lastSec" value="'.$ENV{'form.lastSec'}.'" />'."\n";
+	'<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n";
 
     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
 	'/check.gif" height="16" border="0" />';
@@ -2553,7 +2660,6 @@ sub displayPage {
 
         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
 	    my $parts = $curRes->parts();
-	    $parts = &temp_parts_fix($parts); # remove line when lonnavmap is fixed
             my $title = $curRes->compTitle();
 	    my $symbx = $curRes->symb();
 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$question.
@@ -2564,8 +2670,8 @@ sub displayPage {
 	    } else {
 		my $companswer = &Apache::loncommon::get_student_answers(
 									 $symbx,$uname,$udom,$ENV{'request.course.id'});
-		$companswer=~s|<form(.*?)>||g;
-		$companswer=~s|</form>||g;
+		$companswer =~ s|<form(.*?)>||g;
+		$companswer =~ s|</form>||g;
 
 #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
 #		    $request->print('match='.$1.'<br>');
@@ -2594,11 +2700,16 @@ sub displayPage {
 			my @displaySub = ();
 			foreach my $partid (@{$parts}) {
 			    my @matchKey = grep /^resource\.$partid\..*?\.submission$/,@versionKeys;
+			    next if ($record{"$version:resource.$partid.solved"} eq '');
+#			    next if ($record{"$version:resource.$partid.award"} eq 'APPROX_ANS' && 
+#				     $record{"$version:resource.$partid.solved"} eq '');
 			    $displaySub[0].=(exists $record{$version.':'.$matchKey[0]}) ? 
-				'<b>Part:</b> '.$partid.'&nbsp;<b>Submission:</b>&nbsp;'
-				.$record{$version.':'.$matchKey[0]}.'<br />' : '';
+				'<b>Part&nbsp;'.$partid.'&nbsp;'.
+				($record{"$version:resource.$partid.tries"} eq '' ? 'Trial&nbsp;not&nbsp;counted' :
+				'Trial&nbsp;'.$record{"$version:resource.$partid.tries"}).'</b>&nbsp; '.
+				$record{$version.':'.$matchKey[0]}.'<br />' : '';
 			    $displaySub[1].=(exists $record{"$version:resource.$partid.award"}) ?
-				'<b>Part:</b> '.$partid.'&nbsp;'.
+				'<b>Part&nbsp;'.$partid.'</b> &nbsp;'.
 				$record{"$version:resource.$partid.award"}.'/'.
 				$record{"$version:resource.$partid.solved"}.'<br />' : '';
 			    $displaySub[2].=(exists $record{"$version:resource.$partid.regrader"}) ?
@@ -2641,18 +2752,6 @@ sub displayPage {
     return '';
 }
 
-sub temp_parts_fix { #remove sub once lonnavmap is fixed
-    my $parts = shift;
-    my %seen = ();
-    my @correctParts = ();
-    foreach (@{$parts}) {
-	next if ($seen{$_} > 0);
-	$seen{$_}++;
-	push @correctParts,$_;
-    }
-    return \@correctParts;
-}
-
 sub updateGradeByPage {
     my ($request) = shift;
 
@@ -2660,7 +2759,7 @@ sub updateGradeByPage {
     my $cnum      = $ENV{"course.$ENV{'request.course.id'}.num"};
     my $getsec    = $ENV{'form.section'} eq '' ? 'all' : $ENV{'form.section'};
     my $pageTitle = $ENV{'form.page'};
-    my (undef,undef,$fullname) = &getclasslist($getsec,'0');
+    my (undef,undef,$fullname) = &getclasslist($getsec,'1');
     my ($uname,$udom) = split(/:/,$ENV{'form.student'});
 
     my $result='<h3><font color="#339933">&nbsp;'.$ENV{'form.title'}.'</font></h3>';
@@ -2669,8 +2768,7 @@ sub updateGradeByPage {
 
     $request->print($result);
 
-    my $navmap = Apache::lonnavmaps::navmap-> new($request,
-						  $ENV{'request.course.fn'}.'.db',
+    my $navmap = Apache::lonnavmaps::navmap-> new($ENV{'request.course.fn'}.'.db',
 						  $ENV{'request.course.fn'}.'_parms.db',1, 1);
     my ($mapUrl, $id, $resUrl) = split(/___/, $ENV{'form.page'});
     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
@@ -2694,7 +2792,6 @@ sub updateGradeByPage {
 
         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
 	    my $parts = $curRes->parts();
-	    $parts = &temp_parts_fix($parts); # remove line when lonnavmap is fixed
             my $title = $curRes->compTitle();
 	    my $symbx = $curRes->symb();
 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$question.
@@ -2755,11 +2852,11 @@ sub updateGradeByPage {
     }
 
     $studentTable.='</td></tr></table></td></tr></table>';
-    $studentTable.=($changeflag == 0 ? 'No score was changed or updated.' :
-		    'The scores were changed for '.
-		    $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
     $studentTable.=&show_grading_menu_form($ENV{'form.symb'},$ENV{'form.url'});
-    $request->print($studentTable);
+    my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
+		  'The scores were changed for '.
+		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
+    $request->print($grademsg.$studentTable);
 
     return '';
 }
@@ -2772,6 +2869,15 @@ sub updateGradeByPage {
 #
 #------ start of section for handling grading by page/sequence ---------
 
+sub defaultFormData {
+    my ($symb,$url)=@_;
+    return '
+      <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
+     '<input type="hidden" name="url"     value="'.$url.'" />'."\n".
+     '<input type="hidden" name="saveState" value="'.$ENV{'form.saveState'}.'" />'."\n".
+     '<input type="hidden" name="probTitle" value="'.$ENV{'form.probTitle'}.'" />'."\n";
+}
+
 sub getSequenceDropDown {
     my ($request,$symb)=@_;
     my $result='<select name="selectpage">'."\n";
@@ -2789,17 +2895,47 @@ sub getSequenceDropDown {
     return $result;
 }
 
+sub scantron_uploads {
+    if (!-e $Apache::lonnet::perlvar{'lonScansDir'}) { return ''};
+    my $result=	'<select name="scantron_selectfile">';
+    opendir(DIR,$Apache::lonnet::perlvar{'lonScansDir'});
+    my @files=sort(readdir(DIR));
+    foreach my $filename (@files) {
+	if ($filename eq '.' or $filename eq '..') { next; }
+	$result.="<option>$filename</option>\n";
+    }
+    closedir(DIR);
+    $result.="</select>";
+    return $result;
+}
+
+sub scantron_scantab {
+    my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
+    my $result='<select name="scantron_format">'."\n";
+    foreach my $line (<$fh>) {
+	my ($name,$descrip)=split(/:/,$line);
+	if ($name =~ /^\#/) { next; }
+	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
+    }
+    $result.='</select>'."\n";
+
+    return $result;
+}
+
 sub scantron_selectphase {
     my ($r) = @_;
     my ($symb,$url)=&get_symb_and_url($r);
     if (!$symb) {return '';}
     my $sequence_selector=&getSequenceDropDown($r,$symb);
+    my $default_form_data=&defaultFormData($symb,$url);
+    my $grading_menu_button=&show_grading_menu_form($symb,$url);
+    my $file_selector=&scantron_uploads();
+    my $format_selector=&scantron_scantab();
     my $result;
     $result.= <<SCANTRONFORM;
-<form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
-  <input type="hidden" name="symb" value="$symb" />
-  <input type="hidden" name="url" value="$url" />
-  <input type="hidden" name="command" value="scantron_configphase" />
+<form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantro_process">
+  <input type="hidden" name="command" value="scantron_process" />
+  $default_form_data
   <table width="100%" border="0">
     <tr>
       <td bgcolor="#777777">
@@ -2816,12 +2952,12 @@ sub scantron_selectphase {
           </tr>
           <tr bgcolor="#ffffe6">
             <td>
-		<!-- FIXME I need to present a list of files from a specfic directory that has been configured, or any existing delay queues -->
-		Filename of scoring office file:
-		<select name="selectfile">
-		    <option value="filname1">filename1</option>
-		    <option value="filname2">filename2</option>
-		</select>
+		Filename of scoring office file: $file_selector
+	    </td>
+          </tr>
+          <tr bgcolor="#ffffe6">
+            <td>
+              Format of data file: $format_selector
 	    </td>
           </tr>
         </table>
@@ -2830,42 +2966,211 @@ sub scantron_selectphase {
   </table>
   <input type="submit" value="Submit" />
 </form>
+$grading_menu_button
 SCANTRONFORM
 
     return $result;
 }
 
-sub scantron_configphase {
-    my ($r) = @_;
-    my $sequence=$ENV{'form.selectpage'};
-    my $result;
-    $result.="got page $sequence";
-    $Apache::lonxml::debug=1;
-    &Apache::lonhomework::showhash(%ENV);
-    $Apache::lonxml::debug=0;
-    #FIXME Needs to present some lines from the file and allow the instructor to specify which columns represent what data, possibly have some nice defaults setup, probably should do a pass through all problems for a student to get an idea of how many questions there are, and homw many lines we'll have,
-    return $result;
+sub get_scantron_config {
+    my ($which) = @_;
+    my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
+    my %config;
+    foreach my $line (<$fh>) {
+	my ($name,$descrip)=split(/:/,$line);
+	if ($name ne $which ) { next; }
+	chomp($line);
+	my @config=split(/:/,$line);
+	$config{'name'}=$config[0];
+	$config{'description'}=$config[1];
+	$config{'CODElocation'}=$config[2];
+	$config{'CODEstart'}=$config[3];
+	$config{'CODElength'}=$config[4];
+	$config{'IDstart'}=$config[5];
+	$config{'IDlength'}=$config[6];
+	$config{'Qstart'}=$config[7];
+	$config{'Qlength'}=$config[8];
+	$config{'Qoff'}=$config[9];
+	$config{'Qon'}=$config[10];
+	last;
+    }
+    return %config;
+}
+
+sub username_to_idmap {
+    my ($classlist)= @_;
+    my %idmap;
+    foreach my $student (keys(%$classlist)) {
+	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
+	    $student;
+    }
+    return %idmap;
+}
+
+sub scantron_parse_scanline {
+    my ($line,$scantron_config)=@_;
+    my %record;
+    my $questions=substr($line,$$scantron_config{'Qstart'}-1);
+    my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
+    if ($$scantron_config{'CODElocation'} ne 0) {
+	if ($$scantron_config{'CODElocation'} < 0) {
+	    $record{'scantron.CODE'}=substr($data,$$scantron_config{'CODEstart'}-1,
+					    $$scantron_config{'CODElength'});
+	} else {
+	    #FIXME interpret first N questions
+	}
+    }
+    $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
+				  $$scantron_config{'IDlength'});
+    my @alphabet=('A'..'Z');
+    my $questnum=0;
+    while ($questions) {
+	$questnum++;
+	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
+	substr($questions,0,$$scantron_config{'Qlength'})='';
+	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
+	my (@array)=split(/$$scantron_config{'Qon'}/,$currentquest);
+	if (scalar(@array) gt 2) {
+	    #FIXME do something intelligent with double bubbles
+	    Apache->request->print("<br ><b>Wha!!!</b> <pre>".scalar(@array).
+				   '-'.$currentquest.'-'.$questnum.'</pre><br />');
+	}
+	if (length($array[0]) eq $$scantron_config{'Qlength'}) {
+	    $record{"scantron.$questnum.answer"}='';
+	} else {
+	    $record{"scantron.$questnum.answer"}=$alphabet[length($array[0])];
+	}
+    }
+    $record{'scantron.maxquest'}=$questnum;
+    return \%record;
+}
+
+sub scantron_add_delay {
+}
+
+sub scantron_find_student {
+    my ($scantron_record,$idmap)=@_;
+    my $scanID=$$scantron_record{'scantron.ID'};
+    foreach my $id (keys(%$idmap)) {
+	Apache->request->print('<pre>checking studnet -'.$id.'- againt -'.$scanID.'- </pre>');
+	if (lc($id) eq lc($scanID)) { Apache->request->print('success');return $$idmap{$id}; }
+    }
+    return undef;
+}
+
+sub scantron_filter {
+    my ($curres)=@_;
+    if (ref($curres) && $curres->is_problem() && !$curres->randomout) {
+	return 1;
+    }
+    return 0;
 }
 
 sub scantron_process_students {
+    my ($r) = @_;
+    my (undef,undef,$sequence)=split(/___/,$ENV{'form.selectpage'});
+    my ($symb,$url)=&get_symb_and_url($r);
+    if (!$symb) {return '';}
+    my $default_form_data=&defaultFormData($symb,$url);
+
+    my %scantron_config=&get_scantron_config($ENV{'form.scantron_format'});
+    my $scanlines=Apache::File->new($Apache::lonnet::perlvar{'lonScansDir'}."/$ENV{'form.scantron_selectfile'}");
+    my @scanlines=<$scanlines>;
+    my $classlist=&Apache::loncoursedata::get_classlist();
+    my %idmap=&username_to_idmap($classlist);
+    my $navmap=Apache::lonnavmaps::navmap->new($ENV{'request.course.fn'}.'.db',$ENV{'request.course.fn'}.'_parms.db',1, 1);
+    my $map=$navmap->getResourceByUrl($sequence);
+    my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
+    $r->print("geto ".scalar(@resources)."<br />");
+    my $result= <<SCANTRONFORM;
+<form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
+  <input type="hidden" name="command" value="scantron_configphase" />
+  $default_form_data
+SCANTRONFORM
+    $r->print($result);
+
+    my @delayqueue;
+    my $totalcorrect;
+    my $totalincorrect;
+
+    my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,
+	           'Scantron Status','Scantron Progress',scalar(@scanlines));
+    foreach my $line (@scanlines) {
+	my $studentcorrect;
+	my $studentincorrect;
+
+	chomp($line);
+	my $scan_record=&scantron_parse_scanline($line,\%scantron_config);
+	my ($uname,$udom);
+	if ($uname=&scantron_find_student($scan_record,\%idmap)) {
+	    &scantron_add_delay(\@delayqueue,$line,
+				'Unable to find a student that matches');
+	}
+	$r->print('<pre>doing studnet'.$uname.'</pre>');
+	($uname,$udom)=split(/:/,$uname);
+	&Apache::lonnet::delenv('form.counter');
+	&Apache::lonnet::appenv(%$scan_record);
+#    &Apache::lonhomework::showhash(%ENV);
+    $Apache::lonxml::debug=1;
+	&Apache::lonxml::debug("line is $line");
+	
+	    my $i=0;
+	foreach my $resource (@resources) {
+	    $i++;
+	    my $result=&Apache::lonnet::ssi($resource->src(),
+				 ('submitted'     =>'scantron',
+				  'grade_target'  =>'grade',
+				  'grade_username'=>$uname,
+				  'grade_domain'  =>$udom,
+				  'grade_courseid'=>$ENV{'request.course.id'},
+				  'grade_symb'    =>$resource->symb()));
+	    my %score=&Apache::lonnet::restore($resource->symb(),
+					       $ENV{'request.course.id'},
+					       $udom,$uname);
+	    foreach my $part ($resource->{PARTS}) {
+		if ($score{'resource.'.$part.'.solved'} =~ /^correct/) {
+		    $studentcorrect++;
+		    $totalcorrect++;
+		} else {
+		    $studentincorrect++;
+		    $totalincorrect++;
+		}
+	    }
+	    $r->print('<pre>'.
+		      $resource->symb().'-'.
+		      $resource->src().'-'.'</pre>result is'.$result);
+	    &Apache::lonhomework::showhash(%score);
+	#    if ($i eq 3) {last;}
+	}
+	&Apache::lonnet::delenv('form.counter');
+	&Apache::lonnet::delenv('scantron\.');
+	&Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
+             'last student Who got a '.$studentcorrect.' correct and '.
+	     $studentincorrect.' incorrect. The class has gotten '.
+             $totalcorrect.' correct and '.$totalincorrect.' incorrect');
+	last;
+	#FIXME
+	#get iterator for $sequence
+	#foreach question 'submit' the students answer to the server
+	#   through grade target {
+	#   generate data to pass back that includes grade recevied
+	#}
+    }
+    $Apache::lonxml::debug=0;
+    foreach my $delay (@delayqueue) {
+	#FIXME
+	#print out each delayed student with interface to select how
+	#  to repair student provided info
+	#Expected errors include
+	#  1 bad/no stuid/username
+	#  2 invalid bubblings
+	
+    }
     #FIXME
-    #   loop through students, {
-    #      Check if studnet info valid, if not add line to delay queue
-    #      foreach question 'submit' the students answer to the server
-    #             through grade target {
-    #         generate data to pass back that includes grade recevied
-    #      }
-    #   }
-    #   loop through delay queue {
-    #      print out each delayed student with interface to select how
-    #          to repair student provided info
-    #       Expected errors include
-    #           1 bad/no stuid/username
-    #           2 invalid bubblings
-    #   }
     # if delay queue exists 2 submits one to process delayed students one
     #     to ignore delayed students, possibly saving the delay queue for later
-
+    
+    $navmap->untieHashes();
 }
 #-------- end of section for handling grading scantron forms -------
 #
@@ -2880,39 +3185,39 @@ sub show_grading_menu_form {
     my $result.='<form action="/adm/grades" method="post">'."\n".
 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
 	'<input type="hidden" name="url" value="'.$url.'" />'."\n".
-	'<input type="hidden" name="lastCmd" value="'.$ENV{'form.lastCmd'}.'" />'."\n".
-	'<input type="hidden" name="lastSec" value="'.$ENV{'form.lastSec'}.'" />'."\n".
+	'<input type="hidden" name="saveState"  value="'.$ENV{'form.saveState'}.'" />'."\n".
 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
 	'</form>'."\n";
     return $result;
 }
 
+# -- Retrieve choices for grading form
+sub savedState {
+    my %savedState = ();
+    if ($ENV{'form.saveState'}) {
+	foreach (split(/:/,$ENV{'form.saveState'})) {
+	    my ($key,$value) = split(/=/,$_,2);
+	    $savedState{$key} = $value;
+	}
+    }
+    return \%savedState;
+}
+
 #--- Displays the main menu page -------
 sub gradingmenu {
     my ($request) = @_;
     my ($symb,$url)=&get_symb_and_url($request);
     if (!$symb) {return '';}
+    my $probTitle = &Apache::lonnet::gettitle($symb);
 
     $request->print(<<GRADINGMENUJS);
 <script type="text/javascript" language="javascript">
     function checkChoice(formname) {
 	var cmd = formname.command;
-	formname.lastCmd.value = radioSelection(formname.command);
-	formname.lastSec.value = pullDownSelection(formname.section);
-	if (cmd[0].checked || cmd[1].checked || cmd[2].checked || cmd[4].checked) {
-	    formname.submit();
-	}
-
-	if (cmd[3].checked) {
-	    var url = "/adm/grades?command=csvform&symb="+formname.symb.value+"&url="+formname.url.value;
-	    var options = "width=620,height=340,screenx=70,screeny=75,";
-	    options += "resizable=no,scrollbars=no,status=no,";
-	    options += "menubar=no,toolbar=no,location=no,directories=no";
-	    var newWin = window.open(url, "CSVFile", options);
-	    newWin.focus();
-	}
-
+	formname.saveState.value = "saveCmd="+radioSelection(cmd)+":saveSec="+pullDownSelection(formname.section)+
+	    ":saveSub="+radioSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.status);
+	if (cmd[0].checked || cmd[1].checked || cmd[2].checked || cmd[3].checked || cmd[4].checked) formname.submit();
 	if (cmd[5].checked) {
 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
 	    formname.submit();
@@ -2930,35 +3235,43 @@ sub gradingmenu {
 	    formname.receipt.focus();
 	    return false;
 	}
-	formname.command[4].checked = true;
+	formname.command[5].checked = true;
 	return true;
     }
 
     function radioSelection(radioButton) {
 	var selection=null;
-	for (var i=0; i<radioButton.length; i++) {
-	    if (radioButton[i].checked) {
-		return radioButton[i].value;
+	if (radioButton.length > 1) {
+	    for (var i=0; i<radioButton.length; i++) {
+		if (radioButton[i].checked) {
+		    return radioButton[i].value;
+		}
 	    }
+	} else {
+	    if (radioButton.checked) return radioButton.value;
 	}
 	return selection;
     }
 
     function pullDownSelection(selectOne) {
 	var selection="";
-	for (var i=0; i<selectOne.length; i++) {
-	    if (selectOne[i].selected) {
-		return selectOne[i].value;
+	if (selectOne.length > 1) {
+	    for (var i=0; i<selectOne.length; i++) {
+		if (selectOne[i].selected) {
+		    return selectOne[i].value;
+		}
 	    }
+	} else {
+	    if (selectOne.selected) return selectOne.value;
 	}
     }
+
 </script>
 GRADINGMENUJS
 
-    my $probTitle = &Apache::lonnet::gettitle($ENV{'form.url'});
     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>'.
 	'<table border="0">'.
-	'<tr><td colspan=3><font size=+1><b>Problem: </b>'.$probTitle.'</font></td></tr>';
+	'<tr><td colspan=3><font size=+1><b>Problem: </b>'.$probTitle.'</font></td></tr>'."\n";
     my ($partlist,$handgrade) = &response_type($url);
     my ($resptype,$hdgrade)=('','no');
     for (sort keys(%$handgrade)) {
@@ -2969,11 +3282,14 @@ GRADINGMENUJS
 	    '<td><b>Type: </b>'.$responsetype.'</td>'.
 	    '<td><b>Handgrade: </b>'.$handgrade.'</font></td></tr>';
     }
-    $result.='</table>';
+    $result.='</table>'."\n";
 
-    my ($classlist,$sections) = &getclasslist('all','0');
-    my $lastCmd = ($ENV{'form.lastCmd'} eq '' ? 'pickStudentPage' : $ENV{'form.lastCmd'});
-    my $lastSec = ($ENV{'form.lastSec'} eq '' ? 'all' : $ENV{'form.lastSec'});
+    my (undef,$sections) = &getclasslist('all','0');
+    my $savedState = &savedState();
+    my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'pickStudentPage' : $$savedState{'saveCmd'});
+    my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
+    my $saveSub = ($$savedState{'saveSub'} eq '' ? 'yes' : $$savedState{'saveSub'});
+    my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
 
     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
@@ -2981,8 +3297,7 @@ GRADINGMENUJS
 	'<input type="hidden" name="response"    value="'.$resptype.'" />'."\n".
 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
-	'<input type="hidden" name="lastCmd"     value="" />'."\n".
-	'<input type="hidden" name="lastSec"     value="" />'."\n".
+	'<input type="hidden" name="saveState"   value="" />'."\n".
 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
 
     $result.='<table width=100% border=0><tr><td bgcolor=#777777>'."\n".
@@ -2993,35 +3308,38 @@ GRADINGMENUJS
     $result.='<table width=100% border=0>'.
 	'<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
 	'<input type="radio" name="command" value="pickStudentPage" '.
-	($lastCmd eq 'pickStudentPage' ? 'checked' : '').'> '.
+	($saveCmd eq 'pickStudentPage' ? 'checked' : '').'> '.
 	'Handgrade/View Submission for a student by page/sequence</td></tr>'."\n".
 
 	'<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
 	'<input type="radio" name="command" value="viewgrades" '.
-	($lastCmd eq 'viewgrades' ? 'checked' : '').'> '.
+	($saveCmd eq 'viewgrades' ? 'checked' : '').'> '.
 	'Grade by section or class</td></tr>'."\n".
 
 	'<tr bgcolor="#ffffe6"valign="top"><td><input type="radio" name="command" value="submission" '.
-	($lastCmd eq 'submission' ? 'checked' : '').'> '.
+	($saveCmd eq 'submission' ? 'checked' : '').'> '.
 	($hdgrade eq 'yes' ? 'View/Grade essay response of' : 'View').
 	' an individual student </td>'."\n".
 	'<td>-->&nbsp;For students who has: '.
-	'<input type="radio" name="submitonly" value="yes" checked> submitted'.
-	'<input type="radio" name="submitonly" value="all"> everybody</td></tr>'."\n".
+	'<input type="radio" name="submitonly" value="yes" '.
+	($saveSub eq 'yes' ? 'checked' : '').' /> submitted'.
+	'<input type="radio" name="submitonly" value="all" '.
+	($saveSub eq 'all' ? 'checked' : '').' /> everybody</td></tr>'."\n".
 
 	'<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
-	'<input type="radio" name="command" value="csvupload" '.
-	($lastCmd eq 'csvupload' ? 'checked' : '').'> '.
+	'<input type="radio" name="command" value="csvform" '.
+	($saveCmd eq 'csvform' ? 'checked' : '').'> '.
 	'Upload scores from file</td></tr>'."\n";
 
     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
-	'<input type="radio" name="command" value="scantron_selectphase" /> '.
+	'<input type="radio" name="command" value="scantron_selectphase" '.
+	($saveCmd eq 'scantron_selectphase' ? 'checked="on"' : '').' /> '.
         'Grade scantron forms</td></tr>'."\n";
 
     if ((&Apache::lonnet::allowed('mgr',$ENV{'request.course.id'})) && ($symb)) {
 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
-	    '<input type="radio" name="command" value="verify" onSelect="javascript:this.form.receipt.focus()" '.
-	    ($lastCmd eq 'verify' ? 'checked' : '').'> '.
+	    '<input type="radio" name="command" value="verify" onChecked="javascript:this.form.receipt.focus()" '.
+	    ($saveCmd eq 'verify' ? 'checked' : '').'> '.
 	    'Verify a submission receipt issued by this server</td>'.
 	    '<td>-->&nbsp;Receipt no: '.unpack("%32C*",$Apache::lonnet::perlvar{'lonHostID'}).
 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')">'.
@@ -3029,13 +3347,21 @@ GRADINGMENUJS
     } 
 
     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2"><br />'."\n".
-	'&nbsp;Select section:</b> <select name="section">'."\n";
+	'&nbsp;Select section: <select name="section">'."\n";
     if (ref($sections)) {
 	foreach (sort (@$sections)) {$result.='<option value="'.$_.'" '.
-					 ($lastSec eq $_ ? 'selected="on"' : '').'>'.$_.'</option>'."\n";}
+					 ($saveSec eq $_ ? 'selected="on"' : '').'>'.$_.'</option>'."\n";}
     }
-    $result.= '<option value="all" '.($lastSec eq 'all' ? 'selected="on"' : ''). '>all</select> &nbsp; '.
-	'<font color="red">(Applies to the first three options only.)</font>'."\n";
+    $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</select> &nbsp; ';
+
+    $result.='Student Status:</b><select name="status">'.
+	'<option value="Active" '.($saveStatus eq 'Active' ? 'selected' : '').'>Active</option>'.
+	'<option value="Expired" '.($saveStatus eq 'Expired' ? 'selected' : '').'>Expired</option>'.
+	'<option value="Any" '.($saveStatus eq 'Any' ? 'selected' : '').'>Any</option>'.
+	'</select>';
+
+    $result.=' &nbsp; <font color="red">(Applies to the first three options only.)</font>'."\n";
+
     if (ref($sections)) {
 	$result.='&nbsp;(Section "no" implies the students were not assigned a section.)<br />' 
 	    if (grep /no/,@$sections);
@@ -3140,8 +3466,8 @@ sub handler {
 	    }
 	} elsif ($command eq 'scantron_selectphase') {
 	    $request->print(&scantron_selectphase($request));
-	} elsif ($command eq 'scantron_configphase') {
-	    $request->print(&scantron_configphase($request));
+	} elsif ($command eq 'scantron_process') {
+	    $request->print(&scantron_process_students($request));
 	} else {
 	    $request->print("Unknown action: $command:");
 	}