[system] / trunk / pg / macros / PGbasicmacros.pl Repository:
ViewVC logotype

View of /trunk/pg/macros/PGbasicmacros.pl

Parent Directory Parent Directory | Revision Log Revision Log


Revision 5626 - (download) (as text) (annotate)
Wed Mar 26 02:43:07 2008 UTC (11 years, 10 months ago) by gage
File size: 73445 byte(s)
Fixed bug in base64Q subroutine

    1 
    2 
    3 ####################################################################
    4 # Copyright @ 1995-1998 University of Rochester
    5 # All Rights Reserved
    6 ####################################################################
    7 
    8 =head1 NAME
    9 
   10     PGbasicmacros.pl --- located in the courseScripts directory
   11 
   12 =head1 SYNPOSIS
   13 
   14 
   15 
   16 =head1 DESCRIPTION
   17 
   18 
   19 
   20 =cut
   21 
   22 # this is equivalent to use strict, but can be used within the Safe compartment.
   23 BEGIN{
   24   be_strict;
   25 }
   26 
   27 
   28 my $displayMode;
   29 
   30 my ($PAR,
   31   $BR,
   32   $LQ,
   33   $RQ,
   34   $BM,
   35   $EM,
   36   $BDM,
   37   $EDM,
   38   $LTS,
   39   $GTS,
   40   $LTE,
   41   $GTE,
   42   $BEGIN_ONE_COLUMN,
   43   $END_ONE_COLUMN,
   44   $SOL,
   45   $SOLUTION,
   46   $HINT,
   47   $COMMENT,
   48   $US,
   49   $SPACE,
   50   $BBOLD,
   51   $EBOLD,
   52   $BITALIC,
   53   $EITALIC,
   54   $BCENTER,
   55   $ECENTER,
   56   $HR,
   57   $LBRACE,
   58   $RBRACE,
   59   $LB,
   60   $RB,
   61   $DOLLAR,
   62   $PERCENT,
   63   $CARET,
   64   $PI,
   65   $E,
   66   @ALPHABET,
   67   $envir,
   68   $PG_random_generator,
   69   $inputs_ref,
   70   $rh_sticky_answers,
   71   $r_ans_rule_count,
   72   );
   73 
   74 sub _PGbasicmacros_init {
   75     # The big problem is that at compile time in the cached Safe compartment
   76     # main:: has one definition, probably Safe::Root1::
   77     # At runtime main has another definition Safe::Rootx:: where x is > 1
   78 
   79     # It is important to
   80     # initialize the my variable version of $displayMode from the "runtime" version
   81     # of main::displayMode
   82 
   83     $displayMode         =    main::PG_restricted_eval(q!$main::displayMode!);
   84 
   85 # This is initializes the remaining variables in the runtime main:: compartment.
   86 
   87 main::PG_restricted_eval( <<'EndOfFile');
   88     $displayMode            = $displayMode;
   89 
   90   $main::PAR        = PAR();
   91   $main::BR       = BR();
   92   $main::LQ       = LQ();
   93   $main::RQ       = RQ();
   94   $main::BM       = BM();
   95   $main::EM       = EM();
   96   $main::BDM        = BDM();
   97   $main::EDM        = EDM();
   98   $main::LTS        = LTS();
   99   $main::GTS        = GTS();
  100   $main::LTE        = LTE();
  101   $main::GTE        = GTE();
  102   $main::BEGIN_ONE_COLUMN = BEGIN_ONE_COLUMN();
  103   $main::END_ONE_COLUMN = END_ONE_COLUMN();
  104   $main::SOL        = SOLUTION_HEADING();
  105   $main::SOLUTION     = SOLUTION_HEADING();
  106   $main::HINT       = HINT_HEADING();
  107   $main::US       = US();
  108   $main::SPACE      = SPACE();
  109   $main::BBOLD      = BBOLD();
  110   $main::EBOLD      = EBOLD();
  111   $main::BITALIC      = BITALIC();
  112   $main::EITALIC          = EITALIC();
  113   $main::BCENTER          = BCENTER();
  114   $main::ECENTER          = ECENTER();
  115   $main::HR       = HR();
  116   $main::LBRACE     = LBRACE();
  117   $main::RBRACE     = RBRACE();
  118   $main::LB       = LB();
  119   $main::RB       = RB();
  120   $main::DOLLAR     = DOLLAR();
  121   $main::PERCENT      = PERCENT();
  122   $main::CARET      = CARET();
  123   $main::PI       = PI();
  124   $main::E        = E();
  125   @main::ALPHABET     = ('A'..'ZZ');
  126   %main::STICKY_ANSWERS   = ();
  127 
  128 
  129 EndOfFile
  130 
  131 # Next we transfer the correct definitions in the main:: compartment to the local my variables
  132 # This can't be done inside the eval above because my variables seem to be invisible inside the eval
  133 
  134 
  135     $PAR         = PAR();
  136   $BR            = BR();
  137   $LQ            = LQ();
  138   $RQ            = RQ();
  139   $BM            = BM();
  140   $EM            = EM();
  141   $BDM         = BDM();
  142   $EDM         = EDM();
  143   $LTS         = LTS();
  144   $GTS         = GTS();
  145   $LTE         = LTE();
  146   $GTE         = GTE();
  147   $BEGIN_ONE_COLUMN  = BEGIN_ONE_COLUMN();
  148   $END_ONE_COLUMN      = END_ONE_COLUMN();
  149   $SOL         = SOLUTION_HEADING();
  150   $SOLUTION      = SOLUTION_HEADING();
  151   $HINT        = HINT_HEADING();
  152   $US            = US();
  153   $SPACE           = SPACE();
  154   $BBOLD           = BBOLD();
  155   $EBOLD           = EBOLD();
  156   $BITALIC       = BITALIC();
  157   $EITALIC             = EITALIC();
  158   $BCENTER             = BCENTER();
  159   $ECENTER             = ECENTER();
  160   $HR            = HR();
  161   $LBRACE          = LBRACE();
  162   $RBRACE          = RBRACE();
  163   $LB            = LB();
  164   $RB            = RB();
  165   $DOLLAR          = DOLLAR();
  166   $PERCENT       = PERCENT();
  167   $CARET           = CARET();
  168   $PI            = PI();
  169   $E             = E();
  170   @ALPHABET      = ('A'..'ZZ');
  171 
  172    $envir               = PG_restricted_eval(q!\%main::envir!);
  173    $PG_random_generator = PG_restricted_eval(q!$main::PG_random_generator!);
  174    $inputs_ref          = $envir{inputs_ref};
  175    $rh_sticky_answers   = PG_restricted_eval(q!\%main::STICKY_ANSWERS!);
  176    $r_ans_rule_count     = PG_restricted_eval(q!\$ans_rule_count!);
  177 }
  178 
  179 =head2  Answer blank macros:
  180 
  181 These produce answer blanks of various sizes or pop up lists or radio answer buttons.
  182 The names for the answer blanks are
  183 generated implicitly.
  184 
  185   ans_rule( width )
  186   tex_ans_rule( width )
  187   ans_radio_buttons(value1=>label1, value2,label2 => value3,label3=>...)
  188   pop_up_list(@list)   # list consists of (value => label,  PR => "Product rule",...)
  189   pop_up_list([@list]) # list consists of values
  190 
  191 In the last case, one can use C<pop_up_list(['?', 'yes', 'no'])> to produce a
  192 pop-up list containing the three strings listed, and then use str_cmp to check
  193 the answer.
  194 
  195 To indicate the checked position of radio buttons put a '%' in front of the value: C<ans_radio_buttons(1, 'Yes','%2','No')>
  196 will have 'No' checked.  C<tex_ans_rule> works inside math equations in C<HTML_tth> mode.  It does not work in C<Latex2HTML> mode
  197 since this mode produces gif pictures.
  198 
  199 
  200 The following method is defined in F<PG.pl> for entering the answer evaluators corresponding
  201 to answer rules with automatically generated names.  The answer evaluators are matched with the
  202 answer rules in the order in which they appear on the page.
  203 
  204   ANS(ans_evaluator1, ans_evaluator2,...);
  205 
  206 These are more primitive macros which produce answer blanks for specialized cases when complete
  207 control over the matching of answers blanks and answer evaluators is desired.
  208 The names of the answer blanks must be generated manually, and it is best if they do NOT begin
  209 with the default answer prefix (currently AnSwEr).
  210 
  211   labeled_ans_rule(name, width)  # an alias for NAMED_ANS_RULE where width defaults to 20 if omitted.
  212 
  213   NAMED_ANS_RULE(name, width)
  214   NAMED_ANS_BOX(name, rows, cols)
  215   NAMED_ANS_RADIO(name, value,label,)
  216   NAMED_ANS_RADIO_EXTENSION(name, value,label)
  217   NAMED_ANS_RADIO_BUTTONS(name,value1,label1,value2,label2,...)
  218   check_box('-name' =>answer5,'-value' =>'statement3','-label' =>'I loved this course!'   )
  219   NAMED_POP_UP_LIST($name, @list) # list consists of (value => tag,  PR => "Product rule",...)
  220   NAMED_POP_UP_LIST($name, [@list]) # list consists of a list of values (and each tag will be set to the corresponding value)
  221 
  222 (Name is the name of the variable, value is the value given to the variable when this option is selected,
  223 and label is the text printed next to the button or check box.    Check box variables can have multiple values.)
  224 
  225 NAMED_ANS_RADIO_BUTTONS creates a sequence of NAMED_ANS_RADIO and NAMED_ANS_RADIO_EXTENSION  items which
  226 are  output either as an array or, in scalar context, as the array glued together with spaces.  It is
  227 usually easier to use this than to manually construct the radio buttons by hand.  However, sometimes
  228  extra flexibility is desiredin which case:
  229 
  230 When entering radio buttons using the "NAMED" format, you should use NAMED_ANS_RADIO button for the first button
  231 and then use NAMED_ANS_RADIO_EXTENSION for the remaining buttons.  NAMED_ANS_RADIO requires a matching answer evalutor,
  232 while NAMED_ANS_RADIO_EXTENSION does not. The name used for NAMED_ANS_RADIO_EXTENSION should match the name
  233 used for NAMED_ANS_RADIO (and the associated answer evaluator).
  234 
  235 
  236 The following method is defined in  F<PG.pl> for entering the answer evaluators corresponding
  237 to answer rules with automatically generated names.  The answer evaluators are matched with the
  238 answer rules in the order in which they appear on the page.
  239 
  240       NAMED_ANS(name1 => ans_evaluator1, name2 => ans_evaluator2,...);
  241 
  242 These auxiliary macros are defined in PG.pl
  243 
  244 
  245   NEW_ANS_NAME( number );   # produces a new answer blank name from a number by adding a prefix (AnSwEr)
  246                             # and registers this name as an implicitly labeled answer
  247                             # Its use is paired with each answer evaluator being entered using ANS()
  248 
  249     ANS_NUM_TO_NAME(number);  # adds the prefix (AnSwEr) to the number, but does nothing else.
  250 
  251   RECORD_ANS_NAME( name );  # records the order in which the answer blank  is rendered
  252                             # This is called by all of the constructs above, but must
  253                             # be called explicitly if an input blank is constructed explictly
  254                             # using HTML code.
  255 
  256 These are legacy macros:
  257 
  258   ANS_RULE( number, width );                  # equivalent to NAMED_ANS_RULE( NEW_ANS_NAME(number), width)
  259   ANS_BOX( question_number,height, width );       # equivalent to NAMED_ANS_BOX( NEW_ANS_NAME(number), height, width)
  260   ANS_RADIO( question_number, value,tag );        # equivalent to NAMED_ANS_RADIO( NEW_ANS_NAME(number), value,tag)
  261   ANS_RADIO_OPTION( question_number, value,tag );   # equivalent to NAMED_ANS_RADIO_EXTENSION( ANS_NUM_TO_NAME(number), value,tag)
  262 
  263 
  264 =cut
  265 
  266 
  267 
  268 sub labeled_ans_rule {   # syntactic sugar for NAMED_ANS_RULE
  269   my($name,$col) = @_;
  270   $col = 20 unless defined($col);
  271   NAMED_ANS_RULE($name,$col);
  272 }
  273 
  274 sub NAMED_ANS_RULE {
  275   my($name,$col) = @_;
  276   my $answer_value = '';
  277   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  278     if ($answer_value =~ /\0/ ) {
  279       my @answers = split("\0", $answer_value);
  280       $answer_value = shift(@answers);  # use up the first answer
  281       $rh_sticky_answers->{$name}=\@answers;
  282       # store the rest -- beacuse this stores to a main:; variable
  283       # it must be evaluated at run time
  284       $answer_value= '' unless defined($answer_value);
  285   } elsif (ref($answer_value) eq 'ARRAY') {
  286     my @answers = @{ $answer_value};
  287       $answer_value = shift(@answers);  # use up the first answer
  288       $rh_sticky_answers->{$name}=\@answers;
  289       # store the rest -- beacuse this stores to a main:; variable
  290       # it must be evaluated at run time
  291       $answer_value= '' unless defined($answer_value);
  292   }
  293 
  294   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  295   $answer_value =~ s/\s+/ /g;     ## remove excessive whitespace from student answer
  296   $name = RECORD_ANS_NAME($name);
  297 
  298   my $tcol = $col/2 > 3 ? $col/2 : 3;  ## get max
  299   $tcol = $tcol < 40 ? $tcol : 40;     ## get min
  300 
  301   MODES(
  302     TeX => "\\mbox{\\parbox[t]{${tcol}ex}{\\hrulefill}}",
  303     Latex2HTML => qq!\\begin{rawhtml}<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\\end{rawhtml}!,
  304     HTML => qq!<INPUT TYPE=TEXT SIZE=$col NAME="$name" VALUE="$answer_value">!.
  305                         qq!<INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE="$answer_value">!
  306   );
  307 }
  308 
  309 sub NAMED_HIDDEN_ANS_RULE { # this is used to hold information being passed into and out of applets
  310                             # -- preserves state -- identical to NAMED_ANS_RULE except input type "hidden"
  311   my($name,$col) = @_;
  312   my $answer_value = '';
  313   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  314     if ($answer_value =~ /\0/ ) {
  315       my @answers = split("\0", $answer_value);
  316       $answer_value = shift(@answers);  # use up the first answer
  317       $rh_sticky_answers->{$name}=\@answers;
  318       # store the rest -- beacuse this stores to a main:; variable
  319       # it must be evaluated at run time
  320       $answer_value= '' unless defined($answer_value);
  321   } elsif (ref($answer_value) eq 'ARRAY') {
  322     my @answers = @{ $answer_value};
  323       $answer_value = shift(@answers);  # use up the first answer
  324       $rh_sticky_answers->{$name}=\@answers;
  325       # store the rest -- beacuse this stores to a main:; variable
  326       # it must be evaluated at run time
  327       $answer_value= '' unless defined($answer_value);
  328   }
  329 
  330   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  331   $answer_value =~ s/\s+/ /g;     ## remove excessive whitespace from student answer
  332   $name = RECORD_ANS_NAME($name);
  333 
  334   my $tcol = $col/2 > 3 ? $col/2 : 3;  ## get max
  335   $tcol = $tcol < 40 ? $tcol : 40;     ## get min
  336 
  337   MODES(
  338     TeX => "\\mbox{\\parbox[t]{${tcol}ex}{\\hrulefill}}",
  339     Latex2HTML => qq!\\begin{rawhtml}<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\\end{rawhtml}!,
  340     HTML => qq!<INPUT TYPE=HIDDEN SIZE=$col NAME="$name" VALUE="$answer_value">!.
  341                         qq!<INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE="$answer_value">!
  342   );
  343 }
  344 sub NAMED_ANS_RULE_OPTION {   # deprecated
  345   &NAMED_ANS_RULE_EXTENSION;
  346 }
  347 
  348 sub NAMED_ANS_RULE_EXTENSION {
  349   my($name,$col) = @_;
  350   my $answer_value = '';
  351   $answer_value = ${$inputs_ref}{$name} if defined(${$inputs_ref}{$name});
  352   if ( defined( $rh_sticky_answers->{$name} ) ) {
  353     $answer_value = shift( @{ $rh_sticky_answers->{$name} });
  354     $answer_value = '' unless defined($answer_value);
  355   }
  356   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  357   $answer_value =~ s/\s+/ /g;     ## remove excessive whitespace from student answer
  358   my $tcol = $col/2 > 3 ? $col/2 : 3;  ## get max
  359   $tcol = $tcol < 40 ? $tcol : 40;     ## get min
  360   MODES(
  361     TeX => "\\mbox{\\parbox[t]{${tcol}ex}{\\hrulefill}}",
  362     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\n\\end{rawhtml}\n!,
  363     HTML => qq!<INPUT TYPE=TEXT SIZE=$col NAME = "$name" VALUE = "$answer_value">!.
  364                         qq!<INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE = "$answer_value">!
  365   );
  366 }
  367 
  368 sub ANS_RULE {  #deprecated
  369   my($number,$col) = @_;
  370   my $name = NEW_ANS_NAME($number);
  371     NAMED_ANS_RULE($name,$col);
  372 }
  373 
  374 
  375 sub  NAMED_ANS_BOX {
  376   my($name,$row,$col) = @_;
  377   $row = 10 unless defined($row);
  378   $col = 80 unless defined($col);
  379   $name = RECORD_ANS_NAME($name);
  380   my $height = .07*$row;
  381   my $answer_value = '';
  382   $answer_value = $inputs_ref->{$name} if defined( $inputs_ref->{$name} );
  383   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  384   my $out = M3(
  385        qq!\\vskip $height in \\hrulefill\\quad !,
  386        qq!\\begin{rawhtml}<TEXTAREA NAME="$name" ROWS="$row" COLS="$col"
  387                WRAP="VIRTUAL">$answer_value</TEXTAREA>\\end{rawhtml}!,
  388          qq!<TEXTAREA NAME="$name" ROWS="$row" COLS="$col"
  389                WRAP="VIRTUAL">$answer_value</TEXTAREA>
  390              <INPUT TYPE=HIDDEN  NAME="previous_$name" VALUE = "$answer_value">
  391            !
  392          );
  393   $out;
  394 }
  395 
  396 sub  ANS_BOX { #deprecated
  397   my($number,$row,$col) = @_;
  398   my $name = NEW_ANS_NAME($number);
  399     NAMED_ANS_BOX($name,$row,$col);
  400 }
  401 
  402 sub NAMED_ANS_RADIO {
  403   my $name = shift;
  404   my $value = shift;
  405     my $tag =shift;
  406     $name = RECORD_ANS_NAME($name);
  407     my $checked = '';
  408     if ($value =~/^\%/) {
  409       $value =~ s/^\%//;
  410       $checked = 'CHECKED'
  411     }
  412   if (defined($inputs_ref->{$name}) ) {
  413     if ($inputs_ref->{$name} eq $value) {
  414       $checked = 'CHECKED'
  415     } else {
  416       $checked = '';
  417     }
  418 
  419     }
  420 
  421   MODES(
  422     TeX => qq!\\item{$tag}\n!,
  423     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  424     HTML => qq!<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>$tag!
  425   );
  426 
  427 }
  428 
  429 sub NAMED_ANS_RADIO_OPTION { #deprecated
  430   &NAMED_ANS_RADIO_EXTENSION;
  431 }
  432 
  433 sub NAMED_ANS_RADIO_EXTENSION {
  434   my $name = shift;
  435   my $value = shift;
  436   my $tag =shift;
  437 
  438 
  439     my $checked = '';
  440     if ($value =~/^\%/) {
  441       $value =~ s/^\%//;
  442       $checked = 'CHECKED'
  443     }
  444   if (defined($inputs_ref->{$name}) ) {
  445     if ($inputs_ref->{$name} eq $value) {
  446       $checked = 'CHECKED'
  447     } else {
  448       $checked = '';
  449     }
  450 
  451     }
  452 
  453   MODES(
  454     TeX => qq!\\item{$tag}\n!,
  455     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  456     HTML => qq!<INPUT TYPE=RADIO NAME="$name" VALUE="$value" $checked>$tag!
  457   );
  458 
  459 }
  460 
  461 sub NAMED_ANS_RADIO_BUTTONS {
  462     my $name  =shift;
  463     my $value = shift;
  464     my $tag = shift;
  465 
  466 
  467   my @out = ();
  468   push(@out, NAMED_ANS_RADIO($name, $value,$tag));
  469   my @buttons = @_;
  470   while (@buttons) {
  471     $value = shift @buttons;  $tag = shift @buttons;
  472     push(@out, NAMED_ANS_RADIO_OPTION($name, $value,$tag));
  473   }
  474   (wantarray) ? @out : join(" ",@out);
  475 }
  476 sub ANS_RADIO {
  477   my $number = shift;
  478   my $value = shift;
  479   my $tag =shift;
  480     my $name = NEW_ANS_NAME($number);
  481   NAMED_ANS_RADIO($name,$value,$tag);
  482 }
  483 
  484 sub ANS_RADIO_OPTION {
  485   my $number = shift;
  486   my $value = shift;
  487   my $tag =shift;
  488 
  489 
  490     my $name = ANS_NUM_TO_NAME($number);
  491   NAMED_ANS_RADIO_OPTION($name,$value,$tag);
  492 }
  493 sub ANS_RADIO_BUTTONS {
  494     my $number  =shift;
  495     my $value = shift;
  496     my $tag = shift;
  497 
  498 
  499   my @out = ();
  500   push(@out, ANS_RADIO($number, $value,$tag));
  501   my @buttons = @_;
  502   while (@buttons) {
  503       $value = shift @buttons; $tag = shift @buttons;
  504     push(@out, ANS_RADIO_OPTION($number, $value,$tag));
  505   }
  506   (wantarray) ? @out : join(" ",@out);
  507 }
  508 ##############################################
  509 #   contained_in( $elem, $array_reference or null separated string);
  510 #   determine whether element is equal
  511 #   ( in the sense of eq,  not ==, ) to an element in the array.
  512 ##############################################
  513 sub contained_in {
  514   my $element = shift;
  515   my @input_list    = @_;
  516   my @output_list = ();
  517   # Expand the list -- convert references to  arrays to arrays
  518   # Convert null separated strings to arrays
  519   foreach my $item   (@input_list ) {
  520     if ($item =~ /\0/) {
  521       push @output_list,   split('\0', $item);
  522      } elsif (ref($item) =~/ARRAY/) {
  523       push @output_list, @{$item};
  524      } else {
  525       push @output_list, $item;
  526      }
  527   }
  528 
  529   my @match_list = grep {$element eq $_ } @output_list;
  530   if ( @match_list ) {
  531     return 1;
  532   } else {
  533     return 0;
  534   }
  535 }
  536 
  537 ##########################
  538 # If multiple boxes are checked then the $inputs_ref->{name }will be a null separated string
  539 # or a reference to an array.
  540 ##########################
  541 
  542 sub NAMED_ANS_CHECKBOX {
  543   my $name = shift;
  544   my $value = shift;
  545     my $tag =shift;
  546     $name = RECORD_ANS_NAME($name);
  547 
  548     my $checked = '';
  549     if ($value =~/^\%/) {
  550       $value =~ s/^\%//;
  551       $checked = 'CHECKED'
  552     }
  553 
  554   if (defined($inputs_ref->{$name}) ) {
  555     if ( contained_in($value, $inputs_ref->{$name} ) ) {
  556       $checked = 'CHECKED'
  557     }
  558     else {
  559       $checked = '';
  560     }
  561 
  562     }
  563 
  564   MODES(
  565     TeX => qq!\\item{$tag}\n!,
  566     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  567     HTML => qq!<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>$tag!
  568   );
  569 
  570 }
  571 
  572 sub NAMED_ANS_CHECKBOX_OPTION {
  573   my $name = shift;
  574   my $value = shift;
  575   my $tag =shift;
  576 
  577     my $checked = '';
  578     if ($value =~/^\%/) {
  579       $value =~ s/^\%//;
  580       $checked = 'CHECKED'
  581     }
  582 
  583   if (defined($inputs_ref->{$name}) ) {
  584     if ( contained_in($value, $inputs_ref->{$name}) ) {
  585       $checked = 'CHECKED'
  586     }
  587     else {
  588       $checked = '';
  589     }
  590 
  591     }
  592 
  593   MODES(
  594     TeX => qq!\\item{$tag}\n!,
  595     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>\\end{rawhtml}$tag!,
  596     HTML => qq!<INPUT TYPE=CHECKBOX NAME="$name" VALUE="$value" $checked>$tag!
  597   );
  598 
  599 }
  600 
  601 sub NAMED_ANS_CHECKBOX_BUTTONS {
  602     my $name  =shift;
  603     my $value = shift;
  604     my $tag = shift;
  605 
  606   my @out = ();
  607   push(@out, NAMED_ANS_CHECKBOX($name, $value,$tag));
  608 
  609   my @buttons = @_;
  610   while (@buttons) {
  611     $value = shift @buttons;  $tag = shift @buttons;
  612     push(@out, NAMED_ANS_CHECKBOX_OPTION($name, $value,$tag));
  613   }
  614 
  615   (wantarray) ? @out : join(" ",@out);
  616 }
  617 
  618 sub ANS_CHECKBOX {
  619   my $number = shift;
  620   my $value = shift;
  621   my $tag =shift;
  622     my $name = NEW_ANS_NAME($number);
  623 
  624   NAMED_ANS_CHECKBOX($name,$value,$tag);
  625 }
  626 
  627 sub ANS_CHECKBOX_OPTION {
  628   my $number = shift;
  629   my $value = shift;
  630   my $tag =shift;
  631     my $name = ANS_NUM_TO_NAME($number);
  632 
  633   NAMED_ANS_CHECKBOX_OPTION($name,$value,$tag);
  634 }
  635 
  636 
  637 
  638 sub ANS_CHECKBOX_BUTTONS {
  639     my $number  =shift;
  640     my $value = shift;
  641     my $tag = shift;
  642 
  643   my @out = ();
  644   push(@out, ANS_CHECKBOX($number, $value, $tag));
  645 
  646   my @buttons = @_;
  647   while (@buttons) {
  648     $value = shift @buttons;  $tag = shift @buttons;
  649     push(@out, ANS_CHECKBOX_OPTION($number, $value,$tag));
  650   }
  651 
  652   (wantarray) ? @out : join(" ",@out);
  653 }
  654 
  655 sub ans_rule {
  656   my $len = shift;     # gives the optional length of the answer blank
  657   $len    = 20 unless $len ;
  658   my $name = NEW_ANS_NAME(inc_ans_rule_count());
  659   NAMED_ANS_RULE($name ,$len);
  660 }
  661 sub ans_rule_extension {
  662   my $len = shift;
  663     $len    = 20 unless $len ;
  664   my $name = NEW_ANS_NAME($$r_ans_rule_count);  # don't update the answer name
  665   NAMED_ANS_RULE($name ,$len);
  666 }
  667 sub ans_radio_buttons {
  668   my $name  = NEW_ANS_NAME(inc_ans_rule_count());
  669   my @radio_buttons = NAMED_ANS_RADIO_BUTTONS($name, @_);
  670 
  671   if ($displayMode eq 'TeX') {
  672     $radio_buttons[0] = "\n\\begin{itemize}\n" . $radio_buttons[0];
  673     $radio_buttons[$#radio_buttons] .= "\n\\end{itemize}\n";
  674   }
  675 
  676   (wantarray) ? @radio_buttons: join(" ", @radio_buttons);
  677 }
  678 
  679 #added 6/14/2000 by David Etlinger
  680 sub ans_checkbox {
  681   my $name = NEW_ANS_NAME( inc_ans_rule_count() );
  682   my @checkboxes = NAMED_ANS_CHECKBOX_BUTTONS( $name, @_ );
  683 
  684   if ($displayMode eq 'TeX') {
  685     $checkboxes[0] = "\n\\begin{itemize}\n" . $checkboxes[0];
  686     $checkboxes[$#checkboxes] .= "\n\\end{itemize}\n";
  687   }
  688 
  689   (wantarray) ? @checkboxes: join(" ", @checkboxes);
  690 }
  691 
  692 
  693 ## define a version of ans_rule which will work inside TeX math mode or display math mode -- at least for tth mode.
  694 ## This is great for displayed fractions.
  695 ## This will not work with latex2HTML mode since it creates gif equations.
  696 
  697 sub tex_ans_rule {
  698   my $len = shift;
  699   $len    = 20 unless $len ;
  700     my $name = NEW_ANS_NAME(inc_ans_rule_count());
  701     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  702     my $out = MODES(
  703                      'TeX' => $answer_rule,
  704                      'Latex2HTML' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  705                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  706                      'HTML_dpng' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  707                      'HTML'     => $answer_rule
  708                    );
  709 
  710     $out;
  711 }
  712 sub tex_ans_rule_extension {
  713   my $len = shift;
  714   $len    = 20 unless $len ;
  715     my $name = NEW_ANS_NAME($$r_ans_rule_count);
  716     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  717     my $out = MODES(
  718                      'TeX' => $answer_rule,
  719                      'Latex2HTML' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  720                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  721                      'HTML_dpng' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  722                      'HTML'     => $answer_rule
  723                    );
  724 
  725     $out;
  726 }
  727 # still needs some cleanup.
  728 sub NAMED_TEX_ANS_RULE {
  729     my $name = shift;
  730   my $len = shift;
  731   $len    = 20 unless $len ;
  732     my $answer_rule = NAMED_ANS_RULE($name ,$len);  # we don't want to create three answer rules in different modes.
  733     my $out = MODES(
  734                      'TeX' => $answer_rule,
  735                      'Latex2HTML' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  736                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  737                      'HTML_dpng' => '\\fbox{Answer boxes cannot be placed inside typeset equations}',
  738                      'HTML'     => $answer_rule
  739                    );
  740 
  741     $out;
  742 }
  743 sub NAMED_TEX_ANS_RULE_EXTENSION {
  744   my $name = shift;
  745   my $len = shift;
  746   $len    = 20 unless $len ;
  747     my $answer_rule = NAMED_ANS_RULE_EXTENSION($name ,$len);  # we don't want to create three answer rules in different modes.
  748     my $out = MODES(
  749                      'TeX' => $answer_rule,
  750                      'Latex2HTML' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  751                      'HTML_tth' => '\\begin{rawhtml} '. $answer_rule.'\\end{rawhtml}',
  752                      'HTML_dpng' => '\fbox{Answer boxes cannot be placed inside typeset equations}',
  753                      'HTML'     => $answer_rule
  754                    );
  755 
  756     $out;
  757 }
  758 sub ans_box {
  759   my $row = shift;
  760   my $col =shift;
  761   $row = 5 unless $row;
  762   $col = 80 unless $col;
  763   my $name = NEW_ANS_NAME(inc_ans_rule_count());
  764   NAMED_ANS_BOX($name ,$row,$col);
  765 }
  766 
  767 #this is legacy code; use ans_checkbox instead
  768 sub checkbox {
  769   my %options = @_;
  770   qq!<INPUT TYPE="checkbox" NAME="$options{'-name'}" VALUE="$options{'-value'}">$options{'-label'}!
  771 }
  772 
  773 
  774 sub NAMED_POP_UP_LIST {
  775     my $name = shift;
  776   my @list = @_;
  777   if(ref($list[0]) eq 'ARRAY') {
  778     my @list1 = @{$list[0]};
  779     @list = map { $_ => $_ } @list1;
  780   }
  781   $name = RECORD_ANS_NAME($name);   # record answer name
  782     my $answer_value = '';
  783   $answer_value = ${$inputs_ref}{$name} if defined(${$inputs_ref}{$name});
  784   my $out = "";
  785   if ($displayMode eq 'HTML' or $displayMode eq 'HTML_tth' or
  786             $displayMode eq 'HTML_dpng' or $displayMode eq 'HTML_img' or $displayMode eq 'HTML_jsMath' or
  787       $displayMode eq 'HTML_asciimath' or $displayMode eq 'HTML_LaTeXMathML') {
  788     $out = qq!<SELECT NAME = "$name" SIZE=1> \n!;
  789     my $i;
  790     foreach ($i=0; $i< @list; $i=$i+2) {
  791       my $select_flag = ($list[$i] eq $answer_value) ? "SELECTED" : "";
  792       $out .= qq!<OPTION $select_flag VALUE ="$list[$i]" > $list[$i+1]  </OPTION>\n!;
  793     };
  794     $out .= " </SELECT>\n";
  795   } elsif ( $displayMode eq "Latex2HTML") {
  796     $out = qq! \\begin{rawhtml}<SELECT NAME = "$name" SIZE=1> \\end{rawhtml} \n !;
  797     my $i;
  798     foreach ($i=0; $i< @list; $i=$i+2) {
  799       my $select_flag = ($list[$i] eq $answer_value) ? "SELECTED" : "";
  800       $out .= qq!\\begin{rawhtml}<OPTION $select_flag VALUE ="$list[$i]" > $list[$i+1]  </OPTION>\\end{rawhtml}\n!;
  801     };
  802     $out .= " \\begin{rawhtml}</SELECT>\\end{rawhtml}\n";
  803   } elsif ( $displayMode eq "TeX") {
  804       $out .= "\\fbox{?}";
  805   }
  806 
  807 }
  808 
  809 sub pop_up_list {
  810   my @list = @_;
  811   my $name = NEW_ANS_NAME(inc_ans_rule_count());  # get new answer name
  812   NAMED_POP_UP_LIST($name, @list);
  813 }
  814 
  815 
  816 
  817 =head5  answer_matrix
  818 
  819     Usage   \[ \{   answer_matrix(rows,columns,width_of_ans_rule, @options) \} \]
  820 
  821     Creates an array of answer blanks and passes it to display_matrix which returns
  822     text which represents the matrix in TeX format used in math display mode. Answers
  823     are then passed back to whatever answer evaluators you write at the end of the problem.
  824     (note, if you have an m x n matrix, you will need mn answer evaluators, and they will be
  825     returned to the evaluaters starting in the top left hand corner and proceed to the left
  826     and then at the end moving down one row, just as you would read them.)
  827 
  828     The options are passed on to display_matrix.
  829 
  830 
  831 =cut
  832 
  833 
  834 sub answer_matrix{
  835   my $m = shift;
  836   my $n = shift;
  837   my $width = shift;
  838   my @options = @_;
  839   my @array=();
  840   for( my $i = 0; $i < $m; $i+=1)
  841   {
  842     my @row_array = ();
  843 
  844     for( my $i = 0; $i < $n; $i+=1)
  845     {
  846       push @row_array,  ans_rule($width);
  847     }
  848     my $r_row_array = \@row_array;
  849     push @array,  $r_row_array;
  850   }
  851   # display_matrix hasn't been loaded into the cache safe compartment
  852   # so we need to refer to the subroutine in this way to make
  853   # sure that main is defined correctly.
  854   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  855   &$ra_local_display_matrix( \@array, @options );
  856 
  857 }
  858 
  859 sub NAMED_ANS_ARRAY_EXTENSION{
  860 
  861   my $name = shift;
  862   my $col = shift;
  863   $col = 20 unless $col;
  864   my $answer_value = '';
  865 
  866   $answer_value = ${$inputs_ref}{$name} if    defined(${$inputs_ref}{$name});
  867   if ($answer_value =~ /\0/ ) {
  868     my @answers = split("\0", $answer_value);
  869     $answer_value = shift(@answers);
  870     $answer_value= '' unless defined($answer_value);
  871   } elsif (ref($answer_value) eq 'ARRAY') {
  872     my @answers = @{ $answer_value};
  873       $answer_value = shift(@answers);
  874         $answer_value= '' unless defined($answer_value);
  875   }
  876 
  877   $answer_value =~ tr/\\$@`//d;   #`## make sure student answers can not be interpolated by e.g. EV3
  878   MODES(
  879     TeX => "\\mbox{\\parbox[t]{10pt}{\\hrulefill}}\\hrulefill\\quad ",
  880     Latex2HTML => qq!\\begin{rawhtml}\n<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"\">\n\\end{rawhtml}\n!,
  881     HTML => "<INPUT TYPE=TEXT SIZE=$col NAME=\"$name\" VALUE = \"$answer_value\">\n"
  882   );
  883 }
  884 
  885 sub ans_array{
  886   my $m = shift;
  887   my $n = shift;
  888   my $col = shift;
  889   $col = 20 unless $col;
  890   my $num = inc_ans_rule_count() ;
  891   my $name = NEW_ANS_ARRAY_NAME($num,0,0);
  892   my @options = @_;
  893   my @array=();
  894   my $string;
  895   my $answer_value = "";
  896 
  897   $array[0][0] =   NAMED_ANS_RULE($name,$col);
  898 
  899   for( my $i = 1; $i < $n; $i+=1)
  900   {
  901     $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,0,$i);
  902     $array[0][$i] =   NAMED_ANS_ARRAY_EXTENSION($name,$col);
  903 
  904   }
  905 
  906   for( my $j = 1; $j < $m; $j+=1 ){
  907 
  908     for( my $i = 0; $i < $n; $i+=1)
  909     {
  910       $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,$j,$i);
  911       $array[$j][$i] =  NAMED_ANS_ARRAY_EXTENSION($name,$col);
  912 
  913     }
  914 
  915   }
  916   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  917   &$ra_local_display_matrix( \@array, @options );
  918 
  919 }
  920 
  921 sub ans_array_extension{
  922   my $m = shift;
  923   my $n = shift;
  924   my $col = shift;
  925   $col = 20 unless $col;
  926   my $num = PG_restricted_eval(q!$main::ans_rule_count!);
  927   my @options = @_;
  928   my $name;
  929   my @array=();
  930   my $string;
  931   my $answer_value = "";
  932 
  933   for( my $j = 0; $j < $m; $j+=1 ){
  934 
  935     for( my $i = 0; $i < $n; $i+=1)
  936     {
  937       $name = NEW_ANS_ARRAY_NAME_EXTENSION($num,$j,$i);
  938       $array[$j][$i] =  NAMED_ANS_ARRAY_EXTENSION($name,$col);
  939 
  940     }
  941 
  942   }
  943   my $ra_local_display_matrix=PG_restricted_eval(q!\&main::display_matrix!);
  944   &$ra_local_display_matrix( \@array, @options );
  945 
  946 }
  947 
  948 
  949 # end answer blank macros
  950 
  951 =head2 Hints and solutions macros
  952 
  953   solution('text','text2',...);
  954   SOLUTION('text','text2',...);   # equivalent to TEXT(solution(...));
  955 
  956   hint('text', 'text2', ...);
  957   HINT('text', 'text2',...);      # equivalent to TEXT("$BR$HINT" . hint(@_) . "$BR") if hint(@_);
  958 
  959 Solution prints its concatenated input when the check box named 'ShowSol' is set and
  960 the time is after the answer date.  The check box 'ShowSol' is visible only after the
  961 answer date or when the problem is viewed by a professor.
  962 
  963 $main::envir{'displaySolutionsQ'} is set to 1 when a solution is to be displayed.
  964 
  965 Hints are shown only after the number of attempts is greater than $:showHint
  966 ($main::showHint defaults to 1) and the check box named 'ShowHint' is set. The check box
  967 'ShowHint' is visible only after the number of attempts is greater than $main::showHint.
  968 
  969 $main::envir{'displayHintsQ'} is set to 1 when a hint is to be displayed.
  970 
  971 
  972 =cut
  973 
  974 
  975 
  976 #   solution prints its input when $displaySolutionsQ is set.
  977 #   use as TEXT(solution("blah, blah");
  978 #   \$solutionExists
  979 #   is passed to processProblem which displays a "show Solution" button
  980 #   when a solution is available for viewing
  981 
  982 
  983 sub solution {
  984   my @in = @_;
  985   my $out = '';
  986   PG_restricted_eval(q!$main::solutionExists =1!);
  987   if (PG_restricted_eval(q!$main::envir{'displaySolutionsQ'}!)) {$out = join(' ',@in);}
  988     $out;
  989 }
  990 
  991 
  992 sub SOLUTION {
  993   TEXT( solution(@_)) ;
  994 }
  995 
  996 
  997 
  998 sub hint {
  999     my @in = @_;
 1000   my $out = '';
 1001 
 1002   PG_restricted_eval(q!$main::hintExists =1;
 1003                          $main::numOfAttempts = 0 unless defined($main::numOfAttempts);
 1004     !);
 1005 
 1006   if ($displayMode eq 'TeX')   {
 1007     $out = '';  # do nothing since hints are not available for download
 1008   } elsif (($envir->{'displayHintsQ'}) and
 1009           PG_restricted_eval(q!($main::numOfAttempts >= $main::showHint)!))
 1010 
 1011    ## the second test above prevents a hint being shown if a doctored form is submitted
 1012 
 1013   {$out = join(' ',@in);}    # show hint
 1014 
 1015   $out ;
 1016 }
 1017 
 1018 
 1019 sub HINT {
 1020     TEXT("$BR" . hint(@_) . "$BR") if hint(@_);
 1021 }
 1022 
 1023 
 1024 
 1025 # End hints and solutions macros
 1026 #################################
 1027 
 1028 =head2 Comments to instructors
 1029 
 1030   COMMENT('text','text2',...);
 1031 
 1032 Takes the text to be lines of a comment to be shown only
 1033 in the Library Browser below the rendered problem.
 1034 
 1035 The function COMMENT stores the needed html in the variable
 1036 pgComment, which gets transfered to the flag 'comment' in PG_FLAGS.
 1037 
 1038 =cut
 1039 
 1040 # Add a comment which will display in the Library browser
 1041 #  Currently, the only output is html
 1042 
 1043 sub COMMENT {
 1044     my @in = @_;
 1045   my $out = join("$BR", @in);
 1046   my $out = '<div class=\"AuthorComment\">'.$out.'</div>';
 1047 
 1048   PG_restricted_eval(q!$main::pgComment = "!.$out.q!"!);
 1049   return('');
 1050 }
 1051 
 1052 #################################
 1053 # Produces a random number between $begin and $end with increment 1.
 1054 # You do not have to worry about integer or floating point types.
 1055 
 1056 =head2 Pseudo-random number generator
 1057 
 1058   Usage:
 1059   random(0,5,.1)      # produces a random number between 0 and 5 in increments of .1
 1060   non_zero_random(0,5,.1) # gives a non-zero random number
 1061 
 1062   list_random(2,3,5,6,7,8,10) # produces random value from the list
 1063   list_random(2,3, (5..8),10) # does the same thing
 1064 
 1065   SRAND(seed)     # resets the main random generator -- use very cautiously
 1066 
 1067 
 1068 SRAND(time) will create a different problem everytime it is called.  This makes it difficult
 1069 to check the answers :-).
 1070 
 1071 SRAND($envir->{'inputs_ref'}->{'key'} ) will create a different problem for each login session.
 1072 This is probably what is desired.
 1073 
 1074 =cut
 1075 
 1076 
 1077 sub random  {
 1078   my ($begin, $end, $incr) = @_;
 1079   $PG_random_generator->random($begin,$end,$incr);
 1080 }
 1081 
 1082 
 1083 sub non_zero_random { ##gives a non-zero random number
 1084   my (@arguments)=@_;
 1085   my $a=0;
 1086   my $i=100; #safety counter
 1087   while ($a==0 && ( 0 < $i-- ) ) {
 1088     $a=random(@arguments);
 1089   }
 1090   $a;
 1091 }
 1092 
 1093 sub list_random {
 1094         my(@li) = @_;
 1095         return $li[random(1,scalar(@li))-1];
 1096 }
 1097 
 1098 sub SRAND { # resets the main random generator -- use cautiously
 1099     my $seed = shift;
 1100   $PG_random_generator -> srand($seed);
 1101 }
 1102 
 1103 # display macros
 1104 
 1105 =head2 Display Macros
 1106 
 1107 These macros produce different output depending on the display mode being used to show
 1108 the problem on the screen, or whether the problem is being converted to TeX to produce
 1109 a hard copy output.
 1110 
 1111   MODES   ( TeX =>        "Output this in TeX mode",
 1112             HTML =>       "output this in HTML mode",
 1113             HTML_tth =>   "output this in HTML_tth mode",
 1114             HTML_dpng =>   "output this in HTML_dpng mode",
 1115             Latex2HTML => "output this in Latex2HTML mode",
 1116            )
 1117 
 1118   TEX     (tex_version, html_version) #obsolete
 1119 
 1120   M3      (tex_version, latex2html_version, html_version) #obsolete
 1121 
 1122 
 1123 
 1124 =cut
 1125 
 1126 
 1127 sub TEX {
 1128   my ($tex, $html ) = @_;
 1129   MODES(TeX => $tex, HTML => $html, HTML_tth => $html, HTML_dpng => $html);
 1130 }
 1131 
 1132 
 1133 sub M3 {
 1134   my($tex,$l2h,$html) = @_;
 1135   MODES(TeX => $tex, Latex2HTML => $l2h, HTML => $html, HTML_tth => $html, HTML_dpng => $html);
 1136 }
 1137 
 1138 # MODES() is now table driven
 1139 our %DISPLAY_MODE_FAILOVER = (
 1140   TeX              => [],
 1141   HTML             => [],
 1142   HTML_tth         => [ "HTML", ],
 1143   HTML_dpng        => [ "HTML_tth", "HTML", ],
 1144   HTML_jsMath      => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1145   HTML_asciimath   => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1146   HTML_LaTeXMathML => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1147   # legacy modes -- these are not supported, but some problems might try to
 1148   # set the display mode to one of these values manually and some macros may
 1149   # provide rendered versions for these modes but not the one we want.
 1150   Latex2HTML  => [ "TeX", "HTML", ],
 1151   HTML_img    => [ "HTML_dpng", "HTML_tth", "HTML", ],
 1152 );
 1153 
 1154 # This replaces M3.  You can add new modes at will to this one.
 1155 sub MODES {
 1156   my %options = @_;
 1157 
 1158   # is a string supplied for the current display mode? if so, return it
 1159   return $options{$displayMode} if defined $options{$displayMode};
 1160 
 1161   # otherwise, fail over to backup modes
 1162   my @backup_modes;
 1163   if (exists $DISPLAY_MODE_FAILOVER{$displayMode}) {
 1164     @backup_modes = @{$DISPLAY_MODE_FAILOVER{$displayMode}};
 1165     foreach my $mode (@backup_modes) {
 1166       return $options{$mode} if defined $options{$mode};
 1167     }
 1168   }
 1169   die "ERROR in defining MODES: neither display mode $displayMode nor",
 1170     " any fallback modes (", join(", ", @backup_modes), ") supplied.\n";
 1171 }
 1172 
 1173 # end display macros
 1174 
 1175 
 1176 =head2  Display constants
 1177 
 1178   @ALPHABET       ALPHABET()      capital letter alphabet -- ALPHABET[0] = 'A'
 1179   $PAR        PAR()       paragraph character (\par or <p>)
 1180   $BR             BR()        line break character
 1181   $LQ         LQ()        left double quote
 1182   $RQ         RQ()        right double quote
 1183   $BM         BM()        begin math
 1184   $EM         EM()        end math
 1185   $BDM        BDM()       begin display math
 1186   $EDM        EDM()       end display math
 1187   $LTS        LTS()       strictly less than
 1188   $GTS        GTS()       strictly greater than
 1189   $LTE        LTE()       less than or equal
 1190   $GTE        GTE()       greater than or equal
 1191   $BEGIN_ONE_COLUMN BEGIN_ONE_COLUMN()  begin one-column mode
 1192   $END_ONE_COLUMN   END_ONE_COLUMN()  end one-column mode
 1193   $SOL        SOLUTION_HEADING()  solution headline
 1194   $SOLUTION     SOLUTION_HEADING()  solution headline
 1195   $HINT       HINT_HEADING()    hint headline
 1196   $US         US()        underscore character
 1197   $SPACE        SPACE()       space character (tex and latex only)
 1198   $BBOLD        BBOLD()       begin bold typeface
 1199   $EBOLD        EBOLD()       end bold typeface
 1200   $BITALIC        BITALIC()       begin italic typeface
 1201   $EITALIC        EITALIC()       end italic typeface
 1202   $BCENTER        BCENTER()       begin centered environment
 1203   $ECENTER        ECENTER()       end centered environment
 1204   $HR         HR()        horizontal rule
 1205   $LBRACE       LBRACE()      left brace
 1206   $LB         LB ()       left brace
 1207   $RBRACE       RBRACE()      right brace
 1208   $RB         RB ()       right brace
 1209   $DOLLAR       DOLLAR()      a dollar sign
 1210   $PERCENT      PERCENT()     a percent sign
 1211   $CARET        CARET()       a caret sign
 1212   $PI         PI()        the number pi
 1213   $E          E()         the number e
 1214 
 1215 =cut
 1216 
 1217 
 1218 
 1219 
 1220 
 1221 # A utility variable.  Notice that "B"=$ALPHABET[1] and
 1222 # "ABCD"=@ALPHABET[0..3].
 1223 
 1224 sub ALPHABET  {
 1225   ('A'..'ZZ')[@_];
 1226 }
 1227 
 1228 ###############################################################
 1229 # Some constants which are different in tex and in HTML
 1230 # The order of arguments is TeX, Latex2HTML, HTML
 1231 # Adopted Davide Cervone's improvements to PAR, LTS, GTS, LTE, GTE, LBRACE, RBRACE, LB, RB. 7-14-03 AKP
 1232 sub PAR { MODES( TeX => '\\par ', Latex2HTML => '\\begin{rawhtml}<P>\\end{rawhtml}', HTML => '<P>'); };
 1233 sub BR { MODES( TeX => '\\par\\noindent ', Latex2HTML => '\\begin{rawhtml}<BR>\\end{rawhtml}', HTML => '<BR>'); };
 1234 # Alternate definition of BR which is slightly more flexible and gives more white space in printed output
 1235 # which looks better but kills more trees.
 1236 #sub BR { MODES( TeX => '\\leavevmode\\\\', Latex2HTML => '\\begin{rawhtml}<BR>\\end{rawhtml}', HTML => '<BR>'); };
 1237 sub LQ { MODES( TeX => "``", Latex2HTML =>   '"',  HTML =>  '&quot;' ); };
 1238 sub RQ { MODES( TeX => "''", Latex2HTML =>   '"',   HTML =>  '&quot;' ); };
 1239 sub BM { MODES(TeX => '\\(', Latex2HTML => '\\(', HTML =>  ''); };  # begin math mode
 1240 sub EM { MODES(TeX => '\\)', Latex2HTML => '\\)', HTML => ''); };  # end math mode
 1241 sub BDM { MODES(TeX => '\\[', Latex2HTML =>   '\\[', HTML =>   '<P ALIGN=CENTER>'); };  #begin displayMath mode
 1242 sub EDM { MODES(TeX => '\\]',  Latex2HTML =>  '\\]', HTML => '</P>'); };              #end displayMath mode
 1243 sub LTS { MODES(TeX => '<', Latex2HTML => '\\lt ', HTML => '&lt;', HTML_tth => '<' ); };
 1244 sub GTS { MODES(TeX => '>', Latex2HTML => '\\gt ', HTML => '&gt;', HTML_tth => '>' ); };
 1245 sub LTE { MODES(TeX => '\\le ', Latex2HTML => '\\le ', HTML => '<U>&lt;</U>', HTML_tth => '\\le ' ); };
 1246 sub GTE { MODES(TeX => '\\ge ', Latex2HTML => '\\ge ', HTML => '<U>&gt;</U>', HTML_tth => '\\ge ' ); };
 1247 sub BEGIN_ONE_COLUMN { MODES(TeX => " \\end{multicols}\n",  Latex2HTML => " ", HTML =>   " "); };
 1248 sub END_ONE_COLUMN { MODES(TeX =>
 1249               " \\begin{multicols}{2}\n\\columnwidth=\\linewidth\n",
 1250                             Latex2HTML => ' ', HTML => ' ');
 1251 
 1252 };
 1253 sub SOLUTION_HEADING { MODES( TeX => '\\par {\\bf Solution:}',
 1254                  Latex2HTML => '\\par {\\bf Solution:}',
 1255                HTML =>  '<P><B>Solution:</B>');
 1256               };
 1257 sub HINT_HEADING { MODES( TeX => "\\par {\\bf Hint:}", Latex2HTML => "\\par {\\bf Hint:}", HTML => "<P><B>Hint:</B>"); };
 1258 sub US { MODES(TeX => '\\_', Latex2HTML => '\\_', HTML => '_');};  # underscore, e.g. file${US}name
 1259 sub SPACE { MODES(TeX => '\\ ',  Latex2HTML => '\\ ', HTML => '&nbsp;');};  # force a space in latex, doesn't force extra space in html
 1260 sub BBOLD { MODES(TeX => '{\\bf ',  Latex2HTML => '{\\bf ', HTML => '<B>'); };
 1261 sub EBOLD { MODES( TeX => '}', Latex2HTML =>  '}',HTML =>  '</B>'); };
 1262 sub BITALIC { MODES(TeX => '{\\it ',  Latex2HTML => '{\\it ', HTML => '<I>'); };
 1263 sub EITALIC { MODES(TeX => '} ',  Latex2HTML => '} ', HTML => '</I>'); };
 1264 sub BCENTER { MODES(TeX => '\\begin{center} ',  Latex2HTML => ' \\begin{rawhtml} <div align="center"> \\end{rawhtml} ', HTML => '<div align="center">'); };
 1265 sub ECENTER { MODES(TeX => '\\end{center} ',  Latex2HTML => ' \\begin{rawhtml} </div> \\end{rawhtml} ', HTML => '</div>'); };
 1266 sub HR { MODES(TeX => '\\par\\hrulefill\\par ', Latex2HTML => '\\begin{rawhtml} <HR> \\end{rawhtml}', HTML =>  '<HR>'); };
 1267 sub LBRACE { MODES( TeX => '\{', Latex2HTML =>   '\\lbrace',  HTML =>  '{' , HTML_tth=> '\\lbrace' ); };
 1268 sub RBRACE { MODES( TeX => '\}', Latex2HTML =>   '\\rbrace',  HTML =>  '}' , HTML_tth=> '\\rbrace',); };
 1269 sub LB { MODES( TeX => '\{', Latex2HTML =>   '\\lbrace',  HTML =>  '{' , HTML_tth=> '\\lbrace' ); };
 1270 sub RB { MODES( TeX => '\}', Latex2HTML =>   '\\rbrace',  HTML =>  '}' , HTML_tth=> '\\rbrace',); };
 1271 sub DOLLAR { MODES( TeX => '\\$', Latex2HTML => '&#36;', HTML => '&#36;' ); };
 1272 sub PERCENT { MODES( TeX => '\\%', Latex2HTML => '\\%', HTML => '%' ); };
 1273 sub CARET { MODES( TeX => '\\verb+^+', Latex2HTML => '\\verb+^+', HTML => '^' ); };
 1274 sub PI {4*atan2(1,1);};
 1275 sub E {exp(1);};
 1276 
 1277 ###############################################################
 1278 ## Evaluation macros
 1279 
 1280 
 1281 =head2 TEXT macros
 1282 
 1283   Usage:
 1284     TEXT(@text);
 1285 
 1286 This is the simplest way to print text from a problem.  The strings in the array C<@text> are concatenated
 1287 with spaces between them and printed out in the text of the problem.  The text is not processed in any other way.
 1288 C<TEXT> is defined in PG.pl.
 1289 
 1290   Usage:
 1291     BEGIN_TEXT
 1292       text.....
 1293     END_TEXT
 1294 
 1295 This is the most common way to enter text into the problem.  All of the text between BEGIN_TEXT and END_TEXT
 1296 is processed by the C<EV3> macro described below and then printed using the C<TEXT> command.  The two key words
 1297 must appear on lines by themselves.  The preprocessing that makes this construction work is done in F<PGtranslator.pm>.
 1298 See C<EV3> below for details on the processing.
 1299 
 1300 
 1301 =cut
 1302 
 1303 =head2 Evaluation macros
 1304 
 1305 =head3 EV3
 1306 
 1307         TEXT(EV3("This is a formulat \( \int_0^5 x^2 \, dx \) ");
 1308         TEXT(EV3(@text));
 1309 
 1310     TEXT(EV3(<<'END_TEXT'));
 1311       text stuff...
 1312     END_TEXT
 1313 
 1314 
 1315 The BEGIN_TEXT/END_TEXT construction is translated into the construction above by PGtranslator.pm.  END_TEXT must appear
 1316 on a line by itself and be left justified.  (The << construction is known as a "here document" in UNIX and in PERL.)
 1317 
 1318 The single quotes around END_TEXT mean that no automatic interpolation of variables takes place in the text.
 1319 Using EV3 with strings which have been evaluated by double quotes may lead to unexpected results.
 1320 
 1321 
 1322 The evaluation macro E3 first evaluates perl code inside the braces:  C<\{  code \}>.
 1323 Any perl statment can be put inside the braces.  The
 1324 result of the evaluation (i.e. the last statement evaluated) replaces the C<\{ code \}> construction.
 1325 
 1326 Next interpolation of all variables (e.g. C<$var or @array> ) is performed.
 1327 
 1328 Then mathematical formulas in TeX are evaluated within the
 1329 C<\(  tex math mode \)> and
 1330 C<\[ tex display math mode \] >
 1331 constructions, in that order:
 1332 
 1333 =head3 FEQ
 1334 
 1335   FEQ($string);   # processes and outputs the string
 1336 
 1337 
 1338 The mathematical formulas are run through the macro C<FEQ> (Format EQuations) which performs
 1339 several substitutions (see below).
 1340 In C<HTML_tth> mode the resulting code is processed by tth to obtain an HTML version
 1341 of the formula. (In the future processing by WebEQ may be added here as another option.)
 1342 The Latex2HTML mode does nothing
 1343 at this stage; it creates the entire problem before running it through
 1344 TeX and creating the GIF images of the equations.
 1345 
 1346 The resulting string is output (and usually fed into TEXT to be printed in the problem).
 1347 
 1348   Usage:
 1349 
 1350     $string2 = FEQ($string1);
 1351 
 1352 This is a filter which is used to format equations by C<EV2> and C<EV3>, but can also be used on its own.  It is best
 1353 understood with an example.
 1354 
 1355     $string1 = "${a}x^2 + ${b}x + {$c:%.1f}"; $a = 3;, $b = -2; $c = -7.345;
 1356 
 1357 when interpolated becomes:
 1358 
 1359     $string1 = '3x^2 + -2x + {-7.345:%0.1f}
 1360 
 1361 FEQ first changes the number of decimal places displayed, so that the last term becomes -7.3 Then it removes the
 1362 extraneous plus and minus signs, so that the final result is what you want:
 1363 
 1364     $string2 = '3x^2 - 2x -7.3';
 1365 
 1366 (The %0.1f construction
 1367 is the same formatting convention used by Perl and nearly identical to the one used by the C printf statement. Some common
 1368 usage:  %0.3f 3 decimal places, fixed notation; %0.3e 3 significant figures exponential notation; %0.3g uses either fixed
 1369 or exponential notation depending on the size of the number.)
 1370 
 1371 Two additional legacy formatting constructions are also supported:
 1372 
 1373 C<?{$c:%0.3f} > will give a number with 3 decimal places and a negative
 1374 sign if the number is negative, no sign if the number is positive.
 1375 
 1376 C<!{$c:%0.3f}> determines the sign and prints it
 1377 whether the number is positive or negative.
 1378 
 1379 =head3 EV2
 1380 
 1381     TEXT(EV2(@text));
 1382 
 1383     TEXT(EV2(<<END_OF_TEXT));
 1384       text stuff...
 1385     END_OF_TEXT
 1386 
 1387 This is a precursor to EV3.  In this case the constants are interpolated first, before the evaluation of the \{ ...code...\}
 1388 construct. This can lead to unexpected results.  For example C<\{ join(" ", @text) \}> with C<@text = ("Hello","World");> becomes,
 1389 after interpolation, C<\{ join(" ",Hello World) \}> which then causes an error when evaluated because Hello is a bare word.
 1390 C<EV2> can still be useful if you allow for this, and in particular it works on double quoted strings, which lead to
 1391 unexpected results with C<EV3>. Using single quoted strings with C<EV2> may lead to unexpected results.
 1392 
 1393 The unexpected results have to do with the number of times backslashed constructions have to be escaped. It is quite messy.  For
 1394 more details get a good Perl book and then read the code. :-)
 1395 
 1396 
 1397 
 1398 
 1399 =cut
 1400 
 1401 
 1402 sub ev_substring {
 1403     my $string      = shift;
 1404   my $start_delim = shift;
 1405   my $end_delim   = shift;
 1406   my $actionRef   = shift;
 1407   my ($eval_out,$PG_eval_errors,$PG_full_error_report)=();
 1408     my $out = "";
 1409                 #
 1410                 #  DPVC -- 2001/12/07
 1411                 #     original "while ($string)" fails to process the string "0" correctly
 1412                 #
 1413     while ($string ne "") {
 1414                 #
 1415                 #  end DPVC
 1416                 #
 1417         if ($string =~ /\Q$start_delim\E/s) {
 1418        #print "$start_delim $end_delim evaluating_substring=$string<BR>";
 1419         $string =~ s/^(.*?)\Q$start_delim\E//s;  # get string up to next \{ ---treats string as a single line, ignoring returns
 1420         $out .= $1;
 1421        #print "$start_delim $end_delim substring_out=$out<BR>";
 1422         $string =~ s/^(.*?)\Q$end_delim\E//s;  # get perl code up to \} ---treats string as a single line,  ignoring returns
 1423            #print "$start_delim $end_delim evaluate_string=$1<BR>";
 1424         ($eval_out,$PG_eval_errors,$PG_full_error_report) = &$actionRef($1);
 1425         $eval_out = "$start_delim $eval_out $end_delim" if $PG_full_error_report;
 1426         $out = $out . $eval_out;
 1427        #print "$start_delim $end_delim new substring_out=$out<BR><p><BR>";
 1428         $out .="$PAR ERROR $0 in ev_substring, PGbasicmacros.pl:$PAR <PRE>  $@ </PRE>$PAR" if $@;
 1429         }
 1430       else {
 1431         $out .= $string;  # flush the last part of the string
 1432         last;
 1433         }
 1434 
 1435       }
 1436   $out;
 1437 }
 1438 sub  safe_ev {
 1439     my ($out,$PG_eval_errors,$PG_full_error_report) = &old_safe_ev;   # process input by old_safe_ev first
 1440     $out =~s/\\/\\\\/g;   # protect any new backslashes introduced.
 1441   ($out,$PG_eval_errors,$PG_full_error_report)
 1442 }
 1443 
 1444 sub  old_safe_ev {
 1445     my $in = shift;
 1446     my   ($out,$PG_eval_errors,$PG_full_error_report) = PG_restricted_eval("$in;");
 1447     # the addition of the ; seems to provide better error reporting
 1448     if ($PG_eval_errors) {
 1449       my @errorLines = split("\n",$PG_eval_errors);
 1450     #$out = "<PRE>$PAR % ERROR in $0:old_safe_ev, PGbasicmacros.pl: $PAR % There is an error occuring inside evaluation brackets \\{ ...code... \\} $BR % somewhere in an EV2 or EV3 or BEGIN_TEXT block. $BR % Code evaluated:$BR $in $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR % $BR % $BR </PRE> ";
 1451     warn " ERROR in old_safe_ev, PGbasicmacros.pl: <PRE>
 1452      ## There is an error occuring inside evaluation brackets \\{ ...code... \\}
 1453      ## somewhere in an EV2 or EV3 or BEGIN_TEXT block.
 1454      ## Code evaluated:
 1455      ## $in
 1456      ##" .join("\n     ", @errorLines). "
 1457      ##</PRE>$BR
 1458      ";
 1459      $out ="$PAR $BBOLD  $in $EBOLD $PAR";
 1460 
 1461 
 1462   }
 1463 
 1464   ($out,$PG_eval_errors,$PG_full_error_report);
 1465 }
 1466 
 1467 sub FEQ   {    # Format EQuations
 1468   my $in = shift;
 1469    # formatting numbers -- the ?{} and !{} constructions
 1470   $in =~s/\?\s*\{([.\-\$\w\d]+):?([%.\da-z]*)\}/${ \( &sspf($1,$2) )}/g;
 1471   $in =~s/\!\s*\{([.\-\$\w\d]+):?([%.\da-z]*)\}/${ \( &spf($1,$2) )}/g;
 1472 
 1473   # more formatting numbers -- {number:format} constructions
 1474   $in =~ s/\{(\s*[\+\-\d\.]+[eE]*[\+\-]*\d*):(\%\d*.\d*\w)}/${ \( &spf($1,$2) )}/g;
 1475   $in =~ s/\+\s*\-/ - /g;
 1476   $in =~ s/\-\s*\+/ - /g;
 1477   $in =~ s/\+\s*\+/ + /g;
 1478   $in =~ s/\-\s*\-/ + /g;
 1479   $in;
 1480 }
 1481 
 1482 #sub math_ev3 {
 1483 # my $in = shift; #print "in=$in<BR>";
 1484 # my ($out,$PG_eval_errors,$PG_full_error_report);
 1485 # $in = FEQ($in);
 1486 # $in =~ s/%/\\%/g;   #  % causes trouble in TeX and HTML_tth it usually (always?) indicates an error, not comment
 1487 # return("$BM $in $EM") unless ($displayMode eq 'HTML_tth');
 1488 # $in = "\\(" . $in . "\\)";
 1489 # $out = tth($in);
 1490 # ($out,$PG_eval_errors,$PG_full_error_report);
 1491 #
 1492 #}
 1493 #
 1494 #sub display_math_ev3 {
 1495 # my $in = shift; #print "in=$in<BR>";
 1496 # my ($out,$PG_eval_errors,$PG_full_error_report);
 1497 # $in = FEQ($in);
 1498 # $in =~ s/%/\\%/g;
 1499 # return("$main::BDM $in $main::EDM") unless $displayMode eq 'HTML_tth' ;
 1500 # $in = "\\[" . $in . "\\]";
 1501 # $out =tth($in);
 1502 # ($out,$PG_eval_errors,$PG_full_error_report);
 1503 #}
 1504 
 1505 sub math_ev3 {
 1506   my $in = shift;
 1507   return general_math_ev3($in, "inline");
 1508 }
 1509 
 1510 sub display_math_ev3 {
 1511   my $in = shift;
 1512   return general_math_ev3($in, "display");
 1513 }
 1514 
 1515 sub general_math_ev3 {
 1516   my $in = shift;
 1517   my $mode = shift || "inline";
 1518 
 1519   $in = FEQ($in); # Format EQuations
 1520   $in =~ s/%/\\%/g; # avoid % becoming TeX comments
 1521 
 1522   ## remove leading and trailing spaces so that HTML mode will
 1523   ## not include unwanted spaces as per Davide Cervone.
 1524   $in =~ s/^\s+//;
 1525   $in =~ s/\s+$//;
 1526   ## If it ends with a backslash, there should be another space
 1527   ## at the end
 1528   if($in =~ /\\$/) { $in .= ' ';}
 1529 
 1530   # some modes want the delimiters, some don't
 1531   my $in_delim = $mode eq "inline"
 1532     ? "\\($in\\)"
 1533     : "\\[$in\\]";
 1534 
 1535   my $out;
 1536   if($displayMode eq "HTML_tth") {
 1537     $out = tth($in_delim);
 1538     ## remove leading and trailing spaces as per Davide Cervone.
 1539     $out =~ s/^\s+//;
 1540     $out =~ s/\s+$//;
 1541   } elsif ($displayMode eq "HTML_dpng") {
 1542     # for jj's version of ImageGenerator
 1543     $out = $envir->{'imagegen'}->add($in_delim);
 1544     # for my version of ImageGenerator
 1545     #$out = $envir->{'imagegen'}->add($in, $mode);
 1546   } elsif ($displayMode eq "HTML_img") {
 1547     $out = math2img($in, $mode);
 1548   } elsif ($displayMode eq "HTML_jsMath") {
 1549     $in =~ s/</&lt;/g; $in =~ s/>/&gt;/g;
 1550     $out = '<SPAN CLASS="math">'.$in.'</SPAN>' if $mode eq "inline";
 1551     $out = '<DIV CLASS="math">'.$in.'</DIV>' if $mode eq "display";
 1552   } elsif ($displayMode eq "HTML_asciimath") {
 1553     $out = "`$in`" if $mode eq "inline";
 1554     $out = '<DIV ALIGN="CENTER">`'.$in.'`</DIV>' if $mode eq "display";
 1555   } elsif ($displayMode eq "HTML_LaTeXMathML") {
 1556     $in = '{'.$in.'}';
 1557     $in =~ s/</\\lt/g; $in =~ s/>/\\gt/g;
 1558     $in =~ s/\{\s*(\\(display|text|script|scriptscript)style)/$1\{/g;
 1559     $out = '$$'.$in.'$$' if $mode eq "inline";
 1560     $out = '<DIV ALIGN="CENTER">$$\displaystyle{'.$in.'}$$</DIV>' if $mode eq "display";
 1561   } else {
 1562     $out = "\\($in\\)" if $mode eq "inline";
 1563     $out = "\\[$in\\]" if $mode eq "display";
 1564   }
 1565   return $out;
 1566 }
 1567 
 1568 sub EV2 {
 1569   my $string = join(" ",@_);
 1570   # evaluate code inside of \{  \}  (no nesting allowed)
 1571     $string = ev_substring($string,"\\{","\\}",\&old_safe_ev);
 1572     $string = ev_substring($string,"\\<","\\>",\&old_safe_ev);
 1573   $string = ev_substring($string,"\\(","\\)",\&math_ev3);
 1574   $string = ev_substring($string,"\\[","\\]",\&display_math_ev3);
 1575   # macros for displaying math
 1576   $string =~ s/\\\(/$BM/g;
 1577   $string =~ s/\\\)/$EM/g;
 1578   $string =~ s/\\\[/$BDM/g;
 1579   $string =~ s/\\\]/$EDM/g;
 1580   $string;
 1581 }
 1582 
 1583 sub EV3{
 1584   my $string = join(" ",@_);
 1585   # evaluate code inside of \{  \}  (no nesting allowed)
 1586     $string = ev_substring($string,"\\\\{","\\\\}",\&safe_ev);  # handles \{ \} in single quoted strings of PG files
 1587   # interpolate variables
 1588   my ($evaluated_string,$PG_eval_errors,$PG_full_errors) = PG_restricted_eval("<<END_OF_EVALUATION_STRING\n$string\nEND_OF_EVALUATION_STRING\n");
 1589   if ($PG_eval_errors) {
 1590       my @errorLines = split("\n",$PG_eval_errors);
 1591       $string =~ s/</&lt;/g; $string =~ s/>/&gt;/g;
 1592     $evaluated_string = "<PRE>$PAR % ERROR in $0:EV3, PGbasicmacros.pl: $PAR % There is an error occuring in the following code:$BR $string $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR % $BR % $BR </PRE> ";
 1593     $@="";
 1594   }
 1595   $string = $evaluated_string;
 1596   $string = ev_substring($string,"\\(","\\)",\&math_ev3);
 1597     $string = ev_substring($string,"\\[","\\]",\&display_math_ev3);
 1598   $string;
 1599 }
 1600 
 1601 sub EV4{
 1602     if ($displayMode eq "HTML_dpng") {
 1603         my $string = join(" ",@_);
 1604         my ($evaluated_string,$PG_eval_errors,$PG_full_errors) = PG_restricted_eval("<<END_OF_EVALUATION_STRING\n$string\nEND_OF_EVALUATION_STRING\n");
 1605         if ($PG_eval_errors) {
 1606             my @errorLines = split("\n",$PG_eval_errors);
 1607             $string =~ s/</&lt;/g; $string =~ s/>/&gt;/g;
 1608             $evaluated_string = "<PRE>$PAR % ERROR in $0:EV3, PGbasicmacros.pl:".
 1609       "$PAR % There is an error occuring in the following code:$BR ".
 1610       "$string $BR % $BR % $errorLines[0]\n % $errorLines[1]$BR ".
 1611       "% $BR % $BR </PRE> ";
 1612         }
 1613         $string = $evaluated_string;
 1614         $string = $envir{'imagegen'}->add($string);
 1615         $string;
 1616     } else {
 1617       EV3(@_);
 1618     }
 1619 }
 1620 
 1621 
 1622 =head2 Formatting macros
 1623 
 1624   beginproblem()  # generates text listing number and the point value of
 1625                   # the problem. It will also print the file name containing
 1626                   # the problem for users listed in the PRINT_FILE_NAMES_FOR PG_environment
 1627                   # variable.
 1628   OL(@array)      # formats the array as an Ordered List ( <OL> </OL> ) enumerated by letters.
 1629 
 1630   htmlLink($url, $text)
 1631                   # Places a reference to the URL with the specified text in the problem.
 1632                   # A common usage is \{ htmlLink(alias('prob1_help.html') \}, 'for help')
 1633                   # where alias finds the full address of the prob1_help.html file in the same directory
 1634                   # as the problem file
 1635   appletLink( { name => "xFunctions",
 1636                 codebase => '',    # use this to specify the complete url
 1637                                    # otherwise libraries specified in global.conf are searched
 1638                 archive  => 'xFunctions.zip', # name the archive containing code (.jar files go here also)
 1639                 code     => 'xFunctionsLauncher.class',
 1640                 width    => 100,
 1641                 height   => 14,
 1642                 params   => { param1 =>value1, param2 => value2},
 1643               }
 1644             );
 1645   helpLink()     allows site specific help specified in global.conf or course.conf
 1646                  the parameter localHelpURL  must be defined in the environment
 1647                  currently works only for 'interval notation' and 'units'
 1648                  NEEDS REFINEMENT
 1649 
 1650   ########################
 1651                 deprecated coding method
 1652           appletLink  ($url, $parameters)
 1653                   # For example
 1654                   # appletLink(q!  archive="http: //webwork.math.rochester.edu/gage/xFunctions/xFunctions.zip"
 1655                                   code="xFunctionsLauncher.class"  width=100 height=14!,
 1656                   " parameter text goes here")
 1657                   # will link to xFunctions.
 1658 
 1659   low level:
 1660 
 1661   spf($number, $format)   # prints the number with the given format
 1662   sspf($number, $format)  # prints the number with the given format, always including a sign.
 1663   nicestring($coefficients, $terms) # print a linear combinations of terms using coefficients
 1664   nicestring($coefficients) # uses the coefficients to make a polynomial
 1665       # For example
 1666       # nicestring([1,-2, 0]) produces 'x^2-2x'
 1667       # nicestring([2,0,-1],['', 't', 't^2']) produces '2-t^2'
 1668   protect_underbar($string) # protects the underbar (class_name) in strings which may have to pass through TeX.
 1669 
 1670 =cut
 1671 
 1672 sub beginproblem {
 1673   my $out = "";
 1674   my $problemValue = $envir->{problemValue};
 1675   my $fileName     = $envir->{fileName};
 1676   my $probNum      = $envir->{probNum};
 1677     my $TeXFileName = protect_underbar($envir->{fileName});
 1678     my $l2hFileName = protect_underbar($envir->{fileName});
 1679   my %inlist;
 1680   my $points ='pts';
 1681 
 1682   $points = 'pt' if $problemValue == 1;
 1683   ##    Prepare header for the problem
 1684   grep($inlist{$_}++,@{ $envir->{'PRINT_FILE_NAMES_FOR'} });
 1685   if ( defined($inlist{$envir->{studentLogin}}) and ($inlist{$envir->{studentLogin}} > 0) ) {
 1686     $out = &M3("{\\bf ${probNum}. {\\footnotesize ($problemValue $points) $TeXFileName}}\\newline ",
 1687     " \\begin{rawhtml} ($problemValue $points) <B>$l2hFileName</B><BR>\\end{rawhtml}",
 1688      "($problemValue $points) <B>$fileName</B><BR>"
 1689        ) if ($problemValue ne "");
 1690   } else {
 1691     $out = &M3("{\\bf ${probNum}.} ($problemValue $points) ",
 1692     "($problemValue $points) ",
 1693      "($problemValue $points) "
 1694        ) if ($problemValue ne "");
 1695   }
 1696   $out .= MODES(%{main::PG_restricted_eval(q!$main::problemPreamble!)});
 1697   $out;
 1698 
 1699 }
 1700 
 1701 sub nicestring {
 1702     my($thingy) = shift;
 1703     my(@coefs) = @{$thingy};
 1704     my $n = scalar(@coefs);
 1705     $thingy = shift;
 1706     my(@others);
 1707     if(defined($thingy)) {
 1708   @others = @{$thingy};
 1709     } else {
 1710   my($j);
 1711   for $j (1..($n-2)) {
 1712       $others[$j-1] = "x^".($n-$j);
 1713   }
 1714   if($n>=2) { $others[$n-2] = "x";}
 1715   $others[$n-1] = "";
 1716     }
 1717     my($j, $k)=(0,0);
 1718     while(($k<$n) && ($coefs[$k]==0)) {$k++;}
 1719     if($k==$n) {return("0");}
 1720     my $ans;
 1721     if($coefs[$k]==1) {$ans = ($others[$k]) ? "$others[$k]" : "1";}
 1722     elsif($coefs[$k]== -1) {$ans =  ($others[$k]) ? "- $others[$k]" : "-1"}
 1723     else { $ans = "$coefs[$k] $others[$k]";}
 1724     $k++;
 1725     for $j ($k..($n-1)) {
 1726   if($coefs[$j] != 0) {
 1727       if($coefs[$j] == 1) {
 1728     $ans .= ($others[$j]) ? "+ $others[$j]" : "+ 1";
 1729       } elsif($coefs[$j] == -1) {
 1730     $ans .= ($others[$j]) ? "- $others[$j]" : "-1";
 1731       } else {
 1732     $ans .= "+ $coefs[$j] $others[$j]";
 1733       }
 1734   }
 1735     }
 1736     return($ans);
 1737 }
 1738 
 1739 # kludge to clean up path names
 1740             ## allow underscore character in set and section names and also allows line breaks at /
 1741 sub protect_underbar {
 1742     my $in = shift;
 1743     if ($displayMode eq 'TeX')  {
 1744 
 1745         $in =~ s|_|\\\_|g;
 1746         $in =~ s|/|\\\-/|g;  # allows an optional hyphenation of the path (in tex)
 1747     }
 1748     $in;
 1749 }
 1750 
 1751 
 1752 # An example of a macro which prints out a list (with letters)
 1753 sub OL {
 1754   my(@array) = @_;
 1755   my $i = 0;
 1756   my @alpha = ('A'..'Z', 'AA'..'ZZ');
 1757   my $letter;
 1758   my  $out=   &M3(
 1759           "\\begin{enumerate}\n",
 1760           " \\begin{rawhtml} <OL TYPE=\"A\" VALUE=\"1\"> \\end{rawhtml} ",
 1761           # kludge to fix IE/CSS problem
 1762           #"<OL TYPE=\"A\" VALUE=\"1\">\n"
 1763           "<BLOCKQUOTE>\n"
 1764           ) ;
 1765   my $elem;
 1766   foreach $elem (@array) {
 1767     $letter = shift @alpha;
 1768                 $out .= MODES(
 1769                         TeX=>   "\\item[$ALPHABET[$i].] $elem\n",
 1770                         Latex2HTML=>    " \\begin{rawhtml} <LI> \\end{rawhtml} $elem  ",
 1771                         #HTML=>  "<LI> $elem\n",
 1772                         HTML=>  "<br /> <b>$letter.</b> $elem\n",
 1773                         #HTML_dpng=>     "<LI> $elem <br /> <br /> \n"
 1774                         HTML_dpng=>     "<br /> <b>$letter.</b> $elem \n"
 1775                                         );
 1776     $i++;
 1777   }
 1778   $out .= &M3(
 1779         "\\end{enumerate}\n",
 1780         " \\begin{rawhtml} </OL>\n \\end{rawhtml} ",
 1781         #"</OL>\n"
 1782         "</BLOCKQUOTE>\n"
 1783         ) ;
 1784 }
 1785 
 1786 sub htmlLink {
 1787   my $url = shift;
 1788   my $text = shift;
 1789   my $options = shift;
 1790   $options = "" unless defined($options);
 1791   return "$BBOLD\[ broken link:  $text \] $EBOLD" unless defined($url);
 1792   M3( "{\\bf \\underline{$text}}",
 1793       "\\begin{rawhtml}<A HREF=\"$url\" $options>$text</A>\\end{rawhtml}",
 1794       "<A HREF=\"$url\" $options>$text</A>"
 1795       );
 1796 }
 1797 
 1798 
 1799 sub helpLink {
 1800   my $type1 = shift;
 1801   return "" if(not defined($envir{'localHelpURL'}));
 1802   my $type = lc($type1);
 1803   my %typeHash = (
 1804     'interval notation' => 'IntervalNotation.html',
 1805     'units' => 'Units.html',
 1806     );
 1807 
 1808   my $infoRef = $typeHash{$type};
 1809   return htmlLink( $envir{'localHelpURL'}.$infoRef, $type1,
 1810 'target="ww_help" onclick="window.open(this.href,this.target,\'width=550,height=350,scrollbars=yes,resizable=on\'); return false;"');
 1811 }
 1812 
 1813 sub appletLink {
 1814   my $url  = $_[0];
 1815   return oldAppletLink(@_) unless ref($url) ; # handle legacy where applet link completely defined
 1816   # search for applet
 1817   # get fileName of applet
 1818   my $applet       = shift;
 1819   my $options      = shift;
 1820   my $archive      = $applet ->{archive};
 1821   my $codebase     = $applet ->{codebase};
 1822   my $code         = $applet ->{code};
 1823   my $appletHeader = '';
 1824   # find location of applet
 1825     if (defined($codebase) and $codebase =~/\S/) {
 1826       # do nothing
 1827     } elsif(defined($archive) and $archive =~/\S/) {
 1828       $codebase = findAppletCodebase($archive )
 1829     } elsif (defined($code) and $code =~/\S/) {
 1830       $codebase =  findAppletCodebase($code )
 1831     } else {
 1832       warn "Must define the achive (.jar file) or code (.class file) where the applet code is to be found";
 1833       return;
 1834     }
 1835 
 1836   if ( $codebase =~/^Error/) {
 1837     warn $codebase;
 1838     return;
 1839   } else {
 1840      # we are set to include the applet
 1841   }
 1842   my $appletHeader  =  qq! archive = "$archive " codebase = "$codebase" !;
 1843   foreach my $key ('name', 'code','width','height', ) {
 1844     if ( defined($applet->{$key})   ) {
 1845       $appletHeader .= qq! $key = "!.$applet->{$key}.q!" ! ;
 1846     } else {
 1847       warn " $key is not defined for applet ".$applet->{name};
 1848       # technically name is not required, but all of the other parameters are
 1849     }
 1850   }
 1851   # add parameters to options
 1852   if (defined($applet->{params}) ) {
 1853     foreach my $key (keys %{ $applet->{params} }) {
 1854       my $value = $applet->{params}->{$key};
 1855       $options .=  qq{<PARAM NAME = "$key" VALUE = "$value" >\n};
 1856     }
 1857 
 1858 
 1859   }
 1860   MODES( TeX        => "{\\bf \\underline{APPLET}  }".$applet->{name},
 1861          Latex2HTML => "\\begin{rawhtml} <APPLET $appletHeader> $options </APPLET>\\end{rawhtml}",
 1862          HTML       => "<APPLET\n $appletHeader> \n $options \n </APPLET>",
 1863          #HTML       => qq!<OBJECT $appletHeader codetype="application/java"> $options </OBJECT>!
 1864   );
 1865 }
 1866 
 1867 sub oldAppletLink {
 1868   my $url = shift;
 1869   my $options = shift;
 1870   $options = "" unless defined($options);
 1871   MODES( TeX        => "{\\bf \\underline{APPLET}  }",
 1872          Latex2HTML => "\\begin{rawhtml} <APPLET $url> $options </APPLET>\\end{rawhtml}",
 1873          HTML       => "<APPLET $url> $options </APPLET>"
 1874       );
 1875 }
 1876 sub spf {
 1877   my($number,$format) = @_;  # attention, the order of format and number are reversed
 1878   $format = "%4.3g" unless $format;   # default value for format
 1879   sprintf($format, $number);
 1880   }
 1881 sub sspf {
 1882   my($number,$format) = @_;  # attention, the order of format and number are reversed
 1883   $format = "%4.3g" unless $format;   # default value for format
 1884   my $sign = $number>=0 ? " + " : " - ";
 1885   $number = $number>=0 ? $number : -$number;
 1886   $sign .sprintf($format, $number);
 1887   }
 1888 
 1889 =head2  Sorting and other list macros
 1890 
 1891 
 1892 
 1893   Usage:
 1894   lex_sort(@list);   # outputs list in lexigraphic (alphabetical) order
 1895   num_sort(@list);   # outputs list in numerical order
 1896   uniq( @list);      # outputs a list with no duplicates.  Order is unspecified.
 1897 
 1898   PGsort( \&sort_subroutine, @list);
 1899   # &sort_subroutine defines order. It's output must be 1 or 0 (true or false)
 1900 
 1901 =cut
 1902 
 1903 #  uniq gives unique elements of a list:
 1904  sub uniq {
 1905    my (@in) =@_;
 1906    my %temp = ();
 1907    while (@in) {
 1908           $temp{shift(@in)}++;
 1909       }
 1910    my @out =  keys %temp;  # sort is causing trouble with Safe.??
 1911    @out;
 1912 }
 1913 
 1914 sub lex_sort {
 1915   PGsort sub {$_[0] lt $_[1]}, @_;
 1916 }
 1917 sub num_sort {
 1918   PGsort sub {$_[0] < $_[1]}, @_;
 1919 }
 1920 
 1921 
 1922 =head2 Macros for handling tables
 1923 
 1924   Usage:
 1925   begintable( number_of_columns_in_table)
 1926   row(@dataelements)
 1927   endtable()
 1928 
 1929 Example of useage:
 1930 
 1931   BEGIN_TEXT
 1932     This problem tests calculating new functions from old ones:$BR
 1933     From the table below calculate the quantities asked for:$BR
 1934     \{begintable(scalar(@firstrow)+1)\}
 1935     \{row(" \(x\) ",@firstrow)\}
 1936     \{row(" \(f(x)\) ", @secondrow)\}
 1937     \{row(" \(g(x)\) ", @thirdrow)\}
 1938     \{row(" \(f'(x)\) ", @fourthrow)\}
 1939     \{row(" \(g'(x)\) ", @fifthrow)\}
 1940     \{endtable()\}
 1941 
 1942    (The arrays contain numbers which are placed in the table.)
 1943 
 1944   END_TEXT
 1945 
 1946 =cut
 1947 
 1948 sub begintable {
 1949   my ($number)=shift;   #number of columns in table
 1950   my %options = @_;
 1951   warn "begintable(cols) requires a number indicating the number of columns" unless defined($number);
 1952   my $out = "";
 1953   if ($displayMode eq 'TeX') {
 1954     $out .= "\n\\par\\smallskip\\begin{center}\\begin{tabular}{"  .  "|c" x $number .  "|} \\hline\n";
 1955     }
 1956   elsif ($displayMode eq 'Latex2HTML') {
 1957     $out .= "\n\\begin{rawhtml} <TABLE , BORDER=1>\n\\end{rawhtml}";
 1958     }
 1959   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 1960                $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 1961          $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 1962     $out .= "<TABLE BORDER=1>\n"
 1963   }
 1964   else {
 1965     $out = "Error: PGbasicmacros: begintable: Unknown displayMode: $displayMode.\n";
 1966     }
 1967   $out;
 1968   }
 1969 
 1970 sub endtable {
 1971   my $out = "";
 1972   if ($displayMode eq 'TeX') {
 1973     $out .= "\n\\end {tabular}\\end{center}\\par\\smallskip\n";
 1974     }
 1975   elsif ($displayMode eq 'Latex2HTML') {
 1976     $out .= "\n\\begin{rawhtml} </TABLE >\n\\end{rawhtml}";
 1977     }
 1978   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 1979                $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 1980          $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 1981     $out .= "</TABLE>\n";
 1982     }
 1983   else {
 1984     $out = "Error: PGbasicmacros: endtable: Unknown displayMode: $displayMode.\n";
 1985     }
 1986   $out;
 1987   }
 1988 
 1989 
 1990 sub row {
 1991   my @elements = @_;
 1992   my $out = "";
 1993   if ($displayMode eq 'TeX') {
 1994     while (@elements) {
 1995       $out .= shift(@elements) . " &";
 1996       }
 1997      chop($out); # remove last &
 1998      $out .= "\\\\ \\hline \n";
 1999      # carriage returns must be added manually for tex
 2000     }
 2001   elsif ($displayMode eq 'Latex2HTML') {
 2002     $out .= "\n\\begin{rawhtml}\n<TR>\n\\end{rawhtml}\n";
 2003     while (@elements) {
 2004       $out .= " \n\\begin{rawhtml}\n<TD> \n\\end{rawhtml}\n" . shift(@elements) . " \n\\begin{rawhtml}\n</TD> \n\\end{rawhtml}\n";
 2005       }
 2006     $out .= " \n\\begin{rawhtml}\n</TR> \n\\end{rawhtml}\n";
 2007   }
 2008   elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng'||
 2009          $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2010          $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2011     $out .= "<TR>\n";
 2012     while (@elements) {
 2013       $out .= "<TD>" . shift(@elements) . "</TD>";
 2014       }
 2015     $out .= "\n</TR>\n";
 2016   }
 2017   else {
 2018     $out = "Error: PGbasicmacros: row: Unknown displayMode: $displayMode.\n";
 2019     }
 2020   $out;
 2021 }
 2022 
 2023 =head2 Macros for displaying static images
 2024 
 2025   Usage:
 2026   $string = image($image, width => 100, height => 100, tex_size => 800)
 2027   $string = image($image, width => 100, height => 100, extra_html_tags => 'align="middle"', tex_size => 800)
 2028   $string = image([$image1, $image2], width => 100, height => 100, tex_size => 800)
 2029   $string = caption($string);
 2030   $string = imageRow([$image1, $image2 ], [$caption1, $caption2]);
 2031            # produces a complete table with rows of pictures.
 2032 
 2033 
 2034 =cut
 2035 
 2036 #   More advanced macros
 2037 sub image {
 2038   my $image_ref  = shift;
 2039   my @opt = @_;
 2040   unless (scalar(@opt) % 2 == 0 ) {
 2041     warn "ERROR in image macro.  A list of macros must be inclosed in square brackets.";
 2042   }
 2043   my %in_options = @opt;
 2044   my %known_options = (
 2045     width    => 100,
 2046     height   => 100,
 2047     tex_size => 800,
 2048     extra_html_tags => '',
 2049   );
 2050   # handle options
 2051   my %out_options = %known_options;
 2052   foreach my $opt_name (keys %in_options) {
 2053     if ( exists( $known_options{$opt_name} ) ) {
 2054       $out_options{$opt_name} = $in_options{$opt_name} if exists( $in_options{$opt_name} ) ;
 2055     } else {
 2056       die "Option $opt_name not defined for image. " .
 2057           "Default options are:<BR> ", display_options2(%known_options);
 2058     }
 2059   }
 2060   my $width       = $out_options{width};
 2061   my $height      = $out_options{height};
 2062   my $tex_size    = $out_options{tex_size};
 2063   my $width_ratio = $tex_size*(.001);
 2064   my @image_list  = ();
 2065 
 2066   if (ref($image_ref) =~ /ARRAY/ ) {
 2067     @image_list = @{$image_ref};
 2068   } else {
 2069     push(@image_list,$image_ref);
 2070   }
 2071 
 2072   my @output_list = ();
 2073     while(@image_list) {
 2074     my $imageURL = alias(shift @image_list);
 2075     my $out="";
 2076 
 2077     if ($displayMode eq 'TeX') {
 2078       my $imagePath = $imageURL; # in TeX mode, alias gives us a path, not a URL
 2079       if (defined $envir->{texDisposition} and $envir->{texDisposition} eq "pdf") {
 2080         # We're going to create PDF files with our TeX (using pdflatex), so
 2081         # alias should have given us the path to a PNG image. What we need
 2082         # to do is find out the dimmensions of this image, since pdflatex
 2083         # is too dumb to live.
 2084 
 2085         #my ($height, $width) = getImageDimmensions($imagePath);
 2086         ##warn "&image: $imagePath $height $width\n";
 2087         #unless ($height and $width) {
 2088         # warn "Couldn't get the dimmensions of image $imagePath.\n"
 2089         #}
 2090         #$out = "\\includegraphics[bb=0 0 $height $width,width=$width_ratio\\linewidth]{$imagePath}\n";
 2091         $out = "\\includegraphics[width=$width_ratio\\linewidth]{$imagePath}\n";
 2092       } else {
 2093         # Since we're not creating PDF files, alias should have given us the
 2094         # path to an EPS file. latex can get its dimmensions no problem!
 2095 
 2096         $out = "\\includegraphics[width=$width_ratio\\linewidth]{$imagePath}\n";
 2097       }
 2098     } elsif ($displayMode eq 'Latex2HTML') {
 2099       my $wid = ($envir->{onTheFlyImageSize} || 0)+ 30;
 2100       $out = qq!\\begin{rawhtml}\n<A HREF= "$imageURL" TARGET="_blank" onclick="window.open(this.href,this.target, 'width=$wid,height=$wid,scrollbars=yes,resizable=on'); return false;"><IMG SRC="$imageURL"  WIDTH="$width" HEIGHT="$height"></A>\n
 2101       \\end{rawhtml}\n !
 2102     } elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 2103        $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2104        $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2105       my $wid = ($envir->{onTheFlyImageSize} || 0) +30;
 2106       $out = qq!<A HREF= "$imageURL" TARGET="_blank" onclick="window.open(this.href,this.target, 'width=$wid,height=$wid,scrollbars=yes,resizable=on'); return false;"><IMG SRC="$imageURL"  WIDTH="$width" HEIGHT="$height" $out_options{extra_html_tags} ></A>
 2107       !
 2108     } else {
 2109       $out = "Error: PGbasicmacros: image: Unknown displayMode: $displayMode.\n";
 2110     }
 2111     push(@output_list, $out);
 2112   }
 2113   return wantarray ? @output_list : $output_list[0];
 2114 }
 2115 
 2116 # This is legacy code.
 2117 sub images {
 2118   my @in = @_;
 2119   my @outlist = ();
 2120   while (@in) {
 2121      push(@outlist,&image( shift(@in) ) );
 2122    }
 2123   @outlist;
 2124 }
 2125 
 2126 
 2127 sub caption {
 2128   my ($out) = @_;
 2129   $out = " $out \n" if $displayMode eq 'TeX';
 2130   $out = " $out  " if $displayMode eq 'HTML';
 2131   $out = " $out  " if $displayMode eq 'HTML_tth';
 2132   $out = " $out  " if $displayMode eq 'HTML_dpng';
 2133   $out = " $out  " if $displayMode eq 'HTML_img';
 2134   $out = " $out  " if $displayMode eq 'HTML_jsMath';
 2135   $out = " $out  " if $displayMode eq 'HTML_asciimath';
 2136   $out = " $out  " if $displayMode eq 'HTML_LaTeXMathML';
 2137   $out = " $out  " if $displayMode eq 'Latex2HTML';
 2138     $out;
 2139 }
 2140 
 2141 sub captions {
 2142   my @in = @_;
 2143   my @outlist = ();
 2144   while (@in) {
 2145      push(@outlist,&caption( shift(@in) ) );
 2146   }
 2147   @outlist;
 2148 }
 2149 
 2150 sub imageRow {
 2151 
 2152   my $pImages = shift;
 2153   my $pCaptions=shift;
 2154   my $out = "";
 2155   my @images = @$pImages;
 2156   my @captions = @$pCaptions;
 2157   my $number = @images;
 2158   # standard options
 2159   my %options = ( 'tex_size' => 200,  # width for fitting 4 across
 2160                   'height' => 100,
 2161                   'width' => 100,
 2162                   @_            # overwrite any default options
 2163                 );
 2164 
 2165   if ($displayMode eq 'TeX') {
 2166     $out .= "\n\\par\\smallskip\\begin{center}\\begin{tabular}{"  .  "|c" x $number .  "|} \\hline\n";
 2167     while (@images) {
 2168       $out .= &image( shift(@images),%options ) . '&';
 2169     }
 2170     chop($out);
 2171     $out .= "\\\\ \\hline \n";
 2172     while (@captions) {
 2173       $out .= &caption( shift(@captions) ) . '&';
 2174     }
 2175     chop($out);
 2176     $out .= "\\\\ \\hline \n\\end {tabular}\\end{center}\\par\\smallskip\n";
 2177   } elsif ($displayMode eq 'Latex2HTML'){
 2178 
 2179     $out .= "\n\\begin{rawhtml} <TABLE  BORDER=1><TR>\n\\end{rawhtml}\n";
 2180     while (@images) {
 2181       $out .= "\n\\begin{rawhtml} <TD>\n\\end{rawhtml}\n" . &image( shift(@images),%options )
 2182               . "\n\\begin{rawhtml} </TD>\n\\end{rawhtml}\n" ;
 2183     }
 2184 
 2185     $out .= "\n\\begin{rawhtml}</TR><TR>\\end{rawhtml}\n";
 2186     while (@captions) {
 2187       $out .= "\n\\begin{rawhtml} <TH>\n\\end{rawhtml}\n".&caption( shift(@captions) )
 2188               . "\n\\begin{rawhtml} </TH>\n\\end{rawhtml}\n" ;
 2189     }
 2190 
 2191     $out .= "\n\\begin{rawhtml} </TR> </TABLE >\n\\end{rawhtml}";
 2192   } elsif ($displayMode eq 'HTML' || $displayMode eq 'HTML_tth' || $displayMode eq 'HTML_dpng' ||
 2193      $displayMode eq 'HTML_img' || $displayMode eq 'HTML_jsMath' ||
 2194      $displayMode eq 'HTML_asciimath' || $displayMode eq 'HTML_LaTeXMathML') {
 2195     $out .= "<P>\n <TABLE BORDER=2 CELLPADDING=3 CELLSPACING=2 ><TR ALIGN=CENTER    VALIGN=MIDDLE>\n";
 2196     while (@images) {
 2197       $out .= " \n<TD>". &image( shift(@images),%options ) ."</TD>";
 2198     }
 2199     $out .= "</TR>\n<TR>";
 2200     while (@captions) {
 2201       $out .= " <TH>". &caption( shift(@captions) ) ."</TH>";
 2202     }
 2203     $out .= "\n</TR></TABLE></P>\n"
 2204   }
 2205   else {
 2206     $out = "Error: PGbasicmacros: imageRow: Unknown languageMode: $displayMode.\n";
 2207     warn $out;
 2208   }
 2209   $out;
 2210 }
 2211 
 2212 
 2213 ###########
 2214 # Auxiliary macros
 2215 
 2216 sub display_options2{
 2217   my %options = @_;
 2218   my $out_string = "";
 2219   foreach my $key (keys %options) {
 2220     $out_string .= " $key => $options{$key},<BR>";
 2221   }
 2222   $out_string;
 2223 }
 2224 
 2225 
 2226 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9