#!/usr/bin/perl
# $Id: ivplot.pl,v 1.2 2006/04/11 11:49:55 skoch Exp $
use AFM;

# iv id string for gnuplot label

$no_id="iV ";
if ( scalar(@ARGV) < 1 ) {
    print 'Use: ivplot.pl $rig (Hydrogen||air||none) [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;
}

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

$nskip     = 10;
$linetype  = 1;
$pointtype = 1;
$pointsize = 1;
$pngpoints = "points pointtype 7 pointsize 0.15";
$pspoints  = "points pointtype 7 pointsize 0.15";
$ph2points = "points pointtype 5 pointsize 0.15";
$ppoints   = "lines";

$termtype = "post portrait enhanced color 10";

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

$pssize = 1;
$rigno  = $ARGV[0];
&check_run($rigno);

$awklocation = '/usr/local/bin/awk/';

my $testno = 0;

$h2plot  = ( $ARGV[1] =~ /[Hh]/ );
$allplot = ( $ARGV[1] =~ /[Nn]/ );

if ($h2plot) {
    $tit   = "H_2";
    $input = "h2variation";
    $notit = "Air";
}
else {
    $tit   = "Air";
    $input = "airvariation";
    $notit = "H_2";
}

if ($allplot) {
    $tit   = "all";
    $input = "ivtable";
    $notit = "";
}

