#!/usr/bin/perl
# $Id: plotall.pl,v 1.3 2012/04/27 08:17:59 sofc Exp $
use strict;
use warnings;
use RFC::Header;
use RFC::Main;
use RFC::Rig;

my $VERSION = 0.1;
my $PROGRAM = 'plotall.pl';
my $GNUPLOT = get_cv('GNUPLOT','location');
my $type = get_cv('GNUPLOT','impedance_time_plot_type');
$type = 'points' unless ($type);
for my $string (@ARGV)
{
    if ($string =~ /--version/)
    {
        warn "$PROGRAM is: $VERSION\n";
        exit;
    }
}
#### Get rig and test numbers and exit if wrong user ####
my $rig = RFC::Rig->new(shift);
$rig->check_run;
my $testno = $rig->session;
$testno = shift if (@ARGV);
my $homedir =  $RFC::Header::publicdir.'/rig'.$rig->name.'/'.$rig->name.'test'.$testno.'/';
my $psdir  = $homedir . "ps";
my $pngdir = $homedir . "png";
mkdir($psdir) unless ( -d $psdir );
mkdir($pngdir) unless ( -d $pngdir );
$psdir .= '/all/';
$pngdir .= '/all/';
mkdir($psdir) unless ( -d $psdir );
mkdir($pngdir) unless ( -d $pngdir );
my $jdata = $homedir.'jdata';
open MYIN,'<',$jdata or die "Could not open file '$jdata' $!\n";
my $str = <MYIN>;
close MYIN;
my @list = split(/\s+/,$str);
my $gid = '/tmp/'.$$.'.gp';
my $term = get_cv( "GNUPLOT", 'postportterm' );
$term =~ s/color\s*//;
open GP ,"> $gid" or die "Could not open file $gid for writing!\n";
print GP "set term $term\n";
print GP "set size 1,0.42\n\n\n";

for (my $x = 2; $x < @list; $x+=2)
{
    my $name = $list[$x];
    my $f = $psdir.$name.'.ps';
    print GP "set out '$f'\n";
    print GP "set xrange [0:]\n";
    print GP "set xla 'Time (h)'\n";
    $name =~ s/_/ /g;
    print GP "set yla '$name'\n";
    my $fd = $x+2;
    print GP "plot '$jdata' u 1:(\$$fd>1e37?1/0:\$$fd) tit '' with points pt 0 ps 1\n";
    print GP "\n\n";
}
close GP;
opendir(MYDIR,$psdir) or die "Can not open directory $psdir $!\n";
my @fl = readdir(MYDIR);
closedir(MYDIR);
foreach my $f (@fl)
{
    next unless ($f =~ /[\w\.\-]+\.ps/);
    next unless (-e $psdir.'/'.$f);
    unlink $psdir.'/'.$f;
}
opendir(MYDIR,$pngdir) or die "Can not open directory $psdir $!\n";
@fl = readdir(MYDIR);
closedir(MYDIR);
foreach my $f (@fl)
{
    next unless ($f =~ /[\w\.\-]+\.png/);
    next unless (-e $pngdir.'/'.$f);
    unlink $pngdir.'/'.$f;
}

### Run gnuplot ###
my $cstr = "$GNUPLOT $gid";
system($cstr);

### Convert to png ###

opendir(MYDIR,$psdir) or die "Can not open directory $psdir $!\n";
my @flist = ();
@fl = readdir(MYDIR);
closedir(MYDIR);
foreach my $f (@fl)
{
    next unless ($f =~ /[\w\.\-]+\.ps/);
    next unless (-e $psdir.'/'.$f);
    push @flist,$f;
}

#my @flist = `/bin/ls -1 $psdir`;
for my $s (@flist)
{ 
    chomp $s;
    my $ps = $psdir.$s;
    $s =~ /([\-\w]+)\.ps$/;
    $s = $1;
    my $pngfile = $pngdir.$s.'.png';
    $cstr = "/usr/local/bin/ps2png  $ps $pngfile";
    system($cstr);
}
### Remove temporary files ###
unlink $gid;
exit;
