#!/usr/bin/perl

mkdir("/tmp/CA-GNUPLOT.$$", 777) || die "Could not create /tmp/CA-GNUPLOT.$$";
system "chmod 777 /tmp/CA-GNUPLOT.$$";

open(GNUPLOT, ">/tmp/CA-GNUPLOT.$$/COMMANDS");
open(FILE, ">/dev/null");

if ($#ARGV >= 0) 
	{ $file = "$ARGV[0]"; }
else
	{ $file = "plot$$"; }


@styles = (
 	   "with linespoints ls 3", 
 	   "with lines ls 1", 
           "with lines ls 2", 
	   "with lines ls 3", 
           "with lines ls 4", 
	    "with lines ls 5", "", "", "", "", "");


$index = 0;
$plotcmd = "";
$opened = 1;
$commands = 1;
while (<>) {
	if (/^$/o) { $commands = 0; $opened = 0; next; }
	if ($commands) { print GNUPLOT; next; }
	if (! $opened) { 
		close(FILE);
		s/"(.*)"\n/$1/; 
		$plotcmd .= 
                   "'/tmp/CA-GNUPLOT.$$/$1' title '$1' $styles[$index],";
		$index++;
		open(FILE, ">/tmp/CA-GNUPLOT.$$/$_"); 
		$opened = 1; 
		next; 
	}
	print FILE;
}

close(FILE);

#print GNUPLOT "set term xlib\n";
#print GNUPLOT "set output '$file.plot'\n";

#chop($plotcmd);
#print GNUPLOT "plot $plotcmd\n";

print GNUPLOT "set size 0.5, 0.5\n";
#print GNUPLOT "set term postscript portrait monochrome 'Times-Roman' 13\n";
#print GNUPLOT "set output '$file.ps'\n";

print GNUPLOT "set term pdf\n";
print GNUPLOT "set output '$file.pdf'\n";
chop($plotcmd);
#print GNUPLOT "replot\n";
print GNUPLOT "plot $plotcmd\n";
print GNUPLOT "set output\n";
print GNUPLOT "quit\n";

close (GNUPLOT);

system "gnuplot /tmp/CA-GNUPLOT.$$/COMMANDS";

system "/bin/rm -rf /tmp/CA-GNUPLOT.$$";


