#!/usr/bin/perl
# $Id: ivdataplot-3.0.pl,v 1.9 2015/11/06 11:09:10 sqko Exp $
#use Readline;

my $VERSION = 0.2;
my $PROGRAM = 'ivdataplot.pl';


use AFM;

$GNUPLOT   = '/usr/bin/gnuplot';
$CONVERT   = '/usr/bin/convert';
%plotlabel = (
    "ch4"    => "CH_4",
    "h2"     => "H_2",
    "o2"     => "O_2",
    "O2_in"  => "O_2 in",
    "O2_out" => "O_2 out"
);

sub printgp {

    print GRAPH <<END;
$reset
set $key
    f(x)=x!=-32768?x:1/0
set term $term 
set out \'$outfile\'
set nomulti
set lmargin 12
set rmargin 10
set bmargin 4
END
my $gs = $gsize;
$gs = '0.75,0.75' if ($term =~ /^png$/);
    print GRAPH <<END;
set size $gs
set grid  linetype 5
set border 3
set xtics nomirror
set ytics nomirror
set ylabel \"$ylabel\"
set xlabel \"$xlabel\"
set au
#set xr[0:]
#set yr[0:]
$pltcmd
#pause -1
END
}
$xlabel = "Time, hours";
$key    = " nokey";
$ncol   = 3;
$rigno  = 0;
$debug = 0;

for my $teststr (@ARGV) {
    if ( $teststr =~ /--version/ ) {
        print "$PROGRAM is: $VERSION\n";
        exit;
    }
    if ( $teststr =~ /--debug/)
    {
	$debug = 1;
    }
}

if ( scalar(@ARGV) < 3 ) {
    print "Usage: $PROGRAM rignr testnr iv_curvenr\n";
    exit;
}

if ( scalar(@ARGV) > 3 ) {
    for ( $i = 2 ; $i < $#ARGV ; $i += 2 ) {
        print $ARGV[$i], "\n";
        push ( @ivnumbers, $ARGV[$i] );
        push ( @ivlabels,  $ARGV[ $i + 1 ] );

    }
}

if ( scalar(@ARGV) > 0 ) {
    $rigno = $ARGV[0];
    $rigno =~ /(\d+)/;
    $rigno = $1;
}
&check_run($rigno);

$gsize       = "1,0.5"; # 0.7,0.35";
$psize       = 0.5;
$idat        = 0;
$awklocation = "/usr/local/bin/awk/";
$homedir     = '/home/rig'. $rigno;

my $testno = 1;
my $ivno   = 1;