if ( scalar(@ARGV) > 2 ) {
    $ttestno = $ARGV[2];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
else {
    $testno = &AFM::get_test_nr($rigno);
}
$htmllocation =  "/home/http/html/rig" . $rigno . "/" . $rigno . "test" . $testno;

$plotfile = $htmllocation . "/jdata";
if ( !( -e ($plotfile) ) ) {
    print "$plotfile not found!!\n";
    exit 1;
}
$plotfile2 = $htmllocation . "/iv/ivdatadir-1/ivdata";
if ( !( -e ($plotfile2) ) ) {
    print "$plotfile2 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 = `tail -1 $plotfile2`;
@Fld = split ( ' ', $line, 9999 );

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

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

}

$xcolumn     = 1;
$current     = $col{"current"};
$cellvoltage = $col{"cell_voltage"};
$temperature = $col{"T_center"};
$h2          = $col{"h2"};
$o2          = $col{"o2"};
$air         = $col{"air"};
$o2in        = $col{"O2_in"};
$inplaneh2   = $col{"Inplane_V_hydrogen"};
$ASR         = $col{'ASR_corr'};
$Rsek         = $col{'R_secant'};

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

$grfile  = "$ivlocation" . "/" . $tit . "_iv.gp";
$grfile2  = "$ivlocation" . "/" . $tit . "_ASR.gp";
$fitfile = "$ivlocation" . "/fit_" . $tit . "_iv.gp";

open( GRAPH, "> $grfile" )  || die;
open( GRAPH2, "> $grfile2" )  || die;
open( FIT,   "> $fitfile" ) || die;

$pnglocation = $ivlocation . "/png";
$dir         = $pnglocation;

if ( !( -d $dir ) ) { $mk = system("mkdir $dir") }
$pslocation = $ivlocation . "/ps";
$dir        = $pslocation;
if ( !( -d $dir ) ) { $mk = system("mkdir $dir") }

$outfile    = $dir . "/iv-" . $tit . ".eps";
$outfile2    = $htmllocation.'/ps/ASR-' . $tit . '.ps';
$outpngfile = $pnglocation . "/iv-" . $tit . ".png";

while (<STDIN>) {
    chomp;    # strip record separator
    @Fld = split ( /\s+/, $_, 9999 );
    if ( $#Fld > 2 ) {
        for ( $i = 0 ; $i < $#Fld ; $i += 2 ) {

            $data{ $Fld[$i] } = $Fld[ $i + 1 ];
        }
        $datestart = $Fld[1];
        $nstart    = $data{"nstart"};
        $nstop     = $data{"nstop"};
        $ncmax     = $data{"ncmax"};
        $airmax    = &round( $data{"Air"}, 1 );
        $h2max     = &round( $data{"H_2"}, 1 );
        $iv_id     = $data{"ivnr"};
	$plotfile3 = $ivlocation.'/ivdatadir-'.$iv_id.'/ivdata';
        if ($h2plot) { $flow = $h2max; $noflow = $airmax }
        else {
            $flow   = $airmax;
            $noflow = $h2max;
        }
        $parfile =  "$ivlocation" . "/" . $datestart . "_fit_" . $tit . "_iv.par";
        &fitgp();
        if ( !($allplot) ) {
            $repl = "repl -100 tit \"".$no_id.$iv_id.", $flow L/h\" w  linespoints  lt $linetype  pt $pointtype pointsize $pointsize";
        }
        if ( !$lineno++ ) {
            &printgp();
        }
        else {
            $linetype  = $lineno + 1;
            $pointtype = $lineno + 1;
            if ( !($allplot) ) {
                $repl = "repl -100 tit \"".$no_id.$iv_id.", $flow L/h\" w  linespoints  lt $linetype  pt $pointtype pointsize $pointsize";
            }
            print GRAPH <<END;
repl "< awk 'NR>($nstart-1);NR>($nstop){exit}' $plotfile"  u (\$$current/$area):$cellvoltage  notit  w  lines lt $linetype
repl "< awk 'NR>($nstart-1)&&NR%($nskip)==0;NR>($nstop){exit}' $plotfile"  u (\$$current/$area):$cellvoltage  notit  w  points lt  $linetype  pt $pointtype pointsize $pointsize
$repl

END
            print GRAPH2 <<END;
repl "$plotfile3"  u (\$$current/$area):(\$$ASR>0?\$$ASR:1/0)  notit  w  lines lt $linetype
repl "$plotfile3"  u (\$$current/$area):(\$$ASR>0?\$$ASR:1/0)  notit  w  points lt  $linetype  pt $pointtype pointsize $pointsize
$repl

END
        }
    }
}    # ps-plot

print GRAPH <<END;
set term $termtype
set out \'$outfile\'
repl
set out
quit
    
END

print GRAPH2 <<END;
set term $termtype
set out \'$outfile2\'
repl
set out
quit
    
END

close(GRAPH);
close(GRAPH2);

print FIT <<END;
quit
    
END

close(FIT);

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

# make png-file

$cstr =
"echo \"quit\" | /usr/bin/gs -q -sDEVICE=png256 -sOutputFile=$outpngfile  $outfile > /dev/null";

#print $cstr;
system($cstr);

#make parameter (fit) file

$cstr = "$GNUPLOT $fitfile > /dev/null 2> /dev/null";
system($cstr);
exit;





sub printgp {
    print GRAPH <<END;
reset
set term dumb
set out '/dev/null'
set nomulti
set lmargin 10
set rmargin 10
set bmargin 4
set size 1,0.5
set grid  linetype 5
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Cell voltage (mV)"
set xlabel "current density (A/cm^2)"
#set nok
set xr[0:]
set yr[400:1100]
set ytics 400,100,1100
pl "< awk 'NR>($nstart-1);NR>($nstop){exit}' $plotfile"  u (\$$current/$area):$cellvoltage  notit  w  lines lt $linetype
repl "< awk 'NR>($nstart-1)&&NR%($nskip)==0;NR>($nstop){exit}' $plotfile"  u (\$$current/$area):$cellvoltage  notit  w  points lt  $linetype  pt $pointtype pointsize $pointsize
$repl
END

    print GRAPH2 <<END;
reset
set term dumb
set out '/dev/null'
set nomulti
set lmargin 10
set rmargin 10
set bmargin 4
set size 1,0.5
set grid  linetype 5
set border 3
set xtics nomirror
set ytics nomirror
set ylabel "Cell resistance ({/Symbol W}cm^2)"
set xlabel "current density (A/cm^2)"
#set nok
set xr[0:]
set yr[0:]
set ytics
pl "$plotfile3"  u (\$$current/$area):(\$$ASR>0?\$$ASR:1/0)  notit  w  lines lt $linetype
repl "$plotfile3"  u (\$$current/$area):(\$$ASR>0?\$$ASR:1/0)  notit  w  points lt  $linetype  pt $pointtype pointsize $pointsize
$repl
END

}

sub round {
    local ( $X, $a ) = @_;
    int( ( $X / $a ) + 0.5 ) * $a;
}

sub fitgp {
    print FIT <<END;
femf(x)=ae0+(ae1+(ae2+(ae3+(ae4+ae5*x)*x)*x)*x)*x
fc(x)=ac0+(ac1+(ac2+(ac3+(ac4+ac5*x)*x)*x)*x)*x

fit femf(x) "< awk 'NR>($nstart-1);NR>($ncmax){exit}' $plotfile"  u (\$$current/$area):$cellvoltage  via ae0,ae1,ae2,ae3,ae4,ae5
fit fc(x) "< awk 'NR>($nstart-1);NR>($ncmax){exit}' $plotfile"  u $cellvoltage:(\$$current/$area) via ac0,ac1,ac2,ac3,ac4,ac5
emf0_3=femf(0.3)
emf0_5=femf(0.5)
emf0_8=femf(0.8)
c1000=fc(1000)
c800=fc(800)
c700=fc(700)
c600=fc(600)
sa \'$parfile\'
END
}

