#!/usr/local/bin/perl
require 'cgi-lib.pl';
&ReadParse(*in);

# redirect standard output and standard error 
open(SAVEOUT, ">&STDOUT");
open(SAVEERR, ">&STDERR");
#open(STDOUT, ">../webtmp/data$$"); 
open(STDERR, ">../webtmp/null"); 
$filename="test01-form.dat";
$fileno=$in{'file'}+1;
chmod 0666, "../webtmp/null";

substr($filename, 5, 1) = "$fileno";
#create data file
system("cp ../$filename ../webtmp/data$$");
#close(STDOUT);

#create plot
open(plot, "|/usr/local/bin/gnuplot");
$| =1;
print plot "\nset terminal pbm medium mono\nset output \"../webtmp/m.pbm$$\"\n";

if ($in{'file'}<=1){
print plot "\nset xrange [0:$in{'xmax'}]\n";
print "file value = -1 <br>\n";
}

if ($in{'file'}==0){
print plot "\nset xlabel \"time\" \n set ylabel \"angle\" \n";
}

if ($in{'file'}==1){
print plot "\nset xlabel \"time\" \n set ylabel \"velocity\" \n";
}

if ($in{'file'}==2){
print plot "\nset xlabel \"angle\" \n set ylabel \"velocity\" \n";
}

print plot "\nset title \"Plotting pre-processed data\"\n";
print plot "\nset nokey\n";
print plot "\n plot \"../webtmp/data$$\" w l\n";
close plot;

#make gif
system("/usr/local/bin/ppmtogif -transparent rgb:f/f/f ../webtmp/m.pbm$$>../webtmp/m.gif$$");

$gifile="../webtmp/m.gif$$";
chmod 0666, $gifile;
system ("(cd ../webtmp;/usr/local/bin/mkindex)");

# reinstall stdout and stderr 
open (STDERR, ">&SAVEERR");
open(STDOUT, ">&SAVEOUT"); 

$|=1;

print "Content-type: text/html\n\n";

print "<head><title>Plot of a boring sinusoid</title></head>\n";
#print"<img src=\"../webtmp/m.gif$$\">\n<br><hr></center>\n";
print"<img src=\"$gifile\">\n<br><hr></center>\n";

print "<b>Parameters used for this plot</b>\n";

print "<br>Input File: $filename<br>\n"; 
 
#this is should bring you back, where you came from
print "<hr><a href=\"$ENV{'HTTP_REFERER'}\"><b>Back</b></a>\n";
print " to making more plots<hr>\n";

#clean up all the temp files
unlink ("../webtmp/m.pbm$$");
unlink ("../webtmp/data$$"); 
system ("/bin/sleep 3");
#unlink ("../webtmp/m.gif$$");
chmod 0666, "../webtmp/index";
