--- loncom/homework/rankresponse.pm	2003/03/19 14:23:38	1.4
+++ loncom/homework/rankresponse.pm	2016/01/22 22:42:51	1.73
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # rank style response
 #
-# $Id: rankresponse.pm,v 1.4 2003/03/19 14:23:38 sakharuk Exp $
+# $Id: rankresponse.pm,v 1.73 2016/01/22 22:42:51 damieng Exp $
 # Copyright Michigan State University Board of Trustees
 #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
@@ -24,12 +24,14 @@
 #
 # http://www.lon-capa.org/
 #
-# 2/21 Guy
 
 package Apache::rankresponse;
 use strict;
 use HTML::Entities();
-use Apache::optionresponse;
+use Apache::optionresponse();
+use Apache::lonlocal;
+use Apache::lonxml;
+use Apache::lonnet;
 
 BEGIN {
     &Apache::lonxml::register('Apache::rankresponse',('rankresponse'));
@@ -44,18 +46,22 @@ sub start_rankresponse {
     push (@Apache::lonxml::namespace,'rankresponse');
     my $id = &Apache::response::start_response($parstack,$safeeval);
     %Apache::hint::rank=();
+    undef(%Apache::response::foilnames);
     if ($target eq 'meta') {
 	$result=&Apache::response::meta_package_write('rankresponse');
     } elsif ($target eq 'edit' ) {
-	$result.=&Apache::edit::start_table($token).
-	    '<tr><td>'.&Apache::lonxml::description($token)."</td><td>Delete:".
-	    &Apache::edit::deletelist($target,$token)
-	    ."</td><td>&nbsp".&Apache::edit::end_row()
-	    .&Apache::edit::start_spanning_row();
+	$result.=&Apache::edit::start_table($token)
+           .'<tr><td>'.&Apache::loncommon::insert_folding_button()
+           .&Apache::lonxml::description($token).'</td>'
+           .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
+           .&Apache::edit::deletelist($target,$token)
+           .'</span></td>'
+           .'<td>&nbsp;'.&Apache::edit::end_row()
+           .&Apache::edit::start_spanning_row();
 	
 	$result.=
 	    &Apache::edit::text_arg('Max Number Of Shown Foils:','max',$token,'4').
-	    &Apache::edit::select_arg('Randomize Foil Order','randomize',
+	    &Apache::edit::select_arg('Randomize Foil Order:','randomize',
 				      ['yes','no'],$token).
 	    &Apache::edit::end_row().&Apache::edit::start_spanning_row()."\n";
     } elsif ($target eq 'modified') {
@@ -63,6 +69,12 @@ sub start_rankresponse {
 						     $safeeval,'max',
 						     'randomize');
 	if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
+    } elsif ($target eq 'analyze') {
+	my $part_id="$Apache::inputtags::part.$id";
+        $Apache::lonhomework::analyze{"$part_id.type"} = 'rankresponse';
+	push (@{ $Apache::lonhomework::analyze{"parts"} },$part_id);
+	push (@{ $Apache::lonhomework::analyze{"$part_id.bubble_lines"} }, 1);
+
     }
     return $result;
 }
@@ -75,6 +87,7 @@ sub end_rankresponse {
     pop @Apache::lonxml::namespace;
     &Apache::lonxml::deregister('Apache::rankresponse',
 				('foilgroup','foil','conceptgroup'));
+    undef(%Apache::response::foilnames);
     return $result;
 }
 
@@ -84,14 +97,15 @@ sub start_foilgroup {
     my $result;
     %Apache::response::foilgroup=();
     $Apache::rankresponse::conceptgroup=0;
-    &Apache::response::setrandomnumber();
+    &Apache::response::pushrandomnumber(undef,$target);
     return $result;
 }
 
 sub end_foilgroup {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result;
-    if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' || $target eq 'tex') {
+    if ($target eq 'grade' || $target eq 'web' || $target eq 'answer' ||
+	$target eq 'tex' || $target eq 'analyze') {
 	my $max = &Apache::lonxml::get_param('max',$parstack,$safeeval,'-2');
 	my $randomize = &Apache::lonxml::get_param('randomize',$parstack,
 						   $safeeval,'-2');
@@ -99,12 +113,39 @@ sub end_foilgroup {
 	if (!defined($tol)) { $tol=0; }
 	if ($target eq 'web' || $target eq 'tex') {
 	    $result=&displayfoils($target,$max,$randomize,$tol);
+	    $Apache::lonxml::post_evaluate=0;
 	} elsif ($target eq 'answer' ) {
 	    $result=&displayanswers($max,$randomize,$tol);
 	} elsif ( $target eq 'grade') {
 	    &grade_response($max,$randomize,$tol);
+	} elsif ( $target eq 'analyze') {
+	    my @shown = &whichfoils($max,$randomize);
+	    &Apache::response::analyze_store_foilgroup(\@shown,
+						  ['text','value','location']);
+	    my $part_id=
+		"$Apache::inputtags::part.$Apache::inputtags::response[-1]";
+	    $Apache::lonhomework::analyze{"$part_id.tol"}=$tol;
+	}
+	my $part = $Apache::inputtags::part;
+	my $id   = $Apache::inputtags::response[-1];
+        my ($numrows,$bubbles_per_row);
+        if (($target eq 'tex') && ($Apache::lonhomework::type eq 'exam')) {
+            my (@whichfoils)=&whichfoils($max,$randomize);
+            ($numrows,$bubbles_per_row) =
+                &Apache::optionresponse::getnumrows(scalar(@whichfoils));
+        }
+        if ($numrows < 1) {
+            $numrows = 1;
+        }
+        my $increment = &getfoilcounts($max) * $numrows;
+	&Apache::lonxml::increment_counter($increment,"$part.$id");
+	if ($target eq 'analyze') {
+	    &Apache::lonhomework::set_bubble_lines();
 	}
+    } elsif ($target eq 'edit') {
+	$result=&Apache::edit::end_table();
     }
+    &Apache::response::poprandomnumber();
     return $result;
 }
 
@@ -118,7 +159,7 @@ sub get_correct_order {
     }
     @value_names =
 	sort {
-	    if (abs($a->[0] - $b->[0]) > $tol) {return ($a->[0] cmp $b->[0]);}
+	    if (abs($a->[0] - $b->[0]) > $tol) {return ($a->[0] <=> $b->[0]);}
 	    return 0;
 	} @value_names;
     my @value_names_tmp=@value_names;
@@ -146,21 +187,37 @@ sub get_correct_order {
 
 sub displayanswers {
     my ($max,$randomize,$tol,@opt)=@_;
-    if (!defined(@{ $Apache::response::foilgroup{'names'} })) { return; }
-    my @names = @{ $Apache::response::foilgroup{'names'} };
+    my @names;
+    if (ref($Apache::response::foilgroup{'names'}) eq 'ARRAY') {
+        @names = @{ $Apache::response::foilgroup{'names'} };
+    }
+    return if (!@names);
     my @whichfoils = &whichfoils($max,$randomize);
-    my $result=&Apache::response::answer_header('rankresponse');
     my @correctorder=&get_correct_order($tol,@whichfoils);
-    foreach my $order (@correctorder) {
-	$result.=&Apache::response::answer_part('rankresponse',$order);
+    my $result;
+    if ($Apache::lonhomework::type eq 'exam') {
+	my @alphabet = ('A'..'Z');
+	my $i=0;
+	foreach my $order (@correctorder) {
+	    $result.=&Apache::response::answer_header('rankresponse',$i++);
+	    $result.=&Apache::response::answer_part('rankresponse',
+						    $alphabet[$order-1]);
+	    $result.=&Apache::response::answer_part('rankresponse',$order);
+	    $result.=&Apache::response::answer_footer('rankresponse');
+	}
+    } else {
+	$result=&Apache::response::answer_header('rankresponse');
+	foreach my $order (@correctorder) {
+	    $result.=&Apache::response::answer_part('rankresponse',$order);
+	}
+	$result.=&Apache::response::answer_footer('rankresponse');
     }
-    $result.=&Apache::response::answer_footer('rankresponse');
     return $result;
 }
 
 sub check_response_order {
     my (%responsehash)=@_;
-    my @order=sort(values(%responsehash));
+    my @order=sort( {$a <=> $b} values(%responsehash));
     my $lastvalue=0;
     my $expected=1;
     my $malformed=0;
@@ -178,16 +235,42 @@ sub check_response_order {
 sub grade_response {
     my ($max,$randomize,$tol)=@_;
     my (@whichfoils)=&whichfoils($max,$randomize);
-    if (!defined($ENV{'form.submitted'})) { return; }
+    if (!&Apache::response::submitted()) { return; }
     my %responsehash;
     my %grade;
-    my ($temp,$right,$wrong,$ignored)=(0,0,0,0);
+    my ($temp,$right,$wrong,$ignored)=(1,0,0,0);
     my @correctorder=&get_correct_order($tol,@whichfoils);
+    my ($numrows,$bubbles_per_row);
+    if ($Apache::lonhomework::scantronmode) {
+        my $numitems = scalar(@whichfoils);
+        ($numrows,$bubbles_per_row) =
+            &Apache::optionresponse::getnumrows($numitems);
+    }
+    if ($numrows < 1) {
+        $numrows = 1;
+    }
+
     foreach my $name (@whichfoils) {
-	my $response = $ENV{'form.HWVAL_'.$Apache::inputtags::response['-1'].":$temp"};
-	$responsehash{$name}=$response;
+        my $response;
+        if ($numrows > 1) {
+            my $num = $temp;
+            my $totalnum;
+            for (my $i=0; $i<$numrows; $i++) {
+                my $item = &Apache::response::getresponse($num,'A is 1');
+                if ($item =~ /^\d+$/) {
+                    $totalnum = $i*$bubbles_per_row + $item;
+                }
+                $num ++;
+            }
+            $response = $totalnum;
+            $temp += $numrows;
+        } else {
+            $response = &Apache::response::getresponse($temp,'A is 1');
+            $temp ++;
+        }
 	my $value=shift(@correctorder);
 	if ( $response =~ /[^\s]/) {
+	    $responsehash{$name}=$response;
 	    &Apache::lonxml::debug("submitted a $response for $value<br />\n");
 	    if ($value eq $response) {
 		$grade{$name}='1'; $right++;
@@ -197,7 +280,6 @@ sub grade_response {
 	} else {
 	    $ignored++;
 	}
-	$temp++;
     }
     my $malformed=&check_response_order(%responsehash);
     my $part=$Apache::inputtags::part;
@@ -221,13 +303,51 @@ sub grade_response {
 	    $ad='MISSING_ANSWER';
 	}
     }
+    if (($ad eq 'INCORRECT' || $ad eq 'EXACT_ANS')) {
+        if ($Apache::lonhomework::type eq 'survey') {
+            $ad='SUBMITTED';
+        } elsif ($Apache::lonhomework::type eq 'surveycred') {
+	    $ad='SUBMITTED_CREDIT';
+        } elsif ($Apache::lonhomework::type eq 'anonsurvey') {
+            $ad='ANONYMOUS';
+        } elsif ($Apache::lonhomework::type eq 'anonsurveycred') {
+            $ad='ANONYMOUS_CREDIT';
+        } else {
+            $Apache::lonhomework::results{"resource.$part.$id.submissiongrading"}=$gradestr;
+        }
+    } else {
+	$Apache::lonhomework::results{"resource.$part.$id.submissiongrading"}=$gradestr;
+    }
+    if ($Apache::lonhomework::type eq 'randomizetry') {
+        if ($Apache::lonhomework::type eq 'randomizetry') {
+            $Apache::lonhomework::results{"resource.$part.$id.foilorder"} = &Apache::lonnet::array2str(@whichfoils);
+        }
+    }
     $Apache::lonhomework::results{"resource.$part.$id.submission"}=
 	$responsestr;
-    $Apache::lonhomework::results{"resource.$part.$id.submissiongrading"}=$gradestr;
     $Apache::lonhomework::results{"resource.$part.$id.awarddetail"}=$ad;
     &Apache::response::handle_previous(\%previous,$ad);
 }
 
+sub format_prior_answer {
+    my ($mode,$answer,$other_data) = @_;
+    my %lastresponse=&Apache::lonnet::str2hash($answer);
+    my $foil_order  =$other_data->[0];
+    my %grading     =&Apache::lonnet::str2hash($other_data->[1]);
+    my $output;
+    foreach my $name (@{ $foil_order }) {
+        if (defined($lastresponse{$name})) {
+            $output .= '<tr><td>'.&HTML::Entities::encode($lastresponse{$name},'<>&"').'</td></tr>';
+        } else {
+            $output .= '<tr><td>&nbsp;</td></tr>';
+        }
+    }
+    return if (!defined($output));
+    $output =
+	'<table class="LC_prior_rank">'.$output.'</table>';
+    return $output;
+}
+
 sub displayfoils {
     my ($target,$max,$randomize,$tol)=@_;
     my $result;
@@ -235,60 +355,150 @@ sub displayfoils {
     my (@whichfoils)=&whichfoils($max,$randomize);
     my $part=$Apache::inputtags::part;
     my $solved=$Apache::lonhomework::history{"resource.$part.solved"};
-    my $status=$Apache::inputtags::status[-1];
     my @whichopt=(1..($#whichfoils+1));
     my @correctorder=&get_correct_order($tol,@whichfoils);
-    if (($solved =~ /^correct/) || ($status eq  'SHOW_ANSWER')) {
+    if ( &Apache::response::show_answer() && ($target ne 'tex')) {
 	foreach my $name (@whichfoils) {
 	    my $text=$Apache::response::foilgroup{$name.'.text'};
 	    my $value=shift(@correctorder);
-	    $result.='<br />'.$value.':'.$text;
+	    if ($target eq 'web') {
+		$result.='<div class="LC_rankfoil"><b>'.$value.':</b> '.$text.'</div>';
+	    } else {
+		$result.=' \strut\\\\\strut '.$value.':'.$text;
+	    }
 	}
     } else {
 	my $i = 0;
-	my $temp=0;
+	my $temp=1;
 	my $id=$Apache::inputtags::response[-1];
 	my $part=$Apache::inputtags::part;
-	my $lastresponse=$Apache::lonhomework::history{"resource.$part.$id.submission"};
-	my %lastresponse=&Apache::lonnet::str2hash($lastresponse);
-	foreach my $name (@whichfoils) {
+        my ($lastresponse,$newvariation);
+        if ((($Apache::lonhomework::history{"resource.$part.type"} eq 'randomizetry') ||
+             ($Apache::lonhomework::type eq 'randomizetry')) &&
+        ($Apache::inputtags::status[-1] eq 'CAN_ANSWER')) {
+            if ($env{'form.'.$part.'.rndseed'} ne
+                $Apache::lonhomework::history{"resource.$part.rndseed"}) {
+                $newvariation = 1;
+            }
+        }
+        unless ($newvariation) {
+            if ((($env{'form.grade_username'} eq '') && ($env{'form.grade_domain'} eq '')) ||
+                (($env{'form.grade_username'} eq $env{'user.name'}) &&
+                 ($env{'form.grade_domain'} eq $env{'user.domain'}))) {
+                $lastresponse=$Apache::lonhomework::history{"resource.$part.$id.submission"};
+            } else {
+                unless (($Apache::lonhomework::history{"resource.$part.type"} eq 'anonsurvey') ||
+                        ($Apache::lonhomework::history{"resource.$part.type"} eq 'anonsurveycred')) {
+                    $lastresponse=$Apache::lonhomework::history{"resource.$part.$id.submission"};
+                }
+            }
+        }
+	my %lastresponse=&Apache::lonnet::str2hash($lastresponse); 
+	my @alp = splice @alphabet, 0, $#whichopt + 1;
+	my $internal_counter=$Apache::lonxml::counter;
+        my ($numrows,$bubbles_per_row);
+        if (($target eq 'tex') && ($Apache::lonhomework::type eq 'exam')) {
+            ($numrows,$bubbles_per_row) = 
+                &Apache::optionresponse::getnumrows(scalar(@alp));
+        } else {
+            $numrows = 1;
+        }
+        if($target eq 'tex' && $env{'form.pdfFormFields'} eq 'yes') {
+            $result .= '\strut \\\\ \strut \\\\' ;
+        }
+        foreach my $name (@whichfoils) {
 	    my $lastopt=$lastresponse{$name};
 	    my $optionlist='';
-	    if ($target ne 'tex') {$optionlist="<option></option>\n";}
+	    if ($target ne 'tex') {
+                $optionlist = "<option></option>\n";
+            } 
+            if ($target eq 'tex' && $env{'form.pdfFormFields'} eq 'yes') {
+                my $fieldname = $env{'request.symb'}.'&part_'.$Apache::inputtags::part.'&rankresponse'.'&HWVAL_'.$Apache::inputtags::response['-1'].':'.$temp;
+                $optionlist =  &Apache::lonxml::print_pdf_start_combobox($fieldname);
+            }
 	    my $option;
 	    foreach $option (@whichopt) {
 		if ($option eq $lastopt) {
-		    if ($target ne 'tex') {$optionlist.="<option selected=\"on\">$option</option>\n";}
+		    if ($target ne 'tex' ) {
+                        $optionlist.="<option selected=\"selected\">$option</option>\n";
+                    } elsif ($target eq 'tex' && $env{'form.pdfFormFields'} eq 'yes') {
+                        $optionlist .= &Apache::lonxml::print_pdf_add_combobox_option($option); 
+                    }
 		} else {
-		    if ($target ne 'tex') {$optionlist.="<option>$option</option>\n";}
-		}
+		    if ($target ne 'tex') {
+                        $optionlist.="<option>$option</option>\n";
+                    } elsif ($target eq 'tex' && $env{'form.pdfFormFields'} eq 'yes') {
+                        $optionlist .= &Apache::lonxml::print_pdf_add_combobox_option($option); 
+                    }
+		} 
 	    }
-	    if ($target ne 'tex') {
-		$optionlist='<select name="HWVAL_'.
+	    if ($target ne 'tex' && $Apache::lonhomework::type ne 'exam') {
+		$optionlist='<select onchange="javascript:setSubmittedPart(\''.
+		  $part.'\');" name="HWVAL_'.
 		    $Apache::inputtags::response[-1].':'.$temp.'">'.
 		        $optionlist."</select>\n";
-	    } else {
+	    } elsif ($env{'form.pdfFormFields'} eq 'yes') {
+                #do nothing
+            } else {
 		$optionlist=' '.$temp.' '.$optionlist.' ';
 	    }
 	    my $text=$Apache::response::foilgroup{$name.'.text'};
 	    if ($target ne 'tex') {
-		$result.='<br />'.$optionlist.$text."\n";
+                $result .= '<div class="LC_rankfoil">';
+		if ($Apache::lonhomework::type ne 'exam') {
+		    $result.=$optionlist.$text."\n";
+		} else {
+		    $result.=$text."\n";
+		}
 		if ($Apache::lonhomework::type eq 'exam') {
-		    $result.=&Apache::optionresponse::webbubbles(\@alphabet,\@whichopt);
+		    my @values=(1..scalar(@whichopt));
+		    $result.=&Apache::optionresponse::webbubbles(\@values,\@whichopt,$temp,$lastopt);
 		}
+                $result .= '</div>';
 	    } else {
 		if ($Apache::lonhomework::type eq 'exam') {
-		    $result.=' \framebox[5 mm][s]{\tiny\strut} '.$text."\n";
-		    $result.='\begin{enumerate}\item[\textbf{'.$Apache::lonxml::counter.'}.]'.&Apache::optionresponse::bubbles(\@alphabet,\@whichopt).'\end{enumerate}\strut ';
-		    &Apache::lonxml::increment_counter();
+                    my $itemlabel;
+                    if ($numrows == 1) {
+                        $itemlabel = '\item[\textbf{'.$internal_counter.'}]';
+                    } else {
+                        my $linetext;
+                        for (my $i=0; $i<$numrows; $i++) {
+                            $linetext .= $internal_counter+$i.', ';
+                        }
+                        $linetext =~ s/,\s$//;
+                        $itemlabel = '\item[\small {\textbf{'.$linetext.'}}]'.
+                                     ' {\footnotesize '.
+                                     &mt('(Bubble once in [_1] lines)',$numrows).
+                                     '} \hspace*{\fill} \\\\';
+                    }
+		    $result .= '\vskip 0 mm '.$text.' \vskip 0 mm '."\n";
+		    $result .= '\vskip -1 mm';
+                    $result .= '\begin{enumerate}'.$itemlabel;
+		    $result .= &Apache::optionresponse::bubbles(\@alp,\@whichopt,'rankresponse',undef,$numrows,$bubbles_per_row,$internal_counter);
+                    $result .= '\end{enumerate} \vskip -8 mm \strut ';
+		    $internal_counter += $numrows;
 		} else {
-		$result.=' \\\\ \framebox[5 mm][s]{\tiny\strut} '.$text."\n";
+                    if($env{'form.pdfFormFields'} ne 'yes') {
+		        $result.=' \vskip 0mm \framebox[5 mm][s]{\tiny\strut} '.$text."\n";
+                    } else {
+                        $result.= $optionlist.' '. &Apache::lonxml::print_pdf_end_combobox($text).'\strut \\\\';
+                    }
 		}
 	    }
 	    $temp++;
 	}
     }
-    if ($target ne 'tex') {$result.="<br />";} else {$result.=' \\\\ ';}
+    if ($target eq 'web') {
+        my $questiontype;
+        if ($Apache::lonhomework::type eq 'randomizetry') {
+            $questiontype = $Apache::lonhomework::type;
+        }
+	&Apache::response::setup_prior_tries_hash(\&format_prior_answer,
+						  [\@whichfoils,
+						   'submissiongrading'],
+                                                  $questiontype);
+    }
+    if ($target ne 'tex') {$result.="<br />";} else {$result.=' \vskip 0 mm ';}
     return $result;
 }
 
@@ -304,52 +514,9 @@ sub getfoilcounts {
 
 sub whichfoils {
     my ($max,$randomize)=@_;
-    $max = &getfoilcounts($max);
- #   &Apache::lonxml::debug("man $max randomize $randomize");
-    if (!defined(@{ $Apache::response::foilgroup{'names'} })) { return; }
-    my @names = @{ $Apache::response::foilgroup{'names'} };
-    my @whichopt =();
-    my (%top,@toplist,%bottom,@bottomlist);
-    if (!(&Apache::response::showallfoils() || ($randomize eq 'no'))) {
-	my $current=0;
-	foreach my $name (@names) {
-	    $current++;
-	    if ($Apache::response::foilgroup{"$name.location"} eq 'top') {
-		$top{$name}=$current;
-	    } elsif ($Apache::response::foilgroup{"$name.location"} eq
-		     'bottom') {
-		$bottom{$name}=$current;
-	    }
-	}
-    }
-    while ((($#whichopt+1) < $max) && ($#names > -1)) {
-#	&Apache::lonxml::debug("Have $#whichopt max is $max");
-	my $aopt;
-	if (&Apache::response::showallfoils() || ($randomize eq 'no')) {
-	    $aopt=0;
-	} else {
-	    $aopt=int(&Math::Random::random_uniform() * ($#names+1));
-	}
-#	&Apache::lonxml::debug("From $#whichopt $max $#names elms, picking $aopt");
-	$aopt=splice(@names,$aopt,1);
-#	&Apache::lonxml::debug("Picked $aopt");
-	if ($top{$aopt}) {
-	    $toplist[$top{$aopt}]=$aopt;
-	} elsif ($bottom{$aopt}) {
-	    $bottomlist[$bottom{$aopt}]=$aopt;
-	} else {
-	    push (@whichopt,$aopt);
-	}
-    }
-#    &Apache::lonxml::debug("Grr, ".$#whichopt.":".$#toplist.':'.$#bottomlist);
-    for (my $i=0;$i<=$#toplist;$i++) {
-	if ($toplist[$i]) { unshift(@whichopt,$toplist[$i]) }
-    }
-    for (my $i=0;$i<=$#bottomlist;$i++) {
-	if ($bottomlist[$i]) { push(@whichopt,$bottomlist[$i]) }
-    }
-    &Apache::lonxml::debug("Grr, ".$#whichopt.":".$#toplist.':'.$#bottomlist);
-    return @whichopt;
+    return &Apache::response::whichorder($max,$randomize,
+					 &Apache::response::showallfoils(),
+					 \%Apache::response::foilgroup);
 }
 
 sub start_conceptgroup {
@@ -375,31 +542,13 @@ sub end_conceptgroup {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     $Apache::rankresponse::conceptgroup=0;
     my $result='';
-    if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ) {
+    if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
+	$target eq 'tex' || $target eq 'analyze') {
 	#if not there aren't any foils to display and thus no question
-	if (defined(@{ $Apache::response::conceptgroup{'names'} })) {
-	    my @names = @{ $Apache::response::conceptgroup{'names'} };
-	    my $pick=int(&Math::Random::random_uniform() * ($#names+1));
-	    my $name=$names[$pick];
-	    push @{ $Apache::response::foilgroup{'names'} }, $name;
-	    $Apache::response::foilgroup{"$name.value"} =
-		$Apache::response::conceptgroup{"$name.value"};
-	    $Apache::response::foilgroup{"$name.text"} =
-		$Apache::response::conceptgroup{"$name.text"};
-	    $Apache::response::foilgroup{"$name.location"} =
-		$Apache::response::conceptgroup{"$name.location"};
-	    my $concept = &Apache::lonxml::get_param('concept',$parstack,
-						     $safeeval);
-	    $Apache::response::foilgroup{"$name.concept"} = $concept;
-	    &Apache::lonxml::debug("Selecting $name in $concept");
-	    if ($target eq 'web') {
-		my $part_id="$Apache::inputtags::part.$Apache::inputtags::response[-1]";
-		push(@{ $Apache::hint::rank{"$part_id.concepts"} },
-		     $concept);
-		$Apache::hint::rank{"$part_id.concept.$concept"}=
-		    $Apache::response::conceptgroup{'names'};
-	    }
-	}
+	&Apache::response::pick_foil_for_concept($target,
+						 ['value','text','location'],
+						 \%Apache::hint::rank,
+						 $parstack,$safeeval);
     } elsif ($target eq 'edit') {
 	$result=&Apache::edit::end_table();
     }
@@ -414,8 +563,11 @@ sub insert_conceptgroup {
 sub start_foil {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
-    if ($target eq 'web' || $target eq 'tex') {
+    if ($target eq 'web' || $target eq 'tex' || $target eq 'analyze') {
 	&Apache::lonxml::startredirection;
+	if ($target eq 'analyze') {
+	    &Apache::response::check_if_computed($token,$parstack,$safeeval,'value');
+	}
     } elsif ($target eq 'edit') {
 	$result=&Apache::edit::tag_start($target,$token,"Foil");
 	my $level='-2';
@@ -442,17 +594,29 @@ sub end_foil {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $text ='';
     my $result = '';
-    if ($target eq 'web' || $target eq 'tex') {
+    if ($target eq 'web' || $target eq 'tex' || $target eq 'analyze') {
 	$text=&Apache::lonxml::endredirection;
     }
-    if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' || $target eq 'tex') {
+    if ($target eq 'web' || $target eq 'grade' || $target eq 'answer' ||
+	$target eq 'tex' || $target eq 'analyze') {
 	my $value = &Apache::lonxml::get_param('value',$parstack,$safeeval);
+	if ($target eq 'tex' && $Apache::lonhomework::type eq 'exam') {
+	    $text='\vskip 5mm $\triangleright$ '.$text;
+	}
 	if ($value ne 'unused') {
 	    my $name = &Apache::lonxml::get_param('name',$parstack,$safeeval);
-	    my $location =&Apache::lonxml::get_param('location',$parstack,$safeeval);
 	    &Apache::lonxml::debug("Got a name of :$name:");
-	    if (!$name) { $name=$Apache::lonxml::curdepth; }
+	    if ($name eq "") {
+		&Apache::lonxml::warning(&mt('Foils without names exist. This can cause problems to malfunction.'));
+		$name=$Apache::lonxml::curdepth;
+	    }
 	    &Apache::lonxml::debug("Using a name of :$name:");
+	    if (defined($Apache::response::foilnames{$name})) {
+		&Apache::lonxml::error(&mt('Foil name [_1] appears more than once. Foil names need to be unique.','<b><tt>'.$name.'</tt></b>'));
+	    }
+	    $Apache::response::foilnames{$name}++;
+	    my $location =&Apache::lonxml::get_param('location',$parstack,
+						     $safeeval);
 	    if ( $Apache::rankresponse::conceptgroup
 		 && !&Apache::response::showallfoils() ) {
 		push @{ $Apache::response::conceptgroup{'names'} }, $name;