if ( scalar(@ARGV) > 1 ) {
    $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
$currenttest = $testno;
$area = &AFM::get_usercv_test( $rigno, $testno,'main','cell_area');
$area = &AFM::get_config_value_old($rigno,'area',$testno) unless ($area);
if ( scalar(@ARGV) > 2 ) {
    $ivno = $ARGV[2];
    $ivno =~ /(\d+)/;
    $ivno = $1;
}

$currentlabel = &AFM::get_usercv_test($rigno,$testno,'IV_control','current_label');
$voltlabel = &AFM::get_usercv_test($rigno,$testno,'IV_control','voltage_label');
$voltlabel = 'cell_voltage' unless ($voltlabel);  ## Default value for backwards compatibility ###
$currentlabel = 'current' unless ($currentlabel); ## Default value for backwards compatibility ###


$ivdir =
  $AFM::publicdir . "rig" . $rigno . "/" . $rigno . "test"
  . $currenttest
  . "/iv/ivdatadir-"
  . $ivno;

$cstr      = "/bin/awk 'NR==" . $ivno . "' $ivdir/../ivtable-avg";
print $cstr, "\n" if ($debug);
@avgvalues = `$cstr`;

$cstr        = "/bin/awk 'NR==" . $ivno . "' $ivdir/../ivtable";
print $cstr, "\n" if ($debug);
@tablevalues = `$cstr`;

$html = open( HTML, "> $ivdir" . "/index.html" );

$ivname = $ivdir . "/ivdata";

$| = 1;

$c     = "head -1  $ivname";
@line1 = split ( /\s+/, `$c` );

print HTML <<END;
<html>
<head>
<title>Plot</title>
</head>
<body>
<table>
<tbody>
<tr>
END
for ( $i = 0 ; $i <= $#ivlabels ; $i++ ) {
    $ivsumlabel = $ivsumlabel . "_" . $ivnumbers[$i];
}

$iplot++;
#$gpfile = $ivdir . "/ivplot" . $ivsumlabel ."_".$iplot.".gp";
#open( GRAPH, "> $gpfile" );

if ( -f $ivname ) {
    $pngdir  = $ivdir . "/png";
    $psdir   = $ivdir . "/ps";
    $datadir = $ivdir . "/data";
    if ( !( -d $pngdir ) )  { system("mkdir $pngdir") }
    if ( !( -d $psdir ) )   { system("mkdir $psdir") }
    if ( !( -d $datadir ) ) { system("mkdir $datadir") }
    my @allvalid = &AFM::valid_data($ivname,0);
    for ( $i = 2 ; $i <= $#line1 ; $i += 2 ) {
	my $valid = 0;
	if (($allvalid[0] == 1) && ($allvalid[$i+1] == 1))
	{
	    $valid = 1;
	}
	if ($valid)
	{
	    if ( ( ( $i - 2 ) % ($ncol) == 0 ) ) { print HTML "</tr>\n<tr>" }
	    
	    print HTML
		"<td><a href=data/$line1[$i]><img src=\"png/$line1[$i].png\" alt=\"image\"></a></td>\n";
	    
	    chomp( $line1[$i] );
	    $ylabel = $line1[$i];
	    $col{$ylabel} = $i + 2;
	    
	    $outps  = $psdir . "/" . $ylabel . ".eps";
	    $outpng  = $pngdir . "/" . $ylabel . ".png";
	    push ( @names, $ylabel );
	    
	    if ( exists( $plotlabel{$ylabel} ) ) { $ylabel = $plotlabel{$ylabel} }
	    else { $ylabel =~ s/_/ /g; }
	    
	    $ycol    = $i + 2;
	    $pltcmd  = "plot \'$ivname\' u 1:(f(\$" . $ycol . "))";
	    $term    = "png";
	    $outfile = $outpng;
	    $reset   = "reset";
$iplot++;
$gpfile = $ivdir . "/ivplot" . $ivsumlabel ."_".$iplot.".gp";
open( GRAPH, "> $gpfile" );

	    printgp();
	}
    }

}

$ylabel = "ivcurve";
        $outps  = $psdir . "/" . $ylabel . ".eps";

push ( @names, $ylabel );

$xcol   = $col{$currentlabel};
$i      = 0;
$ycol   = $col{$voltlabel};
$key    = " key";
$ylabel = "Cell Voltage, V";
$xlabel = "Current density, A/cm^2";
$pltcmd =
  "plot \'$ivname"
  . "_up\' u (\$$xcol" . "/"
  . "$area):(f(\$"
  . $ycol
  . ")/1000.0) tit \""
  . " up\" w linesp,\'$ivname"
  . "_down\' u (\$$xcol" . "/"
  . "$area):(f(\$"
  . $ycol
  . ")/1000.0) tit \"down\" w linesp";

$term = "post portrait enhanced color";

$outfile =$outps;


$reset = "reset";
$iplot++;
$gpfile = $ivdir . "/ivplot" . $ivsumlabel ."_".$iplot.".gp";
open( GRAPH, "> $gpfile" );
printgp();




$xcol = $col{$currentlabel};
$key  = " key";

$ycol   = $col{"R_secant"};
$ycol1  = $col{"ASR_corr"};
$ylabel = "Area specific resistance ({/Symbol W} cm^2)";
$xlabel = "Current density, A/cm^2";
$pltcmd =
  "plot \'$ivname"
  . "_up\' u (\$$xcol/$area):(f(\$"
  . $ycol
  . ")) tit \"Secant, up\" w linesp,\'$ivname"
  . "_down\' u (\$$xcol/$area):(f(\$"
  . $ycol
  . ")) tit \"Secant, down\" w linesp,\'$ivname"
  . "_up\' u (\$"
  . $xcol . "/"
  . $area
  . "):(f(\$"
  . $ycol1
  . ")) tit \"corrected, up\" w linesp,\'$ivname"
  . "_down\' u (\$"
  . $xcol . "/"
  . $area
  . "):(f(\$"
  . $ycol1
  . ")) tit \"corrected, down\" w linesp";
$term    = "post portrait enhanced color";
$ylabel="ivcurve-resistance";
        $outps  = $psdir . "/" . $ylabel . ".eps";
	push (@names,$ylabel);
$ylabel = "Area specific resistance ({/Symbol W} cm^2)";
$outfile = $outps;
$reset   = "reset";
$iplot++;
$gpfile = $ivdir . "/ivplot" . $ivsumlabel ."_".$iplot.".gp";
open( GRAPH, "> $gpfile" );
printgp();
$xcol = $col{$currentlabel};
$key  = " key";

if (@ivlabels) {
$ycol   = $col{"R_secant"};
$ycol1  = $col{"ASR_corr"};

$xlabel = "Current density, A/cm^2";
$pltcmd="plot ";
$pltcmd1="plot ";
    for ( $i = 0 ; $i <= $#ivlabels ; $i++ ) {

        print $ivnumbers[$i], "\n";
        $ivdir =
          $celletest_header::publicdir . "rig" . $rigno . "/" . $rigno . "test"
          . $currenttest
          . "/iv/ivdatadir-"
          . $ivnumbers[$i];

        $ivname = $ivdir . "/ivdata";


$pltcmd =$pltcmd 
."\\\n"
    ." \'$ivname"
  . "_up\' u (\$$xcol/$area):(f(\$"
  . $ycol
  . ")) tit \""
  .    $ivlabels[$i]
      ." secant, up\" w linesp,"
."\\\n"
."'$ivname"
  . "_down\' u (\$$xcol/$area):(f(\$"
  . $ycol
    . ")) tit \"down\" w linesp";
if ($i<$#ivlabels ) {$pltcmd =$pltcmd .","};
 
$pltcmd1 =$pltcmd1 
."\\\n"
    ." \'$ivname"
  . "_up\' u (\$$xcol/$area):(f(\$"
  . $ycol1
  . ")) tit \""
  .    $ivlabels[$i]
      ." corrected, up\" w linesp,"
."\\\n"
."'$ivname"
  . "_down\' u (\$$xcol/$area):(f(\$"
  . $ycol1
    . ")) tit \"down\" w linesp";
if ($i<$#ivlabels ) {$pltcmd1 =$pltcmd1 .","};

}


$term    = "post portrait enhanced color";
$ylabel="ivcurve-secant-resistance"."$ivsumlabel";

        $outps  = $psdir . "/" . $ylabel . ".eps";
	push (@names,$ylabel);
$outfile = $outps;
$ylabel = "Area specific resistance ({/Symbol W} cm^2)";
$reset   = "reset";
$iplot++;
$gpfile = $ivdir . "/ivplot" . $ivsumlabel ."_".$iplot.".gp";
open( GRAPH, "> $gpfile" );
printgp();

$ylabel="ivcurve-corrected-resistance"."$ivsumlabel";
$pltcmd=$pltcmd1;
        $outps  = $psdir . "/" . $ylabel . ".eps";
	push (@names,$ylabel);
$outfile = $outps;
$ylabel = "Area specific resistance ({/Symbol W} cm^2)";
$reset   = "reset";
$iplot++;
$gpfile = $ivdir . "/ivplot" . $ivsumlabel ."_".$iplot.".gp";
open( GRAPH, "> $gpfile" );
printgp();

}



print HTML <<END;
<tr></table>
</body>
</html>
END
close(HTML);

my $teststr = "$ivdir/data";
if ( -e ($testsrt) ) {
    $cstr = "rm $ivdir/data/*";
    print $cstr, "\n" if ($debug);
    system($cstr);
}

$ivdirdata = $ivdir.'/data';
if (-e($ivdirdata))
{
    $cstr = "rm -f $ivdir" . "/data/*";
    print $cstr, "\n" if ($debug);
    system($cstr);
}
$cstr = "/bin/awk \'{ for (i=3;i<=NF-1;i+=2) print \$1+0,\$(i+1)+0 >> \"$ivdir/data/\"\$(i)}\' $ivname ";

print $cstr, "\n" if ($debug);

system($cstr);
close(GRAPH);

for (1..$iplot) { 
$gpmess = $ivdir . "/ivplot".$_.".mess";
$gperr  = $ivdir . "/ivplot.".$_.".err";


$gpfile = $ivdir . "/ivplot" . $ivsumlabel ."_".$_.".gp";
# print $gpfile,"\n";
system("$GNUPLOT $gpfile > $gpmess 2> $gperr");
		 }
#system("$GNUPLOT $gpfile >> $gpmess 2>> $gperr");

### Convert ps files to png ###
@names = ("ivcurve-resistance","ivcurve");
for (@names) {
    print "converting ",$_,"\n";
    my $source = $psdir.'/'.$_.'.eps';
    my $target = $pngdir.'/'.$_.'.png';
    my $cstr = "/usr/local/bin/ps2png $source $target";
#    $cstr =
#      "echo \"quit\" | /usr/bin/gs -q -sDEVICE=png256 -sOutputFile=-   $psdir/"
#      . $_
#      . ".eps 2> /dev/null  | $CONVERT -  -crop 0x0  - | $CONVERT -border 15x15 -bordercolor white -  $pngdir/"
#      . $_ . ".png";
    print $cstr, "\n" if ($debug);
    system($cstr);
}

if (chdir $ivdir)
{
    my $cmd = 'for f in ivplot*.mess; do s'."=`".'stat -c "%s" $'."f`".'; if [ $s = 0 ]; then rm $f; fi; done;';
    system($cmd);
    $cmd = 'for f in ivplot*.err; do s'."=`".'stat -c "%s" $'."f`".'; if [ $s = 0 ]; then rm $f; fi; done;';
    system($cmd);
}

