--- loncom/interface/lonprintout.pm	2003/06/18 18:11:16	1.188
+++ loncom/interface/lonprintout.pm	2003/08/20 18:34:14	1.221
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # Printout
 #
-# $Id: lonprintout.pm,v 1.188 2003/06/18 18:11:16 bowersj2 Exp $
+# $Id: lonprintout.pm,v 1.221 2003/08/20 18:34:14 sakharuk Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -286,6 +286,7 @@ sub character_chart {
     $result =~ s/&(mu|\#956);/\$\\mu \$/g;
     $result =~ s/&(nu|\#957);/\$\\nu \$/g;
     $result =~ s/&(xi|\#958);/\$\\xi \$/g;
+    $result =~ s/&(omicron|\#959);/o/g;
     $result =~ s/&(pi|\#960);/\$\\pi \$/g;
     $result =~ s/&(rho|\#961);/\$\\rho \$/g;
     $result =~ s/&(sigma|\#963);/\$\\sigma \$/g;
@@ -295,17 +296,88 @@ sub character_chart {
     $result =~ s/&(chi|\#967);/\$\\chi \$/g;
     $result =~ s/&(psi|\#968);/\$\\psi \$/g;
     $result =~ s/&(omega|\#969);/\$\\omega \$/g;
+    $result =~ s/&(thetasym|\#977);/\$\\vartheta \$/g;
+    $result =~ s/&(piv|\#982);/\$\\varpi \$/g;
+    $result =~ s/&(Alpha|\#913);/A/g;
+    $result =~ s/&(Beta|\#914);/B/g;
     $result =~ s/&(Gamma|\#915);/\$\\Gamma \$/g;
     $result =~ s/&(Delta|\#916);/\$\\Delta \$/g;
+    $result =~ s/&(Epsilon|\#917);/E/g;
+    $result =~ s/&(Zeta|\#918);/Z/g;
+    $result =~ s/&(Eta|\#919);/H/g;
     $result =~ s/&(Theta|\#920);/\$\\Theta \$/g;
+    $result =~ s/&(Iota|\#921);/I/g;
+    $result =~ s/&(Kappa|\#922);/K/g;
     $result =~ s/&(Lambda|\#923);/\$\\Lambda \$/g;
+    $result =~ s/&(Mu|\#924);/M/g;
+    $result =~ s/&(Nu|\#925);/N/g;
     $result =~ s/&(Xi|\#926);/\$\\Xi \$/g;
+    $result =~ s/&(Omicron|\#927);/O/g;
     $result =~ s/&(Pi|\#928);/\$\\Pi \$/g;
+    $result =~ s/&(Rho|\#929);/P/g;
     $result =~ s/&(Sigma|\#931);/\$\\Sigma \$/g;
+    $result =~ s/&(Tau|\#932);/T/g;
     $result =~ s/&(Upsilon|\#933);/\$\\Upsilon \$/g;
     $result =~ s/&(Phi|\#934);/\$\\Phi \$/g;
+    $result =~ s/&(Chi|\#935);/X/g;
     $result =~ s/&(Psi|\#936);/\$\\Psi \$/g;
     $result =~ s/&(Omega|\#937);/\$\\Omega \$/g;
+#Arrows (extended HTML 4.01)
+    $result =~ s/&(larr|\#8592);/\$\\leftarrow \$/g;
+    $result =~ s/&(uarr|\#8593);/\$\\uparrow \$/g;
+    $result =~ s/&(rarr|\#8594);/\$\\rightarrow \$/g;
+    $result =~ s/&(darr|\#8595);/\$\\downarrow \$/g;
+    $result =~ s/&(harr|\#8596);/\$\\leftrightarrow \$/g;
+    $result =~ s/&(lArr|\#8656);/\$\\Leftarrow \$/g;
+    $result =~ s/&(uArr|\#8657);/\$\\Uparrow \$/g;
+    $result =~ s/&(rArr|\#8658);/\$\\Rightarrow \$/g;
+    $result =~ s/&(dArr|\#8659);/\$\\Downarrow \$/g;
+    $result =~ s/&(hArr|\#8660);/\$\\Leftrightarrow \$/g;
+#Mathematical Operators (extended HTML 4.01)
+    $result =~ s/&(forall|\#8704);/\$\\forall \$/g;
+    $result =~ s/&(part|\#8706);/\$\\partial \$/g;
+    $result =~ s/&(exist|\#8707);/\$\\exists \$/g;
+    $result =~ s/&(empty|\#8709);/\$\\emptyset \$/g;
+    $result =~ s/&(nabla|\#8711);/\$\\nabla \$/g;
+    $result =~ s/&(isin|\#8712);/\$\\in \$/g;
+    $result =~ s/&(notin|\#8713);/\$\\notin \$/g;
+    $result =~ s/&(ni|\#8715);/\$\\ni \$/g;
+    $result =~ s/&(prod|\#8719);/\$\\prod \$/g;
+    $result =~ s/&(sum|\#8721);/\$\\sum \$/g;
+    $result =~ s/&(minus|\#8722);/\$-\$/g;
+    $result =~ s/&(lowast|\#8727);/\$*\$/g;
+    $result =~ s/&(radic|\#8730);/\$\\surd \$/g;
+    $result =~ s/&(prop|\#8733);/\$\\propto \$/g;
+    $result =~ s/&(infin|\#8734);/\$\\infty \$/g;
+    $result =~ s/&(ang|\#8736);/\$\\angle \$/g;
+    $result =~ s/&(and|\#8743);/\$\\wedge \$/g;
+    $result =~ s/&(or|\#8744);/\$\\vee \$/g;
+    $result =~ s/&(cap|\#8745);/\$\\cap \$/g;
+    $result =~ s/&(cup|\#8746);/\$\\cup \$/g;
+    $result =~ s/&(int|\#8747);/\$\\int \$/g;
+    $result =~ s/&(sim|\#8764);/\$\\sim \$/g;
+    $result =~ s/&(cong|\#8773);/\$\\cong \$/g;
+    $result =~ s/&(asymp|\#8776);/\$\\approx \$/g;
+    $result =~ s/&(ne|\#8800);/\$\\not= \$/g;
+    $result =~ s/&(equiv|\#8801);/\$\\equiv \$/g;
+    $result =~ s/&(le|\#8804);/\$\\leq \$/g;
+    $result =~ s/&(ge|\#8805);/\$\\geq \$/g;
+    $result =~ s/&(sub|\#8834);/\$\\subset \$/g;
+    $result =~ s/&(sup|\#8835);/\$\\supset \$/g;
+    $result =~ s/&(nsub|\#8836);/\$\\not\\subset \$/g;
+    $result =~ s/&(sube|\#8838);/\$\\subseteq \$/g;
+    $result =~ s/&(supe|\#8839);/\$\\supseteq \$/g;
+    $result =~ s/&(oplus|\#8853);/\$\\oplus \$/g;
+    $result =~ s/&(otimes|\#8855);/\$\\otimes \$/g;
+    $result =~ s/&(perp|\#8869);/\$\\perp \$/g;
+    $result =~ s/&(sdot|\#8901);/\$\\cdot \$/g;
+#Geometric Shapes (extended HTML 4.01)
+    $result =~ s/&(loz|\#9674);/\$\\Diamond \$/g;
+#Miscellaneous Symbols (extended HTML 4.01)
+    $result =~ s/&(spades|\#9824);/\$\\spadesuit \$/g;
+    $result =~ s/&(clubs|\#9827);/\$\\clubsuit \$/g;
+    $result =~ s/&(hearts|\#9829);/\$\\heartsuit \$/g;
+    $result =~ s/&(diams|\#9830);/\$\\diamondsuit \$/g;
     return $result;
 }
 
@@ -324,17 +396,17 @@ sub page_format {
 # 8 - "A6 [105x148 mm]"
 # 
     my ($papersize,$layout,$numberofcolumns) = @_; 
-    my ($textwidth,$textheight,$oddoffset,$evenoffset) = (0,0,0,0);
+    my ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin) = (0,0,0,0,0);
     if ($papersize eq '0') {
 	if ($layout eq 'book') {
 	    if ($numberofcolumns == 1) {
-		$textwidth = '18 cm';
-		$textheight = '25.9 cm';
+		$textwidth = '7.1 in';      #'18 cm';
+		$textheight = '10.2 in';    #'25.9 cm';
 		$oddoffset = '-0.57 in';
 		$evenoffset = '-0.57 in';
 	    } elsif ($numberofcolumns == 2) {
-		$textwidth = '93 mm';
-		$textheight = '25.9 cm';
+		$textwidth = '3.66 in';     #'93 mm';
+		$textheight = '10.2 in';    #'25.9 cm';
 		$oddoffset = '-0.57 in';
 		$evenoffset = '-0.57 in';
 	    }
@@ -345,10 +417,11 @@ sub page_format {
 		$oddoffset = '-40 pt';
 		$evenoffset = '-60 pt';
 	    } elsif ($numberofcolumns == 2) {
-		$textwidth = '4.2 in';
+		$textwidth = '4.4 in';
 		$textheight = '6.8 in';
-		$oddoffset = '-40 pt';
-		$evenoffset = '-60 pt';
+		$oddoffset = '-0.5 in';
+		$evenoffset = '-1.5 in';
+		$topmargin = '3.5 in';
 	    }
 	}
 #    } elsif($papersize eq '1') {
@@ -385,46 +458,56 @@ sub page_format {
 #    } elsif($papersize eq '7') {
 #    } elsif($papersize eq '8') {
     }
-    return $textwidth,$textheight,$oddoffset,$evenoffset;
+    return $textwidth,$textheight,$oddoffset,$evenoffset,$topmargin;
 }
 
 
 sub get_name {
     my ($uname,$udom)=@_;
     if (!defined($uname)) { $uname=$ENV{'user.name'}; }
-    if (!defined($udom)) { $uname=$ENV{'user.domain'}; }
+    if (!defined($udom)) { $udom=$ENV{'user.domain'}; }
     my $plainname=&Apache::loncommon::plainname($uname,$udom);
-    if ($plainname=~/^\s*$/) { $plainname=$uname; }
-    return &Apache::lonxml::latex_special_symbols($plainname,undef,undef,
-						  'header');
+    if ($plainname=~/^\s*$/) { $plainname=$uname.'@'.$udom; }
+    $plainname=&Apache::lonxml::latex_special_symbols($plainname,'header');
+    return $plainname;
 }
 
+sub get_course {
+    my $courseidinfo;
+    if (defined($ENV{'request.course.id'})) {
+	$courseidinfo = &Apache::lonxml::latex_special_symbols(&Apache::lonnet::unescape($ENV{'course.'.$ENV{'request.course.id'}.'.description'}),'header');
+    }
+    return $courseidinfo;
+}
 
 sub page_format_transformation {
-    my ($papersize,$layout,$numberofcolumns,$choice,$text,$assignment) = @_; 
-    my ($textwidth,$textheight,$oddoffset,$evenoffset);
-	$assignment=~s/_/ /g;
-        if ($numberofcolumns != 1) {
-          ($textwidth,$textheight,$oddoffset,$evenoffset) = &page_format($papersize,$layout,$numberofcolumns);
-	} else {
-	  ($textwidth,$textheight,$oddoffset,$evenoffset) = ($ENV{'form.width'},$ENV{'form.height'},$ENV{'form.leftmargin'},$ENV{'form.leftmargin'});
-	}
-    my $name = &get_name();
-    if ($name =~ /^\s*$/) {
-	$name=&Apache::lonxml::latex_special_symbols($ENV{'user.name'},undef,
-						     undef,'header');
+    my ($papersize,$layout,$numberofcolumns,$choice,$text,$assignment,$tableofcontents,$indexlist) = @_; 
+    my ($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin);
+    $assignment=~s/_/ /g;
+    if ($numberofcolumns != 1) {
+	($textwidth,$textheight,$oddoffset,$evenoffset,$topmargin) = &page_format($papersize,$layout,$numberofcolumns,$topmargin);
+    } else {
+	($textwidth,$textheight,$oddoffset,$evenoffset) = ($ENV{'form.width'},$ENV{'form.height'},$ENV{'form.leftmargin'},$ENV{'form.leftmargin'});
     }
-    my $courseidinfo = &Apache::lonxml::latex_special_symbols(&Apache::lonnet::unescape($ENV{'course.'.$ENV{'request.course.id'}.'.description'}),'','','header');
+    my $name = &get_name();
+    my $courseidinfo = &get_course();
+    if (defined($courseidinfo)) { $courseidinfo=' - '.$courseidinfo }
     if ($layout eq 'album') {
-	    $text =~ s/\\begin{document}/\\setlength{\\oddsidemargin}{$oddoffset}\\setlength{\\evensidemargin}{$evenoffset}\\setlength{\\topmargin}{200pt}\\setlength{\\textwidth}{$textwidth}\\setlength{\\textheight}{$textheight}\\setlength{\\parindent}{20pt}\\setlength{\\marginparwidth}{90pt}\\setlength{\\textfloatsep}{8pt plus 2\.0pt minus 4\.0pt}\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm} \\begin{document}\\setcounter{page}{1}\\noindent\\parbox{\\minipagewidth}{\\noindent\\fbox{\\textbf{$name}} \\hfill  $courseidinfo} \\vskip 5 mm /;
+	my $topmargintoinsert = '';
+	if ($topmargin ne '0') {$topmargintoinsert='\setlength{\topmargin}{'.$topmargin.'}';}
+	    $text =~ s/\\begin{document}/\\setlength{\\oddsidemargin}{$oddoffset}\\setlength{\\evensidemargin}{$evenoffset}$topmargintoinsert\\setlength{\\textwidth}{$textwidth}\\setlength{\\textheight}{$textheight}\\setlength{\\textfloatsep}{8pt plus 2\.0pt minus 4\.0pt}\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\\usepackage{fancyhdr}\\pagestyle{fancy}\\rhead{}\\chead{}\\lhead{\\textbf{$name} $courseidinfo \\hfill \\thepage \\\\ \\textit{$assignment}} \\begin{document}\\voffset=-0\.8 cm\\setcounter{page}{1} /;
     } elsif ($layout eq 'book') {
 	if ($choice ne 'All class print') { 
-		$text =~ s/\\begin{document}/\\textheight $textheight\\oddsidemargin = $evenoffset\\evensidemargin = $evenoffset\\textwidth= $textwidth\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\\renewcommand{\\ref}{\\keephidden\}\\usepackage{fancyhdr}\\pagestyle{fancy}\\rhead{}\\chead{}\\lhead{\\textbf{$name} - $courseidinfo \\hfill \\thepage \\\\ \\textit{$assignment}}\\begin{document}\\voffset=-0\.8 cm\\setcounter{page}{1}/;
+	    $text =~ s/\\begin{document}/\\textheight $textheight\\oddsidemargin = $evenoffset\\evensidemargin = $evenoffset\\textwidth= $textwidth\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\\renewcommand{\\ref}{\\keephidden\}\\usepackage{fancyhdr}\\pagestyle{fancy}\\rhead{}\\chead{}\\lhead{\\textbf{$name} $courseidinfo \\hfill \\thepage \\\\ \\textit{$assignment}}\\begin{document}\\voffset=-0\.8 cm\\setcounter{page}{1}/;
 	} else {
-	    $text =~ s/\\pagestyle{fancy}\\rhead{}\\chead{}\s*\\begin{document}/\\textheight $textheight\\oddsidemargin = $evenoffset\\evensidemargin = $evenoffset\\textwidth= $textwidth\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\\renewcommand{\\ref}{\\keephidden\}\\pagestyle{fancy}\\rhead{}\\chead{}\\begin{document}\\voffset=-0\.8cm\\setcounter{page}{1}  \\vskip 5 mm /;
-
+	    $text =~ s/\\pagestyle{fancy}\\rhead{}\\chead{}\s*\\begin{document}/\\textheight = $textheight\\oddsidemargin = $evenoffset\\evensidemargin = $evenoffset\\textwidth= $textwidth\\newlength{\\minipagewidth}\\setlength{\\minipagewidth}{\\textwidth\/\$number_of_columns-0\.2cm}\\renewcommand{\\ref}{\\keephidden\}\\pagestyle{fancy}\\rhead{}\\chead{}\\begin{document}\\voffset=-0\.8cm\\setcounter{page}{1}  \\vskip 5 mm /;
 	}
     }
+    if ($tableofcontents eq 'yes') {$text=~s/(\\setcounter\{page\}\{1\})/$1 \\tableofcontents\\newpage /;}
+    if ($indexlist eq 'yes') {
+	$text=~s/(\\begin{document})/\\makeindex $1/;
+	$text=~s/(\\end{document})/\\strut\\\\\\strut\\printindex $1/;
+    }
     return $text;
 }
 
@@ -499,6 +582,35 @@ sub latex_corrections {
 }
 
 
+sub index_table {
+    my $currentURL = shift;
+    my $insex_string='';
+    $currentURL=~s/\.([^\/+])$/\.$1\.meta/;
+    $insex_string=&Apache::lonnet::metadata($currentURL,'keywords');
+    return $insex_string;
+}
+
+
+sub IndexCreation {
+    my ($texversion,$currentURL)=@_;
+    my @key_words=split(/,/,&index_table($currentURL));
+    my $chunk='';
+    my $st=index $texversion,'\addcontentsline{toc}{subsection}{';
+    if ($st>0) {
+	for (my $i=0;$i<3;$i++) {$st=(index $texversion,'}',$st+1);}
+	$chunk=substr($texversion,0,$st+1);
+	substr($texversion,0,$st+1)=' ';
+    }
+    foreach my $key_word (@key_words) {
+	if ($key_word=~/\S+/) {
+	    $texversion=~s/\b($key_word)\b/$1 \\index{$key_word} /i;
+	}
+    }			
+    if ($st>0) {substr($texversion,0,1)=$chunk;}
+    return $texversion;
+}
+
+
 sub output_data {
     my ($r,$helper,$rparmhash) = @_;
     my %parmhash = %$rparmhash;
@@ -525,11 +637,11 @@ ENDPART
     my ($textwidth,$textheight,$oddoffset,$evenoffset) = &page_format($papersize,$laystyle,$numberofcolumns);
     my $assignment =  $ENV{'form.assignment'};
     my $LaTeXwidth; 
-    if ($textwidth=~/(\d+)\s*cm/) {
+    if ($textwidth=~/(\d+\.?\d*)\s*cm/) {
 	$LaTeXwidth = $1*10;
-    } elsif ($textwidth=~/(\d+)\s*mm/) {
+    } elsif ($textwidth=~/(\d+\.?\d*)\s*mm/) {
 	$LaTeXwidth = $1;
-    } elsif ($textwidth=~/(\d+)\s*in/) {
+    } elsif ($textwidth=~/(\d+\.?\d*)\s*in/) {
 	$LaTeXwidth = $1*25.4;
     }
     $LaTeXwidth.=' mm';
@@ -545,6 +657,7 @@ ENDPART
 	    $currentURL=$helper->{'VARS'}->{'filename'};
 	    $currentURL=~s/\/home\//\/~/;
 	    $currentURL=~s/public_html\///;
+	    if ($currentURL=~/([^?]+)/) {$currentURL=$1;}
 	}
 	$selectionmade = 1;
 	if ($currentURL=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)$/) {
@@ -552,10 +665,14 @@ ENDPART
 	    $moreenv{'request.filename'}=$currentURL;
 	    my %form;
 	    $form{'grade_target'}='tex';
-	    $form{'textwidth'}=$LaTeXwidth;
+	    $form{'textwidth'}=$LaTeXwidth;	
+	    $form{'problem_split'}=$parmhash{'problem_stream_switch'};
+	    $form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 	    my $rndseed=time;
 	    $form{'rndseed'}=$rndseed;
 	    &Apache::lonnet::appenv(%moreenv);
+	    &Apache::lonnet::delenv('form.counter');
+	    &Apache::lonxml::init_counter();
 	    my $texversion=&Apache::lonnet::ssi($currentURL,%form);
 	    &Apache::lonnet::delenv('form.counter');
 	    &Apache::lonnet::delenv('request.filename');
@@ -567,26 +684,43 @@ ENDPART
 		my $answer=&Apache::lonnet::ssi($currentURL,%form);
 		$texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 	    }
+	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
+		$texversion=&IndexCreation($texversion,$currentURL);
+	    }
+	    if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
+		$texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$currentURL| \\strut\\\\\\strut /;
+
+	    }
 	    $result .= $texversion;
 	    if ($currentURL=~m/\.page\s*$/) {
 		($result,$number_of_columns) = &page_cleanup($result);
 	    }
 	} else {
-#	  $result='\documentclass[letterpaper]{article}\usepackage{calc}\begin{document}Printout of this type of document is currently not supported: ';
-#	  if ($ENV{'form.url'}=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) {
-#	      $result.=$1;
-#	  } else {
-#	      $result.=$ENV{'form.url'};
-#	  }
-#	  $result.=' \end{document}'
+	  $result='\documentclass[letterpaper]{article}\usepackage{calc}\begin{document}Printout of this type of document is currently not supported: ';
+	  if ($currentURL=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) {
+	      $result.=$1;
+	  } elsif ($currentURL=~/\/ext\//) {
+	      $result.=' \strut \\\\ THIS IS EXTERNAL RESOURCE WITH URL \strut \\\\ '.$currentURL.' ';
+	  } else {
+	      $result.=$currentURL;
+	  }
+	  $result.=' \end{document}'
 	}
     } elsif (($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems') or
              ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'map_problems_pages') or
              ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems')) { 
         #-- produce an output string
+	my %form=();	   
+	$form{'grade_target'}='tex';
+	$form{'textwidth'}=$LaTeXwidth;
+	$form{'problem_split'}=$parmhash{'problem_stream_switch'};
+	$form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 	my $flag_latex_header_remove = 'NO';
 	my $flag_page_in_sequence = 'NO';
 	my @master_seq=split /\|\|\|/, $helper->{'VARS'}->{'RESOURCES'};
+	my $prevassignment='';
+	&Apache::lonnet::delenv('form.counter');
+	&Apache::lonxml::init_counter();
 	for (my $i=0;$i<=$#master_seq;$i++) {
 	    $master_seq[$i]=~/___\d+___(.*)$/;
 	    my $urlp='/res/'.$1;
@@ -597,11 +731,9 @@ ENDPART
 	    } elsif ($helper->{'VARS'}->{'PRINT_TYPE'} eq 'all_problems') {
 		$selectionmade = 4;
 	    }
-	    my %form;	   
-	    $form{'grade_target'}='tex';
-	    $form{'textwidth'}=$LaTeXwidth;
 	    $form{'symb'}=$master_seq[$i];
-            $form{'problem_split'}=$parmhash{'problem_stream_switch'};
+	    $master_seq[$i]=~/(.*)___\d*___/;
+	    my $assignment=&Apache::lonnet::gettitle($1); #tittle of the assignment which contains this problem
 	    #&Apache::lonnet::logthis("Trying to get $urlp with symb $master_seq[$i]");
 	    my $texversion=&Apache::lonnet::ssi($urlp,%form);
 	    if ($urlp=~/\.page$/) {
@@ -622,7 +754,17 @@ ENDPART
 		my $answer=&Apache::lonnet::ssi($urlp,%form);
 		$texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
 	    }
-	    $result .= $texversion;         
+	    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
+		$texversion=&IndexCreation($texversion,$urlp);
+	    }
+	    if (($selectionmade == 4) and ($assignment ne $prevassignment) and ($i>=1)) {
+		my ($name,$courseidinfo) = &get_name;
+		$courseidinfo = &get_course();
+		if (defined($courseidinfo)) { $courseidinfo=' - '.$courseidinfo }
+		$prevassignment=$assignment;
+		$result .='\newpage \noindent\parbox{\minipagewidth}{\noindent\\lhead{\\textit{\\textbf{'.$name.'}}'.$courseidinfo.' \\hfill \\thepage \\\\ \\textit{'.$assignment.'}}} \vskip -5 mm ';
+	    }
+	    $result .= $texversion;
 	    $flag_latex_header_remove = 'YES';   
 	}
 	&Apache::lonnet::delenv('form.counter');
@@ -644,7 +786,11 @@ ENDPART
 #	    my ($usersection,$username,$userdomain) = split /:/,$person;
 	    my ($username,$userdomain) = split /:/,$person;
 	    my $fullname = &get_name($username,$userdomain);
+
+	    if ($parmhash{'anonymous_quiz'}=~/yes/) {$fullname=' ';} #put here something reasonable for anonymous exams or quiz
             #goes through all resources, checks if they are available for current student, and produces output   
+	    &Apache::lonnet::delenv('form.counter');
+	    &Apache::lonxml::init_counter();
 	    foreach my $curresline (@master_seq)  {
 		if ($curresline=~ m/\.(problem|exam|quiz|assess|survey|form|library)$/) {
 		    my ($map,$id,$res_url) = split(/___/,$curresline);
@@ -659,8 +805,8 @@ ENDPART
 			if($helper->{'VARS'}->{'ANSWER_TYPE'} eq 'no') {
 			    my %form;
 			    $form{'answer_output_mode'}='tex';
-			    my $ansrendered = &Apache::loncommon::get_student_answers($curresline,$username,$userdomain,
-										      $ENV{'request.course.id'},%form);
+			    $form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
+			    my $ansrendered = &Apache::loncommon::get_student_answers($curresline,$username,$userdomain,$ENV{'request.course.id'},%form);
 			    $rendered=~s/(\\keephidden{ENDOFPROBLEM})/$ansrendered$1/;
 			}
 			$current_output .= $rendered;
@@ -668,13 +814,15 @@ ENDPART
 		    $flag_latex_header_remove = 'YES';
 		}
 	    }
-	    my $courseidinfo = $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
+	    my $courseidinfo = &get_course();
+	    if (defined($courseidinfo)) { $courseidinfo=' - '.$courseidinfo }
+	    my $currentassignment=&Apache::lonxml::latex_special_symbols($helper->{VARS}->{'assignment'},'header');
 	    if ($current_output=~/\\documentclass/) {
-		$current_output =~ s/\\begin{document}/\\setlength{\\topmargin}{1cm} \\begin{document}\\noindent\\lhead{\\textit{\\textbf{$fullname}} - $courseidinfo \\hfill \\thepage \\\\ \\textit{$helper->{VARS}->{'assignment'}}}\\vskip 3 mm /;
+		$current_output =~ s/\\begin{document}/\\setlength{\\topmargin}{1cm} \\begin{document}\\noindent\\lhead{\\textit{\\textbf{$fullname}}$courseidinfo \\hfill \\thepage \\\\ \\textit{$currentassignment}}\\vskip 3 mm /;
 	    } else {
 		my $blanspages = '';
 		for (my $j=0;$j<$helper->{'VARS'}->{'EMPTY_PAGES'};$j++) {$blanspages.='\clearpage\strut\clearpage';}
-		$current_output = '\strut\\newline\\noindent\\makebox[\\textwidth/$number_of_columns][b]{\\hrulefill}\\newline\\noindent{\\tiny Printed from LON-CAPA\\copyright MSU{\\hfill} Licensed under GNU General Public License }\\newpage '.$blanspages.'\setcounter{page}{1}\noindent\parbox{\minipagewidth}{\noindent\\lhead{\\textit{\\textbf{'.$fullname.'}} - '.$courseidinfo.' \\hfill \\thepage \\\\ \\textit{'.$helper->{VARS}->{'assignment'}.'}}} \vskip -5 mm '.$current_output;
+		$current_output = '\strut\\newline\\noindent\\makebox[\\textwidth/$number_of_columns][b]{\\hrulefill}\\newline\\noindent{\\tiny Printed from LON-CAPA\\copyright MSU{\\hfill} Licensed under GNU General Public License }\\newpage '.$blanspages.'\setcounter{page}{1}\noindent\parbox{\minipagewidth}{\noindent\\lhead{\\textit{\\textbf{'.$fullname.'}}'.$courseidinfo.' \\hfill \\thepage \\\\ \\textit{'.$currentassignment.'}}} \vskip -5 mm '.$current_output;
 	    }
 	    $result .= $current_output;
 	    &Apache::lonnet::delenv('form.counter');	    
@@ -709,6 +857,7 @@ ENDPART
 		    my %form;
 		    $form{'grade_target'}='answer';
 		    $form{'answer_output_mode'}='tex';
+		    $form{'latex_type'}=$helper->{'VARS'}->{'LATEX_TYPE'};
 		    $form{'rndseed'}=$rndseed;
 		    my $answer=&Apache::lonnet::ssi($urlp,%form);
 		    $texversion=~s/(\\keephidden{ENDOFPROBLEM})/$answer$1/;
@@ -738,6 +887,13 @@ ENDPART
 		} else {
 		    $texversion =~ s/\\end{document}//;
 		}
+		if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
+		    $texversion=&IndexCreation($texversion,$urlp);
+		}
+		if ($helper->{'VARS'}->{'CONSTR_RESOURSE_URL'} eq 'yes') {
+		    $texversion=~s/(\\addcontentsline\{toc\}\{subsection\}\{[^\}]*\})/$1 URL: \\verb|$urlp| \\strut\\\\\\strut /;
+		    
+		}
 		$result .= $texversion;
 	    }
 	    $flag_latex_header_remove = 'YES';  
@@ -746,15 +902,19 @@ ENDPART
 	$result .= '\end{document}';      	
     }
 #-------------------------------------------------------- corrections for the different page formats
-    $result = &page_format_transformation($papersize,$laystyle,$numberofcolumns,$helper->{'VARS'}->{'PRINT_TYPE'},$result,$helper->{VARS}->{'assignment'});
+    $result = &page_format_transformation($papersize,$laystyle,$numberofcolumns,$helper->{'VARS'}->{'PRINT_TYPE'},$result,$helper->{VARS}->{'assignment'},$helper->{'VARS'}->{'TABLE_CONTENTS'},$helper->{'VARS'}->{'TABLE_INDEX'});
     $result = &latex_corrections($number_of_columns,$result);
-#    #changes page's parameters for the one column output 
-#    if ($ENV{'form.numberofcolumns'} == 1) {
-#	$result =~ s/\\textwidth= 9cm/\\textwidth= $ENV{'form.width'}/;
-#	$result =~ s/\\textheight 25\.9cm/\\textheight $ENV{'form.height'}/;
-#	$result =~ s/\\evensidemargin = -0\.57in/\\evensidemargin= $ENV{'form.leftmargin'}/;
-#	$result =~ s/\\oddsidemargin = -0\.57in/\\oddsidemargin= $ENV{'form.leftmargin'}/;
-#    }
+    #changes page's parameters for the one column output 
+    if ($numberofcolumns == 1) {
+	$result =~ s/\\textwidth= 9cm/\\textwidth= $helper->{'VARS'}->{'pagesize.width'} $helper->{'VARS'}->{'pagesize.widthunit'} /;
+	$result =~ s/\\textheight 25\.9cm/\\textheight $helper->{'VARS'}->{'pagesize.height'} $helper->{'VARS'}->{'pagesize.heightunit'} /;
+	$result =~ s/\\evensidemargin = -0\.57in/\\evensidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
+	$result =~ s/\\oddsidemargin = -0\.57in/\\oddsidemargin= $helper->{'VARS'}->{'pagesize.lmargin'} $helper->{'VARS'}->{'pagesize.lmarginunit'} /;
+    }
+    if ($helper->{'VARS'}->{'TABLE_CONTENTS'} eq 'yes') {$selectionmade*=10;}
+    if ($helper->{'VARS'}->{'TABLE_INDEX'} eq 'yes') {
+	if ($selectionmade<10) {$selectionmade*=100;} else {$selectionmade*=10;}
+    }
 #-- writing .tex file in prtspool 
     my $temp_file;
     my $filename = "/home/httpd/prtspool/$ENV{'user.name'}_$ENV{'user.domain'}_printout_".time."_".rand(10000000).".tex";
@@ -764,7 +924,6 @@ ENDPART
     } 
     print $temp_file $result;
 
-#<meta http-equiv="Refresh" content="0; url=/cgi-bin/printout.pl?$filename&$laystyle&$numberofcolumns&$selectionmade">
 $r->print(<<FINALEND);
 <meta http-equiv="Refresh" content="0; url=/cgi-bin/printout.pl?$filename&$laystyle&$numberofcolumns&$selectionmade">
 </body>
@@ -799,13 +958,12 @@ sub handler {
 #	return OK;
 
     my %parmhash=&Apache::lonnet::coursedescription($ENV{'request.course.id'});
-#    $r->print('<br /> START '.$ENV{'request.course.fn'}.' FINISH <br />');
-#    my $key; 
-#    foreach $key (keys %parmhash) {
-#	$r->print(' '.$key.'->'.$parmhash{$key}.'<-<br />');
-#    }
-#    return OK;
     
+#	my $key; 
+#	foreach $key (keys %parmhash) {
+#	    $r->print(' '.$key.'->'.$parmhash{$key}.'<-<br />');
+#	}
+#	return OK;
 
     &output_data($r,$helper,\%parmhash);
     return OK;
@@ -856,8 +1014,7 @@ sub printHelper {
     # This will persistently load in the data we want from the
     # very first screen.
     # Detect whether we're coming from construction space
-    if ($ENV{'form.postdata'} =~ /http:\/\// ) {
-        $ENV{'form.postdata'} =~ /http:\/\/[^\/]+\/~([^\/]+)\/(.*)/;
+    if ($ENV{'form.postdata'}=~/^(?:http:\/\/[^\/]+\/|\/|)\~([^\/]+)\/(.*)$/) {
         $helper->{VARS}->{'filename'} = "/home/$1/public_html/$2";
         $helper->{VARS}->{'construction'} = 1;
     } else {
@@ -906,6 +1063,8 @@ sub printHelper {
         $subdir = &Apache::lonnet::filelocation("", $url);
     }
 
+    my $userCanSeeHidden = Apache::lonnavmaps::advancedUser();
+
     Apache::lonhelper::registerHelperTags();
 
     # "Delete everything after the last slash."
@@ -913,6 +1072,8 @@ sub printHelper {
     if (not $helper->{VARS}->{'construction'}) {
 	$subdir='/home/httpd/html/res/'.$subdir;
     }
+    # "Remove all duplicate slashes."
+    $subdir =~ s|/+|/|g;
 
     # What can be printed is a very dynamic decision based on
     # lots of factors. So we need to dynamically build this list.
@@ -941,18 +1102,20 @@ sub printHelper {
         # Allow all resources from sequence
         push @{$printChoices}, ["Everything (problem(s), page(s), html/xml file(s)) from <b>$sequenceTitle</b>", 'map_problems_pages', 'CHOOSE_PROBLEMS_HTML'];
 
-        my $isProblem = '$res->is_problem();';
+        my $isProblem = '$res->is_problem()';
+	$isProblem .= ' && !$res->randomout()' if !$userCanSeeHidden;
         my $isProblemOrMap = '$res->is_problem() || $res->is_map()';
-        my $isNotMap = '!$res->is_map();';
-        my $symb = '$res->symb();';
+        my $isNotMap = '!$res->is_map()';
+	$isNotMap .= ' && !$res->randomout()' if !$userCanSeeHidden;
+        my $symb = '$res->symb()';
         my $helperFragment = <<HELPERFRAGMENT;
   <state name="CHOOSE_PROBLEMS" title="Select Problem(s) to print">
     <message>(mark them then click "next" button) <br /></message>
     <resource variable="RESOURCES" multichoice="1" toponly='1'>
       <nextstate>PAGESIZE</nextstate>
-      <filterfunc>return $isProblem</filterfunc>
+      <filterfunc>return $isProblem;</filterfunc>
       <mapurl>$map</mapurl>
-      <valuefunc>return $symb</valuefunc>
+      <valuefunc>return $symb;</valuefunc>
       </resource>
     </state>
 
@@ -962,7 +1125,7 @@ sub printHelper {
       <nextstate>PAGESIZE</nextstate>
       <filterfunc>return $isNotMap;</filterfunc>
       <mapurl>$map</mapurl>
-      <valuefunc>return $symb</valuefunc>
+      <valuefunc>return $symb;</valuefunc>
       </resource>
     </state>
 HELPERFRAGMENT
@@ -976,22 +1139,23 @@ HELPERFRAGMENT
         push @{$printChoices}, ['<b>Problems</b> in this course', 'all_problems', 'ALL_PROBLEMS'];
         push @{$printChoices}, ["Problems from <b>$sequenceTitle</b> for selected students", 'problems_for_students', 'CHOOSE_STUDENTS'];
 
-        my $isProblem = '$res->is_problem();';
-        my $isProblemOrMap = '$res->is_problem() || $res->is_map()';
-        my $symb = '$res->symb();';
+        my $isProblem = '$res->is_problem()';
+	$isProblem .= ' && !$res->randomout()' if !$userCanSeeHidden;
+        my $isProblemOrMap = '($res->is_problem() || $res->is_map())';
+	$isProblemOrMap .= ' && !$res->randomout()' if !$userCanSeeHidden;
+        my $symb = '$res->symb()';
         &Apache::lonxml::xmlparse($r, 'helper', <<CHOOSE_STUDENTS);
   <state name="ALL_PROBLEMS" title="Select Problem(s) to print">
     <message>(mark them then click "next" button) <br /></message>
     <resource variable="RESOURCES" multichoice="1" suppressEmptySequences='1'>
       <nextstate>PAGESIZE</nextstate>
-      <filterfunc>return $isProblemOrMap</filterfunc>
-      <choicefunc>return $isProblem</choicefunc>
-      <valuefunc>return $symb</valuefunc>
+      <filterfunc>return $isProblemOrMap;</filterfunc>
+      <choicefunc>return $isProblem;</choicefunc>
+      <valuefunc>return $symb;</valuefunc>
       </resource>
     </state>
 
   <state name="CHOOSE_STUDENTS" title="Choose Students whose assignments you want to print">
-    <message>(do not forget to select assignment itself - make another selection below) <br /></message>
     <student multichoice='1' variable="STUDENTS" nextstate="PAGESIZE" />
     <message><br /><big><i><b>Select resources for the assignment</b></i></big><br /></message>
     <resource variable="RESOURCES" multichoice="1">
@@ -1001,16 +1165,17 @@ HELPERFRAGMENT
       </resource>
     <message><br /><big><i><b>How should the results be printed?</b></i></big><br /></message>
     <choices variable="EMPTY_PAGES">
-      <choice computer='0'>Start each student's assignment on a new page (add a pagefeed after each assignment)</choice>
-      <choice computer='1'>Add one empty page after each student's assignment</choice>
-      <choice computer='2'>Add two empty pages after each student's assignment</choice>
+      <choice computer='0'>Start each student\'s assignment on a new page/column (add a pagefeed after each assignment)</choice>
+      <choice computer='1'>Add one empty page/column after each student\'s assignment</choice>
+      <choice computer='2'>Add two empty pages/column after each student\'s assignment</choice>
+      <choice computer='3'>Add three empty pages/column after each student\'s assignment</choice>
       </choices>
     </state>
 CHOOSE_STUDENTS
     }
 
     # FIXME: That RE should come from a library somewhere.
-    if (((&Apache::lonnet::allowed('bre',$subdir) eq 'F') and ($helper->{VARS}->{'postdata'}=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)/)) or defined $helper->{'VARS'}->{'construction'}) {    
+    if ((((&Apache::lonnet::allowed('bre',$subdir) eq 'F') and ($helper->{VARS}->{'postdata'}=~/\.(problem|exam|quiz|assess|survey|form|library|page|xml|html|htm|xhtml|xhtm)/)) or defined $helper->{'VARS'}->{'construction'}) and $ENV{'request.role.adv'}) {    
         push @{$printChoices}, ["Problems from current subdirectory <b>$subdir</b>", 'problems_from_directory', 'CHOOSE_FROM_SUBDIR'];
         
         my $f = '$filename';
@@ -1024,7 +1189,7 @@ CHOOSE_FROM_SUBDIR
         
         $xmlfrag .= <<'CHOOSE_FROM_SUBDIR';
       <filefilter>return $filename =~ 
-           m/^[^\.]+\.(problem|exam|quiz|assess|survey|form|library)$/;
+           m/\.(problem|exam|quiz|assess|survey|form|library)$/;
       </filefilter>
       </files>
     </state>
@@ -1046,7 +1211,7 @@ CHOOSE_FROM_SUBDIR
     if (($ENV{'request.role.adv'} and &Apache::lonnet::allowed('vgr',$ENV{'request.course.id'})) or 
 	($helper->{VARS}->{'construction'} eq '1')) {
         $paramHash = Apache::lonhelper::getParamHash();
-        $paramHash->{MESSAGE_TEXT} = "<br /><big><b><i>Next option is available only for advanced users:</i></b></big><br />";
+        $paramHash->{MESSAGE_TEXT} = "<br /><table><tr><td><big><b><i>Next four options are available only for advanced users:  </i></b></big></td><td>";
         Apache::lonhelper::message->new();
         $paramHash = Apache::lonhelper::getParamHash();
 	$paramHash->{'variable'} = 'ANSWER_TYPE';   
@@ -1054,7 +1219,67 @@ CHOOSE_FROM_SUBDIR
         $paramHash->{CHOICES} = [
                                    ['Print without answer', 'yes'],
                                    ['Print with answers', 'no'] ];
-        Apache::lonhelper::choices->new();
+        Apache::lonhelper::dropdown->new();
+    }
+
+    if ($ENV{'request.role.adv'}) {
+        $paramHash = Apache::lonhelper::getParamHash();
+        $paramHash->{MESSAGE_TEXT} = "</td></tr><tr><td>&nbsp;</td><td>";
+        Apache::lonhelper::message->new();
+        $paramHash = Apache::lonhelper::getParamHash();
+	$paramHash->{'variable'} = 'LATEX_TYPE';   
+	$helper->declareVar('LATEX_TYPE');  
+	if ($helper->{VARS}->{'construction'} eq '1') {       
+	    $paramHash->{CHOICES} = [
+				     ['Print in standard LaTeX mode', 'standard'], 
+				     ['Print in LaTeX batchmode', 'batchmode'], ];
+	} else {
+	    $paramHash->{CHOICES} = [
+				     ['Print in LaTeX batchmode', 'batchmode'],
+				     ['Print in standard LaTeX mode', 'standard'] ];
+	}
+        Apache::lonhelper::dropdown->new();
+ 
+        $paramHash = Apache::lonhelper::getParamHash();
+        $paramHash->{MESSAGE_TEXT} = "</td></tr><tr><td>&nbsp;</td><td>";
+        Apache::lonhelper::message->new();
+        $paramHash = Apache::lonhelper::getParamHash();
+	$paramHash->{'variable'} = 'TABLE_CONTENTS';   
+	$helper->declareVar('TABLE_CONTENTS');         
+        $paramHash->{CHOICES} = [
+                                   ['Print without Table of Contents', 'no'],
+                                   ['Print with Table of Contents', 'yes'] ];
+        Apache::lonhelper::dropdown->new();
+        
+	if (not $helper->{VARS}->{'construction'}) {
+	    $paramHash = Apache::lonhelper::getParamHash();
+	    $paramHash->{MESSAGE_TEXT} = "</td></tr><tr><td>&nbsp;</td><td>";
+	    Apache::lonhelper::message->new();
+	    $paramHash = Apache::lonhelper::getParamHash();
+	    $paramHash->{'variable'} = 'TABLE_INDEX';   
+	    $helper->declareVar('TABLE_INDEX');         
+	    $paramHash->{CHOICES} = [
+				     ['Print without Index', 'no'],
+				     ['Print with Index', 'yes'] ];
+	    Apache::lonhelper::dropdown->new();
+	}
+
+	if ($helper->{VARS}->{'construction'}) {
+	    $paramHash = Apache::lonhelper::getParamHash();
+	    $paramHash->{MESSAGE_TEXT} = "</td></tr><tr><td>&nbsp;</td><td>";
+	    Apache::lonhelper::message->new();
+	    $paramHash = Apache::lonhelper::getParamHash();
+	    $paramHash->{'variable'} = 'CONSTR_RESOURSE_URL';   
+	    $helper->declareVar('CONSTR_RESOURSE_URL');         
+	    $paramHash->{CHOICES} = [
+				     ['Print without URL', 'no'],
+				     ['Print with UTL', 'yes'] ];
+	    Apache::lonhelper::dropdown->new();
+	}
+
+        $paramHash = Apache::lonhelper::getParamHash();
+        $paramHash->{MESSAGE_TEXT} = "</td></tr><table>";
+        Apache::lonhelper::message->new();
     }
 
     Apache::lonprintout::page_format_state->new("FORMAT");