--- loncom/xml/lonplot.pm	2001/12/19 19:22:52	1.8
+++ loncom/xml/lonplot.pm	2001/12/21 21:39:51	1.16
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Dynamic plot
 #
-# $Id: lonplot.pm,v 1.8 2001/12/19 19:22:52 matthew Exp $
+# $Id: lonplot.pm,v 1.16 2001/12/21 21:39:51 matthew Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -26,73 +26,101 @@
 # http://www.lon-capa.org/
 #
 # 12/15/01 Matthew
-# 12/18 Matthew
+# 12/17 12/18 12/19 12/20 12/21 Matthew
 package Apache::lonplot;
+
 use strict;
+use Apache::File;
 use Apache::response;
 use Apache::lonxml;
-use Digest::MD5  qw(md5 md5_hex md5_base64);
+
+use Digest::MD5 qw(md5_base64);
 
 sub BEGIN {
   &Apache::lonxml::register('Apache::lonplot',('plot'));
 }
 
+## 
+## Description of data structures:
+##
+##  %plot       %key    %axis
+## --------------------------
+##  height      title   color
+##  width       box     xmin
+##  bgcolor     pos     xmax
+##  fgcolor             ymin
+##  transparent         ymax
+##  grid
+##  border
+##  font
+##
+##  @labels: $labels[$i] = \%label
+##           %label: text, xpos, ypos, justify
+##
+##  @curves: $curves[$i] = \%curve
+##           %curve: name, linestyle, ( function | data )
+##
+##  $curves[$i]->{'data'} = [ [x1,x2,x3,x4],
+##                            [y1,y2,y3,y4] ]
+##
+##------------------------------------------------------------
 ##
 ## Tests used in checking the validitity of input
 ##
