#!/usr/bin/perl
# $Id: history-plot-3.0.pl,v 1.3 2012/06/04 11:31:26 sofc Exp $

use AFM;

if ( scalar(@ARGV) < 1 ) {
    print 'Use: history-plot.pl $rig [optional: $testno --version --debug], where $rig is the rig number' , "\n";
    print '$testno is the test number if an other test than the current is to be processed', "\n";
    exit 1;
}
my $VERSION = 0.3;
my $PROGRAM = 'history-plot.pl';
my $debug = 0;
if ( scalar(@ARGV) > 0 ) {
    for ( my $x = 0 ; $x < scalar(@ARGV) ; $x++ ) {
        if ( $ARGV[$x] =~ /--version/ ) {
            print "$PROGRAM is: $VERSION\n";
            exit 0;
        }
	if ( $ARGV[$x] =~ /--debug/)
	{
	    $debug = 1;
	}
    }
}


$GNUPLOT = '/usr/bin/gnuplot';


$pngpoints = "points pointtype 15 pointsize 0.25";
$pspoints  = "points pointtype 15 pointsize 0.25";

$xla     = "Hours";
$xcolumn = 1;
$pngsize = 0.7;

# 0.5;
$pssize = "1,0.5";
$rigno  = $ARGV[0];
if ( !&AFM::check_rig_nr($rigno) ) {
    print "Rig $rigno is not valid!\n";
    exit 1;
}


