#!/usr/bin/perl
# $Id: multiplot.pl,v 1.17 2012/07/03 08:56:25 sofc Exp $
use AFM;
my $VERSION = 0.22;
my $PROGRAM = 'multiplot.pl';
$xrange = " [0:]";
$timeid = "";
if ( scalar(@ARGV) > 0 ) {
    for ( my $x = 0 ; $x < scalar(@ARGV) ; $x++ ) {
        if ( $ARGV[$x] =~ /--version/ ) {
            print "$PROGRAM is: $VERSION\n";
            exit 0;
        }
    }
}

if ( scalar(@ARGV) < 1 ) {
    print
      'Use: multiplot.pl $rig [optional: $testno], 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 ($cymin,$cymax) = (0,0);
my ($cymint,$cymaxt) = (0,0);
$GNUPLOT = '/usr/bin/gnuplot';
my @low =();
my @high = ();
my %gasses = ();

sub printgpstart {
    print GRAPH <<END;

reset
set nomulti
#set term dumb
#set out '/dev/null'
#set xr[]  writeback
#pl '$plotfile' u $xcolumn:(1)
#set noautoscale x
set term $termtype 
set out \'$outfile\'
END
}

sub printgpcellvoltage {
    print GRAPH <<END;
set multi
#set linestyle 1 lt 1
#set linestyle 2 lt 2
#set linestyle 11 lt 11

set lmargin 10
set rmargin 10
set bmargin 2
set size 1,0.25
set grid y linetype 0
set origin 0,0.75
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Cell voltage (mV)"
set nok
set yr[400:1200]
set ytics 400,200,1000
set xr $xrange
pl '$plotfile' u $xcolumn:$cellvoltage  w  $ppoints
END
}

sub printgprmin {

    print GRAPH <<END;

set multi

#set linestyle 1 lt 1
#set linestyle 2 lt 2
#set linestyle 11 lt 11

set lmargin 10
set rmargin 10
set bmargin 2
set size 1,0.25
set grid y linetype 0
set origin 0,0.75
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Secant ASR ({/Symbol W} cm^2)"
set nok
set yr[0:]
#set ytics 400,200,1000
set xr $xrange
pl '$rminfile' u 2:1  w $res_pspoints, '$plotfile' u 1:(-1) 
END
}

sub printgprcurrent {

    print GRAPH <<END;

set multi

#set linestyle 1 lt 1
#set linestyle 2 lt 2
#set linestyle 11 lt 11

set lmargin 10
set rmargin 10
set bmargin 2
set size 1,0.25
set grid y linetype 0
set origin 0,0.75
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Secant ASR ({/Symbol W} cm^2)"
set nok
set yr[0:]
set ytics 0.2
set xr $xrange
pl \"< paste $rfile $tfile\" u 3:2,\"$plotfile\" u 1:(-1)
END
}

sub printgprstart {

    print GRAPH <<END;

set multi

#set linestyle 1 lt 1
#set linestyle 2 lt 2
#set linestyle 11 lt 11

set lmargin 10
set rmargin 10
set bmargin 2
set size 1,0.25
set grid y linetype 0
set origin 0,0.75
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Secant ASR ({/Symbol W} cm^2)"
set nok
set yr[0:]
#set ytics 400,200,1000
set xr $xrange
pl '$rstartfile' u 1:$col{"R_secant"}  w $res_pspoints, '$plotfile' u 1:(-1) 
END
}

sub printg_temp_emf {
    print GRAPH <<END;
set origin 0,0.5
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Temperature (^oC)" 
set nok
set yr[000:1200]
set ytics 0,200,1000
set xr $xrange
pl '$plotfile' u $xcolumn:$temperature w $ppoints

set origin 0,0.25
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Current density (A/cm^2)"
set nok
set yr[$cymin:$cymax]
set ytics $cymint,0.5,$cymaxt
set xr $xrange
pl '$plotfile' u $xcolumn:(\$$current/$area)  w $ppoints

set origin 0,0

set border 11
set xtics nomirror
set ytics nomirror
set yrange[-700:-1200]
set ylabel "Emf O_2"
set key  right bottom
set ytics -1100,100,-700
f(x) = x<0?x:-x
set ylabel "Emf O_2"
set key  right bottom
set xr $xrange
pl '$plotfile' u $xcolumn:(f(\$$O2_in))  tit \'O_2 in\'  w $ppoints ,'$plotfile' u $xcolumn:(f(\$$O2_out))  tit \'O_2 out\' w $ppoints 
END
}

sub printg_temp_I_flow {
    my $y2label = 'Flow';
    foreach (@high)
    {
	my $l = $_;
	$l =~ s/_/ /g;
	$l =~ s/\b(\w)/\u$1/g;
	$l =~ s/(\D)(\d)/\u$1\_$2/g;
	$y2label .= ', '.$l;
    }
    $y2label .= ' (l/h)';
    my $ylabel = 'Flow';
    foreach (@low)
    {
	my $l = $_;
	$l =~ s/_/ /g;
	$l =~ s/\b(\w)/\u$1/g;
	$l =~ s/(\D)(\d)/\u$1\_$2/g;
	$ylabel .= ', '.$l;
    }
    $ylabel .= ' (l/h)';
    print GRAPH <<END;
set origin 0,0.5
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Temperature (^oC)" 
set nok
set yr[0:1200]
set ytics 0,200,1000
set xr $xrange
pl '$plotfile' u $xcolumn:$temperature w $ppoints

set origin 0,0.25
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Current density (A/cm^2)"
set nok
set  au y
set yr[$cymin:$cymax]
set ytics $cymint,0.5,$cymaxt
set xr $xrange
pl '$plotfile' u $xcolumn:(\$$current/$area)  w $ppoints

set origin 0,0

set border 11
set xtics nomirror
set ytics nomirror
set yrange[0:30]
set y2range[0:200]
set xrange $xrange
set y2tics 0,50,200
set y2label '$y2label'
set ylabel '$ylabel'
set key
set ytics 0,7.5,30
set grid y linetype 0
END


print GRAPH "pl ";
my $comma = 0;
foreach (@high)
{
    my $tit = $_;
    $tit =~ s/_/ /g;
    $tit =~ s/\b(\w)/\u$1/g;
    $tit =~ s/(\D)(\d)/\u$1\_$2/g;
    if ($comma)
    {
	print GRAPH ', ';
    }
    else
    {
	$comma = 1;
    }
    print GRAPH "'$plotfile' u $xcolumn:$gasses{$_} axes x1y2 tit '$tit' w lines";
}
foreach (@low)
{
    my $tit = $_;
    $tit =~ s/_/ /g;
    $tit =~ s/\b(\w)/\u$1/g;
    $tit =~ s/(\D)(\d)/\u$1\_$2/g;
    if ($comma)
    {
	print GRAPH ', ';
    }
    else
    {
	$comma = 1;
    }
    print GRAPH "'$plotfile' u $xcolumn:$gasses{$_} axes x1y1 tit '$tit' w lines";
}

print GRAPH "\n\n";
}

sub printgpm2 {
    print GRAPH <<END;
set nomulti
set out \'$outfile1\'
set multi
set noarrow
set noy2tics
set nolabel
set y2label ""
set size 1,0.4
set origin 0,0.6
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Cell voltage (mV)"
set nok
set yr[400:1200]
set ytics 400,200,1000
set xr $xrange
pl '$plotfile' u $xcolumn:$cellvoltage  w  $ppoints

set origin 0,0.2
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "-Oxygen potential of inlet H_2 (mV)"
set nok
f(x) = x<0?-x:x
set yr[900:1100]
set ytics 900,50,1100
set xr $xrange
pl '$plotfile' u $xcolumn:(\$$o2in)  w  $ppoints
set nomulti


set out
set out \'$outfile2\'
set multi
set noarrow
set noy2tics
set nolabel
set y2label ""
set size 1,0.4
set origin 0,0.6
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "In-plane voltage (mV)"
set nok
set yr[-4:4]
set ytics -4,2,4
set xr $xrange
pl '$plotfile' u $xcolumn:(\$$inplaneh2*(-1000))  w  $ppoints
set nomulti
set out
q

quit

END
}

$pngpoints    = "points pointtype 7 pointsize 0.15";
$pspoints     = "points pointtype 7 pointsize 0.15";
$res_pspoints = "points pointtype 2 pointsize 0.75";
$ph2points    = "points pointtype 5 pointsize 0.15";
$ppoints      = $pspoints;

$termtype = "post portrait enhanced color 10";

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

# 0.5;
$pssize = 1;
$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);
}
if ( scalar(@ARGV) > 2 ) {
    $xrange = " [" . $ARGV[2] . ":" . $ARGV[3] . "]";
    $timeid = "_" . ( $ARGV[2] + 0 ) . "_" . ( $ARGV[3] + 0 );

}