-my $int_test       = sub {$_[0]=~/^\d+$/};
-my $real_test      = sub {$_[0]=~/^[+-]?\d*\.?\d*$/};
-my $color_test     = sub {$_[0]=~/^x[\da-f]{6}$/};
+my $int_test       = sub {$_[0]=~s/\s+//g;$_[0]=~/^\d+$/};
+my $real_test      = sub {$_[0]=~s/\s+//g;$_[0]=~/^[+-]?\d*\.?\d*$/};
+my $color_test     = sub {$_[0]=~s/\s+//g;$_[0]=~/^x[\da-f]{6}$/};
 my $onoff_test     = sub {$_[0]=~/^(on|off)$/};
-my $key_pos_test   = sub {$_[0]=~/^(top|bottom|right|left|outside|below)+$/};
+my $key_pos_test   = sub {$_[0]=~/^(top|bottom|right|left|outside|below| )+$/};
 my $sml_test       = sub {$_[0]=~/^(small|medium|large)$/};
 my $linestyle_test = sub {$_[0]=~/^(lines|linespoints|dots|points|steps)$/};
-my $words_test     = sub {$_[0]=~/^((\w+\b*)+$/};
+my $words_test     = sub {$_[0]=~s/\s+/ /g;$_[0]=~/^([\w\(\)]+ ?)+$/};
 ##
 ## Default values for attributes of elements
 ##
 my %plot_defaults = 
     (
-     height       => {default => 200,       test => $int_test  },
-     width        => {default => 200,       test => $int_test  },
-     bgcolor      => {default => 'xffffff', test => $color_test},
-     fgcolor      => {default => 'x000000', test => $color_test},
-     transparent  => {default => 'off',     test => $onoff_test},
-     grid         => {default => 'off',     test => $onoff_test},
-     border       => {default => 'on',      test => $onoff_test},
-     font         => {default => 'medium',  test => $sml_test  }
+     height       => {default => 200,       test => $int_test   },
+     width        => {default => 200,       test => $int_test   },
+     bgcolor      => {default => 'xffffff', test => $color_test },
+     fgcolor      => {default => 'x000000', test => $color_test },
+     transparent  => {default => 'off',     test => $onoff_test },
+     grid         => {default => 'off',     test => $onoff_test },
+     border       => {default => 'on',      test => $onoff_test },
+     font         => {default => 'medium',  test => $sml_test   },
+     align        => {default => 'left',    test => $words_test }
      );
 
 my %key_defaults = 
     (
-     title => { default => '',          test => $words_test  },
-     box   => { default => 'off',       test => $onoff_test  },
-     pos   => { default => 'top right', test => $key_pos_test}
+     title => { default => '',          test => $words_test   },
+     box   => { default => 'off',       test => $onoff_test   },
+     pos   => { default => 'top right', test => $key_pos_test }
      );
 
 my %label_defaults = 
     (
-     xpos    => {default => 0,         test => $real_test                   },
-     ypos    => {default => 0,         test => $real_test                   },
+     xpos    => {default => 0,         test => $real_test     },
+     ypos    => {default => 0,         test => $real_test     },
      justify => {default => 'left',    
-                 test => sub {$_[0]=~/^(left|right|center)$/}}
+                 test => sub {$_[0]=~/^(left|right|center)$/} }
      );
 
 my %axis_defaults = 
     (
      color     => {default => 'x000000', test => $color_test},
-#     thickness => {default => 1,         test => $int_test  },
-     xmin      => {default => -10.0,     test => $real_test },
-     xmax      => {default =>  10.0,     test => $real_test },
-     ymin      => {default => -10.0,     test => $real_test },
-     ymax      => {default =>  10.0,     test => $real_test }
+     xmin      => {default => '-10.0',   test => $real_test },
+     xmax      => {default => ' 10.0',   test => $real_test },
+     ymin      => {default => '-10.0',   test => $real_test },
+     ymax      => {default => ' 10.0',   test => $real_test },
+     linestyle => {default => 'points',  test => $linestyle_test}
      );
 
 my %curve_defaults = 
     (
-     color     => {default => 'x000000', test => $color_test      },
-     name      => {default => 'x000000', test => sub {$_[0]=~/^[\w ]*$/} },
-     linestyle => {default => 'lines',   test => $linestyle_test  }
+     color     => {default => 'x000000', test => $color_test     },
+     name      => {default => '',        test => $words_test     },
+     linestyle => {default => 'lines',   test => $linestyle_test }
      );
 
 ##
@@ -101,13 +129,13 @@ my %curve_defaults =
 my (%plot,%key,%axis,$title,$xlabel,$ylabel,@labels,@curves);
 
 sub start_plot {
-    %plot = '';   %key='';    %axis=''; 
-    $title='';    $xlabel=''; $ylabel='';
-    @labels = ''; @curves='';
+    %plot    = undef;   %key     = undef;   %axis   = undef; 
+    $title   = undef;   $xlabel  = undef;   $ylabel = undef;
+    $#labels = -1;      $#curves = -1;
     #
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
-    &Apache::lonxml::register('Apache::plot',
+    &Apache::lonxml::register('Apache::lonplot',
 	     ('title','xlabel','ylabel','key','axis','label','curve'));
     push (@Apache::lonxml::namespace,'plot');
     ## Always evaluate the insides of the <plot></plot> tags
@@ -115,7 +143,8 @@ sub start_plot {
     $inside=&Apache::run::evaluate($inside,$safeeval,$$parstack[-1]);
     &Apache::lonxml::newparser($parser,\$inside);
     ##-------------------------------------------------------
-    &get_attributes(\%plot,\%plot_defaults,$parstack,$safeeval,'plot');
+    &get_attributes(\%plot,\%plot_defaults,$parstack,$safeeval,
+		    $tagstack->[-1]);
     if ($target eq 'web') {
     }
     return '';
@@ -128,18 +157,43 @@ sub end_plot {
 	('title','xlabel','ylabel','key','axis','label','curve'));
     my $result = '';
     if ($target eq 'web') {
-	## Determine filename -- Need to use the 'id' thingy that Gerd 
-	## mentioned.
+	##
+	## Make sure we have all the input we need:
+	if (! defined(%plot  )) { &set_defaults(\%plot,\%plot_defaults); }
+	if (! defined(%key   )) {} # No key for this plot
+	if (! defined(%axis  )) { &set_defaults(\%axis,\%axis_defaults); }
+	if (! defined($title )) {} # No title for this plot
+	if (! defined($xlabel)) {} # No xlabel for this plot
+	if (! defined($ylabel)) {} # No ylabel for this plot
+	if ($#labels < 0) { } # No labels for this plot
+	if ($#curves < 0) { 
+	    &Apache::lonxml::warning("No curves specified for plot!!!!");
+	    return '';
+	}
+	my $curve;
+	foreach $curve (@curves) {
+	    if (!defined($curve->{'function'})&&!defined($curve->{'data'})){
+		&Apache::lonxml::warning("One of the curves specified did not contain any <data> or <function> declarations\n");
+		return '';
+	    }
+	}
+	##
+	## Determine filename
 	my $tmpdir = '/home/httpd/perl/tmp/';
-	my $filename = $tmpdir.$ENV{'user.name'}.'_'.$ENV{'user.domain'}.
-	    '_plot.data';
-	my $usersees=md5_base64($filename.'_'.$ENV{'REMOTE_ADDR'});
-	
+	my $filename = $ENV{'user.name'}.'_'.$ENV{'user.domain'}.
+	    '_'.time.'_'.$$.'_plot.data';
 	## Write the plot description to the file
-	my $fh=&Apache::File->new('/home/httpd/perl/tmp/'.$realname);
-	&write_gnuplot_file($fh);
+	my $fh=Apache::File->new(">$tmpdir$filename");
+	print $fh &write_gnuplot_file();
+	close($fh);
 	## return image tag for the plot
-	$result = '<img src=\"/cgi-bin/plot.cgi?'.$usersees.'"';
+	$result .= <<"ENDIMAGE";
+<img src    = "/cgi-bin/plot.gif?$filename" 
+     width  = "$plot{'width'}" 
+     height = "$plot{'height'}"
+     align  = "$plot{'align'}"
+     alt    = "/cgi-bin/plot.gif?$filename" />
+ENDIMAGE
     }
     return $result;
 }
@@ -148,7 +202,8 @@ sub end_plot {
 sub start_key {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
-    &get_attributes(\%key,\%key_defaults,$parstack,$safeeval,$tagstack);
+    &get_attributes(\%key,\%key_defaults,$parstack,$safeeval,
+		    $tagstack->[-1]);
     if ($target eq 'web') {
 	# This routine should never return anything.
     }
@@ -225,8 +280,13 @@ sub start_label {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
     my %label;
-    &get_attributes($label,\%label_defaults,$parstack,$safeeval,$tagstack);
-    $label->{'text'} = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
+    &get_attributes(\%label,\%label_defaults,$parstack,$safeeval,
+		    $tagstack->[-1]);
+    $label{'text'} = &Apache::lonxml::get_all_text("/label",$$parser[-1]);
+    if (! &$words_test($label{'text'})) {
+	# I should probably warn about it, too.
+	$label{'text'} = 'Illegal text';
+    }
     push(@labels,\%label);
     if ($target eq 'web') {
 	# This routine should never return anything.
@@ -248,8 +308,9 @@ sub start_curve {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
     my %curve;
-    &get_attributes($curve,\%curve_defaults,$parstack,$safeeval,$tagstack);
-    push (@curves,$curve);
+    &get_attributes(\%curve,\%curve_defaults,$parstack,$safeeval,
+		    $tagstack->[-1]);
+    push (@curves,\%curve);
     &Apache::lonxml::register('Apache::lonplot',('function','data'));
     push (@Apache::lonxml::namespace,'curve');
     if ($target eq 'web') {
@@ -272,9 +333,9 @@ sub end_curve {
 sub start_function {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
-    if (exists($curves[-1]->{'data'}) {
+    if (exists($curves[-1]->{'data'})) {
 	&Apache::lonxml::warning('Use of <function> precludes use of <data>.  The <data> will be omitted in favor of the <function> declaration.');
-	delete($curves[-1]->{'data'});
+	delete $curves[-1]->{'data'} ;
     }
     $curves[-1]->{'function'} = 
 	&Apache::lonxml::get_all_text("/function",$$parser[-1]);
@@ -297,12 +358,14 @@ sub start_data {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
     if (exists($curves[-1]->{'function'})) {
-	&Apache::lonxml::warning('Use of <data> precludes use of <function>.  The <function> will be omitted in favor of the <data> declaration.');
+	&Apache::lonxml::warning('Use of <data> precludes use of <function>.'.
+            '  The <function> will be omitted in favor of the <data>'.
+            ' declaration.');
 	delete($curves[-1]->{'function'});
     }
     my $datatext = &Apache::lonxml::get_all_text("/data",$$parser[-1]);
-    $datatext =~ s/(\s+$|^\s+)//g;
-    $datatext =~ s/\s+/ /g;
+    $datatext =~ s/\s+/ /g;  # No whitespace, numbers must be seperated
+                            # by commas
     if ($datatext !~ /^(([+-]?\d*\.?\d*)[, ]?)+$/) {
 	&Apache::lonxml::warning('Malformed data: '.$datatext);
 	$datatext = '';
@@ -310,8 +373,19 @@ sub start_data {
     # Need to do some error checking on the @data array - 
     # make sure it's all numbers and make sure each array 
     # is of the same length.
-    my @data = split /[, ]/,$datatext;
-    push( @{$curves[-1]->{'data'}},\@data;
+    my @data;
+    if ($datatext =~ /,/) {
+        @data = split /,/,$datatext;
+    } else { # Assume it's space seperated.
+        @data = split / /,$datatext;
+    }
+    for (my $i=0;$i<=$#data;$i++) {
+	# Check that it's non-empty
+	# Check that it's a number
+	# Maybe I need a 'debug=on' switch to list the data set
+	#    out in a warning?
+    }
+    push  @{$curves[-1]->{'data'}},\@data;
     if ($target eq 'web') {
 	# This routine should never return anything.
     }
@@ -331,7 +405,8 @@ sub end_data {
 sub start_axis {
     my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
     my $result='';
-    &get_attributes(\%axis,\%label_defaults,$parstack,$safeeval,$tagstack);
+    &get_attributes(\%axis,\%axis_defaults,$parstack,$safeeval,
+		    $tagstack->[-1]);
     if ($target eq 'web') {
 	# This routine should never return anything.
     }
@@ -347,108 +422,120 @@ sub end_axis {
     return $result;
 }
 
+##----------------------------------------------------------- set_defaults
+sub set_defaults {
+    my $var      = shift;
+    my $defaults = shift;
+    my $key;
+    foreach $key (keys %$defaults) {
+	$var->{$key} = $defaults->{$key}->{'default'};
+    }
+}
+
 ##------------------------------------------------------------------- misc
 sub get_attributes{
-    %values   = %{shift};
-    %defaults = %{shift};
-    $parstack = shift;
-    $safeeval = shift;
-    $tag      = shift;
+    my $values   = shift;
+    my $defaults = shift;
+    my $parstack = shift;
+    my $safeeval = shift;
+    my $tag      = shift;
     my $attr;
-    foreach $attr (keys %defaults) {
-	$values{$attr} = &Apache::lonxml::get_param($attr,$parstack,$safeeval);
-	if ($values{$attr} eq '' | !defined($values{$attr})) {
-	    $values{$attr} = $defaults{$attr};
+    foreach $attr (keys %{$defaults}) {
+	$values->{$attr} = 
+	    &Apache::lonxml::get_param($attr,$parstack,$safeeval);
+	if ($values->{$attr} eq '' | !defined($values->{$attr})) {
+	    $values->{$attr} = $defaults->{$attr}->{'default'};
 	    next;
 	}
-	my $test = $defaults{$attr}->{'test'};
-	if (! &$test($values{$attr})) {
+	my $test = $defaults->{$attr}->{'test'};
+	if (! &$test($values->{$attr})) {
 	    &Apache::lonxml::warning
 		($tag.':'.$attr.': Bad value.'.'Replacing your value with : '
-		 .$defaults{$attr} );
-	    $values{$attr} = $defaults{$attr};
+		 .$defaults->{$attr}->{'default'} );
+	    $values->{$attr} = $defaults->{$attr}->{'default'};
+	}
     }
     return ;
 }
-
+##------------------------------------------------------- write_gnuplot_file
 sub write_gnuplot_file {
-    my $fh = shift;
     my $gnuplot_input = '';
+    my $curve;
     # Collect all the colors
     my @Colors;
     push @Colors, $plot{'bgcolor'};
     push @Colors, $plot{'fgcolor'}; 
-    push @Colors, $axis{'color'};
-    push @Colors, $axis{'color'}; 
-    foreach $curve (@Curves) {
-	push @Colors, ($curve{'color'} ne '' ? 
-		       $curve{'color'}       : 
-		       $plot{'fgcolor'}      );
+    push @Colors, (defined($axis{'color'})?$axis{'color'}:$plot{'fgcolor'});
+    foreach $curve (@curves) {
+	push @Colors, ($curve->{'color'} ne '' ? 
+		       $curve->{'color'}       : 
+		       $plot{'fgcolor'}        );
     }
     # set term
     $gnuplot_input .= 'set term gif ';
     $gnuplot_input .= 'transparent ' if ($plot{'transparent'} eq 'on');
     $gnuplot_input .= $plot{'font'} . ' ';
-    $gnuplot_input .= 'size ' . $plot{'width'} . ' ';
-    $gnuplot_input .= $plot{'height'} . ' ';
+    $gnuplot_input .= 'size '.$plot{'width'}.','.$plot{'height'}.' ';
     $gnuplot_input .= "@Colors\n";
     # grid
-    $gnuplot_input .= ($plot->{'grid'} eq 'on' ?
-		       'set grid\n'            :
-		       ''                      );
+    $gnuplot_input .= 'set grid'.$/ if ($plot{'grid'} eq 'on');
     # border
-    $gnuplot_input .= ($plot->{'border'} eq 'on'?
-		       'set border\n'           :
-		       'set noborder\n'         );    # title, xlabel, ylabel
-    {
-    $gnuplot_input .<<"ENDLABELS";
-set title  $title->{'text'}
-set xlabel $xlabel->{'text'}
-set ylabel $ylabel->{'text'}
-set xrange $axis->{'xmin'}:$axis->{'xmax'}
-set yrange $axis->{'ymin'}:$axis->{'ymax'}
-ENDLABELS
+    $gnuplot_input .= ($plot{'border'} eq 'on'?
+		       'set border'.$/           :
+		       'set noborder'.$/         );    # title, xlabel, ylabel
+    $gnuplot_input .= "set output\n";
+    $gnuplot_input .= "set title  \"$title\"\n"  if (defined($title)) ;
+    $gnuplot_input .= "set xlabel \"$xlabel\"\n" if (defined($xlabel));
+    $gnuplot_input .= "set ylabel \"$ylabel\"\n" if (defined($ylabel));
+    if (defined(%axis)) {
+	$gnuplot_input .= "set xrange \[$axis{'xmin'}:$axis{'xmax'}\]\n";
+	$gnuplot_input .= "set yrange \[$axis{'ymin'}:$axis{'ymax'}\]\n";
     }
     # Key
-    if (defined($key{'pos'})) {
-	$gnuplot_input .= 'set key '.$key->{'pos'}.' ';
-	$gnuplot_input .= ($key->{'box'} eq 'on' ? 'box ' : 'nobox ');
-	if ($key->{'title'} ne '') {
-	    $gnuplot_input .= 'title "'$key->{'title'}.'"\n';
-	} else {
-	    $gnuplot_input .= '\n';
-	}
+    if (defined(%key)) {
+	$gnuplot_input .= 'set key '.$key{'pos'}.' ';
+	if ($key{'title'} ne '') {
+	    $gnuplot_input .= 'title "'.$key{'title'}.'" ';
+	} 
+	$gnuplot_input .= ($key{'box'} eq 'on' ? 'box ' : 'nobox ').$/;
     } else {
-	$gnuplot_input .= 'set nokey\n';
-    }    
-    # axis
-    $gnuplot_input .= 'set xrange ['.$axis{'xmin'}.':'.$axis{'xmin'}.']\n';
-    $gnuplot_input .= 'set yrange ['.$axis{'ymin'}.':'.$axis{'ymin'}.']\n';
+	$gnuplot_input .= 'set nokey'.$/;
+    }
     # labels
+    my $label;
     foreach $label (@labels) {
 	$gnuplot_input .= 'set label "'.$label->{'text'}.'" at '.
-	    $label->{'x'}.','.$label->{'y'}.'\n';
+	    $label->{'xpos'}.','.$label->{'ypos'}.' '.$label->{'justify'}.$/ ;
     }
     # curves
     $gnuplot_input .= 'plot ';
     my $datatext = '';
-    foreach $curve (@curves) {
+    for (my $i = 0;$i<=$#curves;$i++) {
+	$curve = $curves[$i];
+	$gnuplot_input.= ', ' if ($i > 0);
 	if (exists($curve->{'function'})) {
-	    $gnuplot_input.= $curve->{'function'}.' with '.$curve->{'linestyle'};
+	    $gnuplot_input.= 
+		$curve->{'function'}.' title "'.
+		$curve->{'name'}.'" with '.
+		$curve->{'linestyle'};
 	} elsif (exists($curve->{'data'})) {
-	    $gnuplot_input.= '\'-\' with '.$curve->{'linestyle'};
+	    $gnuplot_input.= '\'-\' title "'.
+		$curve->{'name'}.'" with '.
+		$curve->{'linestyle'};
 	    my @Data = @{$curve->{'data'}};
-	    for ($i =0; $i<=$#Data; $i++) {
+	    my @Data0 = @{$Data[0]};
+	    for (my $i =0; $i<=$#Data0; $i++) {
+		my $dataset;
 		foreach $dataset (@Data) {
-		    $datatext .= $dataset[$i] . ' ';
+		    $datatext .= $dataset->[$i] . ' ';
 		}
-		$datatext .='\n';
+		$datatext .= $/;
 	    }
-	    $datatext .='\n';
+	    $datatext .=$/;
 	}
     }
-    $gnuplot_input .= $datatext;
-    print $fh $gnuplot_input;
+    $gnuplot_input .= $/.$datatext;
+    return $gnuplot_input;
 }
 
 1;