$awklocation = '/usr/local/bin/awk/';
my $testno = 0;
if ( scalar(@ARGV) > 1 ) {
    $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
else {
    $testno = &AFM::get_test_nr($rigno);
}

$voltagerange = &AFM::get_usercv_test($rigno,$testno,'userinterface','pO2_voltagerange');
$voltagerange='300,1400' unless ($voltagerange);
my ($vmin,$vmax) = split(/\,/,$voltagerange);

my @tempnames;
my @waternames;
my @gasnames;
my @currentnames;
my @simplenames;

my $conf = &AFM::get_usercv_test($rigno,$testno,'report','temp_names_history');
@tempnames = split(/\s*\,\s*/,$conf) if ($conf);
@tempnames = ('T_in','T_out','T_air_flow','T_center','T_corner') unless (@tempnames);
$conf = &AFM::get_usercv_test($rigno,$testno,'report','water_names_history');
@waternames = split(/\s*\,\s*/,$conf) if ($conf);
@waternames = ('bottle_temp') unless (@waternames);
$conf = &AFM::get_usercv_test($rigno,$testno,'report','gas_names_history');
@gasnames = split(/\s*\,\s*/,$conf) if ($conf);
@gasnames = () unless (@gasnames);
$conf = &AFM::get_usercv_test($rigno,$testno,'report','current_names_history');
@currentnames = split(/\s*\,\s*/,$conf) if ($conf);
@currentnames = ('current') unless (@currentnames);
$conf = &AFM::get_usercv_test($rigno,$testno,'report','simple_names_history');
@simplenames = split(/\s*\,\s*/,$conf) if ($conf);
@simplenames = ('cell_voltage','O2_in','O2_out') unless (@simplenames);

if ($debug)
{
    print "Temperature names;\n";
    foreach (@tempnames)
    {
	print $_,"\n";
    }
    print "\n";
    print "Water names;\n";
    foreach (@waternames)
    {
	print $_,"\n";
    }
    print "\n";
    print "Gas names;\n";
    foreach (@gasnames)
    {
	print $_,"\n";
    }
    print "\n";
    print "Voltage names;\n";
    foreach (@simplenames)
    {
	print $_,"\n";
    }
    print "\n";
    print "Current names;\n";
    foreach (@currentnames)
    {
	print $_,"\n";
    }
    print "\n";
}

$htmllocation =  "/home/http/html/rig" . $rigno . "/" . $rigno . "test" . $testno;
$htmlfile = $htmllocation."/history.html";
$plotfile = $htmllocation . "/jdata";
if ( !( -e ($plotfile) ) ) {
    print "$plotfile not found!!\n";
    exit 1;
}

### Find min and max current and set yrange accordingly ####
my $ymin = 0;
my $ymax = 0;
my $min = 0;
my $max = 0;
foreach (@currentnames)
{
    my ($mi,$ma) = `/usr/local/bin/get_min_max.pl $rigno $testno $_`;
    if ($mi < -0.1)
    {
	if ($mi < -16)
	{
	    $min = -2 if ($min > -2);
	    $ymin = -2.5 if ($ymin > -2.5);
	}
	else
	{
	    $min = -1 if ($min > -1);
	    $ymin = -1.5 if ($ymin > -1.5);
	}
    }
    else
    {
	$min = 0 unless ($min < 0);
    }
    if ($ma > 0.1)
    {
	if ($ma > 16)
	{
	    $max = 2 if ($max < 2);
	    $ymax = 2.5 if ($ymax < 2.5);
	}
	else
	{
	    $max = 1 if ($max < 1);
	    $ymax = 1.5 if ($ymax < 1.5);
	}
    }
    else
    {
	$max = 0 unless ($max > 0);
    }
}

$gpfile=$htmllocation."/history.gp";
open( GRAPH, "> $gpfile" ) || die "Could not open $gpfile\n";
$line = `head -1 $plotfile`;
@Fld  = split ( ' ', $line, 9999 );

for ( $i = 0 ; $i < $#Fld ; $i += 2 ) {
    $name{$Fld[$i] } = $Fld[ $i ];
    $data{ $Fld[$i] } = $Fld[ $i + 1 ];
    $col{ $Fld[$i] }  = $i + 2

}

$area = &AFM::get_usercv_test($rigno,$testno,'main','cell_area');
$area = &AFM::get_config_value_old( $rigno, 'area' ,$testno) unless ($area);


$pnglocation = $htmllocation . "/png";
$pslocation  = $htmllocation . "/ps";
$cstr="mkdir $pslocation";
print $cstr,"\n" if ($debug);
system($cstr) if (!-e($pslocation));
$cstr="mkdir $pnglocation";
print $cstr,"\n" if ($debug);
system($cstr) if (!-e($pnglocation));


$pngtype = "png";

foreach my $w (@waternames)
{
    print "Processing $w\n" if ($debug);
    $filename   = $w;
    $ylabel     = "Temperature, ^oC";
    my $t = &AFM::get_usercv_test($rigno,$testno,$w,'title');
    $t = $w unless ($t);
    my @wn = split(/_/,$t);
    foreach (@wn)
    {
	$_ = ucfirst($_);
    }
    $title      = join(' ',@wn);
    $yrange     = "[0:50]";
    $ytics      = " 0,10,50";
    $plotcolumn = $col{$filename};
    $fx = "(abs(x)<2000?x:1/0)";
    printgp();
}

foreach my $tn (@tempnames)
{
    print "Processing $tn\n" if ($debug);
    $filename   = $tn;
    my $t = &AFM::get_usercv_test($rigno,$testno,$tn,'title');
    $t = $tn unless ($t);
    $title      = $t;
    $title =~ s/_/ /g;
    $yrange     = "[0:1100]";
    $ytics      = "0,200,1000";
    $plotcolumn = $col{$filename};
    $fx = "(abs(x)<2000?x:1/0)";
    printgp();
}

foreach my $tn (@gasnames)
{
    print "Processing $tn\n" if ($debug);
    $filename   = $tn;
    my $t = &AFM::get_usercv_test($rigno,$testno,$tn,'title');
    $t = $tn unless ($t);
    $title      = $t;
    $yrange     = "[0:]";
    $ytics      = "";
    $ylabel     = "L/hour";
    $plotcolumn = $col{$filename};
    $fx = "(x<0?0:x)";
    printgp();
}

foreach my $sn (@simplenames)
{
    print "Processing $sn\n" if ($debug);
    my ($mi,$ma) = `/usr/local/bin/get_min_max.pl $rigno $testno $sn`;
    $filename = $sn;
    my $t = &AFM::get_usercv_test($rigno,$testno,$sn,'title');
    $t = $sn unless ($t);
    @tn    = split(/_/,$t);
    foreach (@tn)
    {
	$_ = ucfirst($_);
    }
    $title = join(' ',@tn);
    $ylabel   = "mV";
    my $diff = $ma-$mi;
    if ($mi+$diff/2 < 0)
    {
	$fx = "(abs(abs(x)<2000?x:1/0))";
	($mi,$ma) = (-$ma,-$mi);
    }
    if ($diff > 500)
    {
	my $ymi = sprintf("%.0f",$mi/100)*100;
	my $yma = sprintf("%.0f",$ma/100)*100+100;
	### Hard coded max and min values for yvalues              ###
	### only used if the actual values are outside this range  ###
	$yma = 2000 if ($yma > 2500);
	$ymi = -2000 if ($ymi < -2500);
	$yrange   = "[$ymi:$yma]";
	my @ticarr = ();
	for (my $x = $ymi;$x <= $yma; $x+=200)
	{
	    push @ticarr, '"'.-$x.'" '.$x;
	}
	$ytics = '('.join(',',@ticarr).')';
    }
    else
    {
	$yrange = "[:]";
	$ytics = '';
    }
    $plotcolumn = $col{$filename};
    printgp();
}

foreach my $cn (@currentnames)
{
    print "Processing $cn\n" if ($debug);
    $filename = $cn;
    my $t = &AFM::get_usercv_test($rigno,$testno,$cn,'title');
    $t = $cn unless ($t);
    $title    = ucfirst($t);
    $plotcolumn = $col{$filename};
    $yrange     = "[$ymin:$ymax]";
    $ytics      = "$min,0.5,$max";
    $ylabel     = "A/cm^2";
    $fx         = "(abs(x)<2000?x:1/0)/$area";
    printgp()
}


close(GRAPH);

print "Done creating gnuplot file\n" if ($debug);

$cstr="$GNUPLOT $gpfile";
system($cstr);

print "Done plotting\n" if ($debug);

open(HTML,"> $htmlfile") or die "Could not open $htmlfile";
print $htmlfile,"\n" if ($debug);

print HTML <<END;
<html>
<head>
<title>Plot</title>
</head>
<body>
<table>
<tbody>
<tr>
END


    $ncol=2;
for ($i=0;$i<=$#psfiles;$i++) 
{ 
    if ( ( ( $i - 2 ) % ($ncol) == 0 ) ) { print HTML "</tr>\n<tr>" };
    print HTML "<td><img src=\"png/$psfiles[$i].png\" alt=\"image\"></a></td>\n";
    $cstr = "/usr/local/bin/ps2png  $pslocation"."/".$psfiles[$i].".eps $pnglocation"."/".$psfiles[$i].".png";
    print $cstr,"\n" if ($debug);
    system($cstr);
}
print HTML <<END;
</tr></table>
</body>
</html>
END

close(HTML);
exit;



sub printgp {
    push(@psfiles, $filename);
    if ($plotcolumn)
    {
	print GRAPH <<END;

reset
set noytics
set xla "$xla"
#set bmargin 3
set nokey
set title \'$title\'
set yr$yrange
set ytics $ytics
    f(x)=$fx;
set yla '$ylabel'
set term post portrait enhanced color
set size $pssize
set out '$pslocation/$filename.eps'
plot '$plotfile' u 1:(f(\$$plotcolumn)) w $pspoints
END
    }
}



