#!/usr/bin/perl
#$Id: plot.cgi,v 1.3 2014/10/07 11:11:10 sqko Exp $
use strict;
use warnings;
use RFC::RFCCGI qw(:cgi :html);
use CGI qw(:standard :netscape);
use File::stat;

my $data = param('data');
$data = '' unless ($data);
my @lines = split(/\,/,$data);
&print_header('Plot');
print RFC_start_html(-title=>"Plot", -style=>{src=>'/celltest/RFCcontrol.css'});
unless (@lines && @lines > 1)
{
    print center(h1({-class=>'Alert'},"No data to plot!"));
    &print_end();
    exit;
}
my $pid = param('pid');
$pid = $$ unless ($pid);
my $size = param('size');
my $f = SemaforeFile->new('/tmp/data_'.$pid.'.txt');
$f->writeline(@lines);
my $fname = 'dataplot_'.$pid.'.png';
my $psname = 'dataplot_'.$pid.'.ps';
my $pngfn = $RFC::Header::htmldir.'/png/'.$fname;
my $psfn = $RFC::Header::htmldir.'/png/'.$psname;
my $gp = SemaforeFile->new('/tmp/plot_'.$$.'.gp');
$gp->open_write;
$gp->append("set out '$psfn'");
$gp->append('set term postscript enhanced color');
$gp->append('set nokey');
if (param('yaxis') && param('yaxis') =~ /log/i)
{
    $gp->append('set logscale y');
}
$gp->append('set zeroaxis lt -1');
$gp->append('f(x) = x==-32768?1/0:x');
$gp->append('set size '.$size) if ($size);
if ($data =~ /\d+\:\d+\:\d+/)
{
    $gp->append("set timefmt '%H:%M:%S'");
    $gp->append("set xdata time");
}
my $plotstr = "plot '".$f->filename."' u 1:(f(\$2)) w points,'' u 1:(f(\$2)) smooth csplines";
$plotstr = "plot '".$f->filename."' u 1:(f(\$2)) w linespoints" if (@lines < 3);
$gp->append($plotstr);
$gp->close();
eval {
    my $errfile = '/tmp/gp_error_'.$$;
    system('/usr/bin/gnuplot '.$gp->filename.' 2> '.$errfile);
    if (-e $errfile)
    {
	open MYIN,'<',$errfile or die "Could not open file $errfile $!\n";
	my @e = <MYIN>;
	close MYIN;
	unlink $errfile;
	my $errstr = join("\n",@e);
	die $errstr if ($errstr && $errstr !~ /empty\sy\srange/i);
    }
    system('/usr/local/bin/celltest/ps2png '.$psfn.' '.$pngfn);
};
if ($@)
{
    print h2({-class=>'Alert'},$@);
    unlink $gp->filename if ($gp->exist);
    &print_end();
    exit;
}
print '<center>';
print "<img src='/celltest/png/".$fname."'>";
print p();
print start_form(-name=>'sofc');
print hidden(-name=>'data');
print hidden(-name=>'size');
print print popup_menu(-name=>'yaxis',-values=>['Linear','Logarithmic'],-onchange=>'document.sofc.submit()');
print end_form();
print p();
print button(-name=>'Ok',-class=>'s3',-style=>'width:100px;',-onclick=>'window.close()');
print '</center>';

&print_end();
unlink $gp->filename if ($gp->exist);
unlink $f->filename if ($f->exist);
unlink $psfn if (-e $psfn);
### Clean old files in pngdir ###
my $dir = $RFC::Header::htmldir.'/png/';
opendir DIR,$dir or die "Could not open directory '$dir' $!\n";
while (my $file = readdir(DIR))
{
    next unless ($file =~ /^dataplot_/);
    my $fn = $dir.$file;
    my $sb = stat($fn);
    next unless ((time-30) > $sb->mtime);
    if ($fn =~ /([\w\.\/\-\,\:\(\)\[\]\s]+)/)
    {
	unlink $1 if -e ($1);
    }
}