$htmllocation =
  "/home/http/html/rig" . $rigno . "/" . $rigno . "test" . $testno;
$grfile = "$htmllocation" . "/multi.gp";
open( GRAPH, "> $grfile" ) || die;
;

$plotfile = $htmllocation . "/jdata";
if ( !( -e ($plotfile) ) ) {
    print "$plotfile not found!!\n";
    exit 1;
}

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

$line = `head -1 $plotfile`;
@Fld = split ( ' ', $line, 9999 );

for ( $i = 2 ; $i < $#Fld ; $i += 2 ) {

    $data{ $Fld[$i] } = $Fld[ $i + 1 ];
    $col{ $Fld[$i] }  = $i + 2

}

### Get gas colums to include and find out which axis to use (high or low flow range)
my @glist = split(/\s*\,\s*/,&AFM::get_usercv_test($rigno,$testno,'main','gas_names')); 
@glist = ('h2','o2','ch4','air') unless (@glist);
foreach (@glist)
{
    $gasses{$_} = $col{$_};
}
my $minmax = '/usr/local/bin/get_min_max.pl '.$rigno.' '.$testno;
foreach my $key (keys %gasses)
{
    my $cutof = &AFM::get_usercv_test($rigno,$testno,'gas_'.$key,'cutoff_report');
    $cutof = &AFM::get_config_value_old($rigno,$key.'_cutof',$testno) unless ($cutof);
    my ($min,$max) = `$minmax $key 0 1000`;
    chomp $max;
    next unless ($max > $cutof);
    if ($max > 30)
    {
	push @high, $key;
	next;
    }
    push @low, $key;
}
my ($min,$max) = `$minmax current -10000 10000`;
chomp $min;
chomp $max;
if ($min < -0.1)
{
    $cymin = -1.5;
    $cymint = -1;
}
if ($min < -16)
{
    $cymin = -2.5;
    $cymint = -2;
}
if ($max > 0.1)
{
    $cymax = 1.5;
    $cymaxt = 1;
}
if ($max > 16)
{
    $cymax = 2.5;
    $cymaxt = 2;
}
if ($cymin == $cymax)
{
    $cymin = 0; 
    $cymax = 0.5;
    $cymint = 0; 
    $cymaxt = 0.5;
}
$xcolumn     = 1;
$current     = 26;
$current     = $col{"current"};
$cellvoltage = $col{"cell_voltage"};
$temperature = $col{"T_center"};
$O2_in       = $col{"O2_in"};
$O2_out      = $col{"O2_out"};

