#!/usr/bin/perl
#$Id: ajax_plot.cgi,v 1.13 2024/04/12 07:35:28 sqko Exp $
use strict;
use warnings;
use RFC::Header;
use SemaforeFile;
use CGI qw(:standard :netscape);
use File::stat;

print header(-charset=>'utf-8');
my $ac = param('action');
unless ($ac)
{
    print "Oops, no paramerters!\n-";
    exit;
}

if ($ac eq 'plot')
{
    my $pid = param('pid');
    $pid = $$ unless ($pid);
    my $data = param('data');
    unless ($data)
    {
	print "Oops no data to plot!\n";
	exit;
    }
    my $rows = param('rows');
    unless ($rows)
    {
	print "Oops no rows to plot!\n";
	exit;
    }
    my $size = param('size');
    my $f = SemaforeFile->new('/tmp/data_'.$pid.'.txt');
    $f->writeline($data);
    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');
    $gp->append('set xtics 5');
    $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 $first = 1;
    my $plotstr;
    foreach my $r (split(/\s*\,\s*/,$rows))
    {
	if ($first)
	{
	    $plotstr = "plot '".$f->filename."' u 1:(f(\$$r)) w lines";
	    $first = 0;
	    next;
	}
	$plotstr .= ",'' u 1:(f(\$$r)) w lines";
    }
    $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 "ERROR\n";
        print $@;
        unlink $gp->filename if ($gp->exist);
        exit;
    }
    print "OK\n";
    print $fname;
    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);
        }
    }

}


if ($ac eq 'plot2')
{
    my $pid = param('pid');
    $pid = $$ unless ($pid);
    my $data = param('data');
    unless ($data)
    {
	print "Oops no data to plot!\n";
	exit;
    }
    my $rows = param('rows');
    unless ($rows)
    {
	print "Oops no rows to plot!\n";
	exit;
    }
    my $size = param('size');
    my $f = SemaforeFile->new('/tmp/data_'.$pid.'.txt');
    $f->writeline($data);
    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');
    my $rownr = scalar(split(/\s*\,\s*/,$rows));
    $gp->open_write;
    $gp->append("set out '$psfn'");
    $gp->append('set term postscript enhanced color');
    $gp->append('set zeroaxis lt -1');
    $gp->append('set y2tics') if ($rownr > 1);
    $gp->append('set ytics nomirror');
    $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 $first = 1;
    my $plotstr;
    my $key = param('keys');
    $key = '' unless ($key);
    my @keylst = split(/\s*\,\s*/,$key);
    my $x = 0;
    foreach (split(/\s*\,\s*/,$rows))
    {
	my $tit = '';
	$tit = $keylst[$x] if ($x < @keylst && $keylst[$x]);
	$tit =~ s/_/ /g;
	if ($first)
	{
	    $plotstr = "plot '".$f->filename."' u 1:(f(\$$_)) w lines tit '$tit <-'";
	    $first = 0;
	    $x++;
	    next;
	}
	$plotstr .= ",'' u 1:(f(\$$_)) axis x1y2 w lines tit '$tit ->'";
	$x++;
    }
    $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\s\w+\srange/i);
	}
        system('/usr/local/bin/celltest/ps2png '.$psfn.' '.$pngfn);
    };
    if ($@)
    {
        print "ERROR\n";
        print $@;
        unlink $gp->filename if ($gp->exist);
        exit;
    }
    print "OK\n";
    print $fname;
    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);
        }
    }

}