$o2in      = $col{"O2_in"};
$inplaneh2 = $col{"inplane_V_hydrogen"};

$pnglocation = $htmllocation . "/png";
$dir         = $pnglocation;
if ( !( -d $dir ) ) { $mk = system("mkdir $dir") }

$pslocation = $htmllocation . "/ps";
$dir        = $pslocation;
if ( !( -d $dir ) ) { $mk = system("mkdir $dir") }
$awkfile = $awklocation . "mode.awk";
$outfile  = $dir . "/multi" . $timeid . ".ps";
$outfile1 = $dir . "/multi-1" . $timeid . ".ps";
$outfile2 = $dir . "/multi-2" . $timeid . ".ps";

printgpstart();
printgpcellvoltage();
printg_temp_I_flow();
printgpm2();

$cstr = "$GNUPLOT < $grfile";
system($cstr);

$grfile = "$htmllocation" . "/multi-emf.gp";

$outfile = $dir . "/multi-emf" . $timeid . ".ps";
open( GRAPH, "> $grfile" ) || die;
printgpstart();
printgpcellvoltage();
printg_temp_emf();
close(GRAPH);
$cstr = "$GNUPLOT < $grfile";
system($cstr);

$cstr = "$GNUPLOT < $grfile";

system($cstr);

$grfile = "$htmllocation" . "/multi-res.gp";
open( GRAPH, "> $grfile" ) || die;
;

$sec = "";

$rminfile = $htmllocation . "/iv/plotdata/rminvalues";
if ( -f $rminfile ) {

    $outfile = $dir . "/multi-sec-res-min" . $timeid . ".ps";

    printgpstart();
    printgprmin();
    printg_temp_I_flow();
    close(GRAPH);

    $cstr = "$GNUPLOT < $grfile";

    system($cstr);

}

$grfile = "$htmllocation" . "/multi-res-at_current_0_5.gp";

open( GRAPH, "> $grfile" ) || die;

$rfile = $htmllocation . "/iv/plotdata/current_0.5";
$tfile = $htmllocation . "/iv/plotdata/imaxvalues";
if ( -f $rfile ) {

    $outfile = $dir . "/multi-res-at_current_0_5" . $timeid . ".ps";

    printgpstart();
    printgprcurrent();
    printg_temp_I_flow();
    close(GRAPH);

    $cstr = "$GNUPLOT < $grfile";

    system($cstr);

}

$grfile = "$htmllocation" . "/multi-res-start.gp";
open( GRAPH, "> $grfile" ) || die;

$rstartfile = $htmllocation . "/iv/plotdata/rstartvalues";
if ( -f $rstartfile ) {
    $line = `head -1 $rstartfile`;
    @Fld  = split ( ' ', $line, 9999 );

    for ( $i = 2 ; $i < $#Fld ; $i += 2 ) {

        $data{ $Fld[$i] } = $Fld[ $i + 1 ];
        $col{ $Fld[$i] }  = $i + 2

    }

    $outfile = $dir . "/multi-sec-res-start" . $timeid . ".ps";

    printgpstart();
    printgprstart();
    printg_temp_I_flow();
    close(GRAPH);

    $cstr = "$GNUPLOT < $grfile";

    system($cstr);

}

for ( "", "-1", "-2", "-emf", "-sec-res-min", "-res-at_current_0_5",
    "-sec-res-start" )
{
    $cstr =
      "/usr/local/bin/ps2png  $dir" . "/multi" . $_ . $timeid
      . ".ps $pnglocation"
      . "/multi"
      . $_
      . $timeid . ".png ";
    system($cstr);
}


