#!/usr/bin/perl
# $Id: resistance_flow_variation_plot.pl,v 1.2 2015/04/15 10:55:29 sqko Exp $
use AFM;
$GNUPLOT = '/usr/bin/gnuplot';
my $rigno = 0;
if ( scalar(@ARGV) > 0 ) {
    $rigno = $ARGV[0];
    $rigno =~ /(\d+)/;
    $rigno = $1;
}
&check_run($rigno);
my $testno = 1;
if ( scalar(@ARGV) > 1 ) {
    $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}
$currenttest = $testno;

$ivdir =  $AFM::publicdir . "rig" . $rigno . "/" . $rigno . "test"  . $currenttest  . "/iv";
my $command = '/bin/rm -f '.$ivdir.'/*.par';
system($command);
my $command = '/bin/rm -f '.$ivdir.'/*.gp';
system($command);

setup();

$pngdir  = $ivdir . "/png";
$psdir   = $ivdir . "/ps";
$txt = $ivdir . "/text";
if ( !( -d $pngdir ) )  { system("mkdir $pngdir") }
if ( !( -d $psdir ) )   { system("mkdir $psdir") }
if ( !( -d $txt ) ) { system("mkdir $txt") }


make_flow_variation_files();




$ytype="R_secant";
$xtype  = "h2";
$xlabel = "H_2 flow (l/h)";
$subdir   = $plotdir . "/../plot_ivtable_sort_Air_constant";
$gpfile   = $subdir . "/fuel_flow_variation_R_imax_etc.gp";
$psfile   = $plotdir . "/../ps/fuel_flow_variation_R_imax_etc.ps";
$pngfile  = $plotdir . "/../png/fuel_flow_variation_R_imax_etc.png";

gas_flow_variation_R_imax();

$xtype  = "air";
$xlabel = "Air flow (l/h)";
$subdir   = $plotdir . "/../plot_ivtable_sort_H_2_constant";
$gpfile   = $subdir . "/air_flow_variation_R_imax_etc.gp";
$psfile   = $plotdir . "/../ps/air_flow_variation_R_imax_etc.ps";
$pngfile  = $plotdir . "/../png/air_flow_variation_R_imax_etc.png";


gas_flow_variation_R_imax();

$xtype  = "air";
$xlabel = "Air flow (l/h)";
$subdir   = $plotdir . "/../plot_ivtable_sort_H_2_constant";
$gpfile   = $subdir . "/air_flow_variation_R_current.gp";
$psfile   = $plotdir . "/../ps/air_flow_variation_R_current.ps";
$pngfile  = $plotdir . "/../png/air_flow_variation_R_current.png";


gas_flow_variation_R_current();

$xtype  = "h2";
$xlabel = "H_2 flow (l/h)";
$subdir   = $plotdir . "/../plot_ivtable_sort_Air_constant";
$gpfile   = $subdir . "/fuel_flow_variation_R_current.gp";
$psfile   = $plotdir . "/../ps/fuel_flow_variation_R_current.ps";
$pngfile  = $plotdir . "/../png/fuel_flow_variation_R_current.png";


gas_flow_variation_R_current();

$ytype="Power";
$xtype  = "air";
$xlabel = "Air flow (l/h)";
$subdir   = $plotdir . "/../plot_ivtable_sort_H_2_constant";
$gpfile   = $subdir . "/air_flow_variation_Power.gp";
$psfile   = $plotdir . "/../ps/air_flow_variation_Power.ps";
$pngfile  = $plotdir . "/../png/air_flow_variation_Power.png";


gas_flow_variation_power();

$xtype  = "h2";
$xlabel = "H_2 flow (l/h)";
$subdir   = $plotdir . "/../plot_ivtable_sort_Air_constant";
$gpfile   = $subdir . "/fuel_flow_variation_Power.gp";
$psfile   = $plotdir . "/../ps/fuel_flow_variation_Power.ps";
$pngfile  = $plotdir . "/../png/fuel_flow_variation_Power.png";


gas_flow_variation_power();


$ytype="R_secant";
$xtype  = "T_center";
$xlabel = "T center ^oC";
$subdir   = $plotdir . "/../plot_tempvariation";
$gpfile   = $subdir . "/temp_variation.gp";
$psfile   = $plotdir . "/../ps/temp_variation.ps";
$pngfile  = $plotdir . "/../png/temp_variation.png";

temp_variation();

$ytype="ASR_corr";
$xtype  = "T_center";
$xlabel = "1000 /T center K";
$subdir   = $plotdir . "/../plot_tempvariation";
$gppre   = $subdir . "/arrhenius_temp_variation";
$psfile   = $plotdir . "/../ps/arrhenius_temp_variation.ps";
$pngfile  = $plotdir . "/../png/arrhenius_temp_variation.png";
$tablepre = $plotdir . "/../plot_tempvariation/arrhenius_table";

arrhenius_temp_variation();


#exit;

sub setup {
    $currentepsilon    = 0.05;
    $currentresistance = 0.15;

    @resistance_current_values = ( "0.065", "0.25", "0.5" );

    if ( scalar(@ARGV) < 1 ) {
        print 'Use: resistance_calc.pl $rig   $testno 
 where $rig is the rig number' . "\n";
        print 'and $testno is the test number' . "\n";
        exit 1;
    }
    $ii = 0;

    my $debug = 0;
    for my $string (@ARGV) {
        if ( $string =~ /--debug/ ) {
            $debug = 1;
        }
    }

    $predominant_current = 1;
    my $file = $AFM::publicdir.'iv/predominant_current.txt';
    if (-e $file)
    {
	open MYIN, '<', $file or die "Could not open file $file for reading!\n";
	my $teststr = <MYIN>;
	close MYIN;
	if ($teststr =~ /(\d*\.*\d+)/)
	{
	    $predominant_current = $1;    
	}
    }
    if ( scalar(@ARGV) > 2 ) {
        $tpredominant_current = $ARGV[2];
        $tpredominant_current =~ /([\.\d]+)/;
        $predominant_current = $1;
    }
    $area = &AFM::get_usercv_test($rigno,$testno,'main','cell_area');
    $area = &AFM::get_config_value_old( $rigno, 'area' ,$testno) unless ($area);
    $htmllocation = $AFM::publicdir.'rig' . $rigno . "/" . $rigno . "test" . $testno;

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

    $ivavgtablefile = $htmllocation . "/iv/ivtable-avg";
    $plotfile = $htmllocation . "/jdata";
    open( IVTABLE, $ivtablefile ) || die ("Could not open $ivtablefile");
    $plotdir = $htmllocation . "/iv/plotdata";
}

sub make_flow_variation_files {

    for (
        "ivtable_sort_Air_constant", "ivtable_sort_H_2_constant",
        "tempvariation"
      )
    {
        $name   = $_;
        $subdir = $plotdir . "/../plot_" . $name;

        system("rm -rf  $subdir");
        system("mkdir $subdir");

        $cstr = "cat     $htmllocation" . "/iv/" . $_ . " | awk '{print \$NF}'";
        @lines = `$cstr`;
        $cstr  = " head -1  $plotdir" . "/imaxvalues";
        $line  = `$cstr`;

        @Fld = split ( ' ', $line, 9999 );

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

            $col{ $Fld[$ii1] } = $ii1 + 2;
        }

        @files = `ls $plotdir`;
        for (@files) {
            $filename = $_;
            chomp($filename);

            for (@lines) {
                chomp($_);
		if ($_) {
                $cstr =
                  "awk 'NR==" . $_
                  . "{print ; exit}' $plotdir" . "/"
                  . "$filename >> "
                  . $subdir . "/"
                  . $filename;
                system($cstr);
	    }
            }

        }
    }
};

sub plotcmdline {
    $pltcmd =
      ",\"<paste $subdir" . "/"
      . "$filename $subdir"
      . "/imaxvalues  u 2:(\$"
      . $col{$xtype} . ")\\\n";

}

sub gas_flow_variation_power {
        $iline=0;
    open( GRAPH, "> $gpfile" );
    print GRAPH <<END;
set term post portrait enhanced color 10
set nokey 
set size 1,0.5
set grid
set ylabel \'Power W/cm^2\'
set xlabel \'$xlabel\'
set out \'$psfile\'
set xr[0:]
set yr[0:]
END

    $plotcmd   = "plot ";
    @filenames = ( "powermaxvalues");

    for (@filenames) {
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $xcol    = $col{$xtype}+1;
        $ycol    = $col{$ytype}+1;
        $plotcmd =
          $plotcmd . "\'" . $subdir . "/" . $_
          . "\'  u (\$"
          . $xcol . "):(\$"
          . $ycol
          . ") tit \'"
          . $_
          . "\'\\\n";
    }

    print GRAPH $plotcmd;
    close(GRAPH);
    $cstr = "$GNUPLOT $gpfile";
    system($cstr);
    $cstr = "ps2png $psfile $pngfile";
    system($cstr);
}


sub gas_flow_variation_R_imax {
        $iline=0;
    open( GRAPH, "> $gpfile" );
    print GRAPH <<END;
set term post portrait enhanced color 10
set key left
set size 1,0.5
set grid
set ylabel \'Area specific resistance ({/Symbol W} cm^2)\'
set xlabel \'$xlabel\'
set out \'$psfile\'
set xr[0:]
set yr[0:]
END

    $plotcmd   = "plot ";
    @filenames = ( "rstartvalues", "imaxvalues" );

    for (@filenames) {
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $xcol    = $col{$xtype};
        $ycol    = $col{$ytype};
        $plotcmd =
          $plotcmd . "\'" . $subdir . "/" . $_
          . "\'  u (\$"
          . $xcol . "):(\$"
          . $ycol
          . ") tit \'"
          . $_
          . "\'\\\n";
    }

    @filenames = ("rminvalues");

    for (@filenames) {
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $xcol    = $col{$xtype} + 1;
        $ycol    = $col{$ytype} + 1;
        $plotcmd =
          $plotcmd . "\'" . $subdir . "/" . $_
          . "\'  u (\$"
          . $xcol . "):(\$"
          . $ycol
          . ") tit \'"
          . $_
          . "\'\\\n";
    }
    @filenames = ("R_750_mV");

    for (@filenames) {
	$title=$_;
    $title =~ s/_/ /g;
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $xcol    = $col{$xtype} + 2;
        $ycol    = 2;
        $plotcmd = $plotcmd
          . "\"< paste "
          . $subdir . "/"
          . $_ . " "
          . $subdir
          . "/imaxvalues \"  u (\$"
          . $xcol . "):(\$"
          . $ycol
          . ") tit \'"
          . $title
          . "\'\\\n";
    }

    print GRAPH $plotcmd;
    close(GRAPH);
    $cstr = "$GNUPLOT $gpfile";
    system($cstr);
    $cstr = "ps2png $psfile $pngfile";
    system($cstr);
}
sub gas_flow_variation_R_current {
        $iline=0;
    open( GRAPH, "> $gpfile" );
    print GRAPH <<END;
set term post portrait enhanced color 10
set key left
set size 1,0.5
set grid
set ylabel \'Area specific resistance ({/Symbol W} cm^2)\'
set xlabel \'$xlabel\'
set out \'$psfile\'
set xr[0:]
set yr[0:]
END

    $plotcmd   = "plot ";
    @filenames = ( "current_0.065","current_0.25","current_0.5","current_2_div_3_imax");

    for (@filenames) {
	$title=$_;
    $title =~ s/_/ /g;
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $xcol    = $col{$xtype} + 2;
        $ycol    = 2;
        $plotcmd = $plotcmd
          . "\"< paste "
          . $subdir . "/"
          . $_ . " "
          . $subdir
          . "/imaxvalues \"  u (\$"
          . $xcol . "):(\$"
          . $ycol
          . ") tit \'"
          . $title
          . "\'\\\n";
    }

    print GRAPH $plotcmd;
    close(GRAPH);
    $cstr = "$GNUPLOT $gpfile";
    system($cstr);
    $cstr = "ps2png $psfile $pngfile";
    system($cstr);
}

sub temp_variation {
        $iline=0;
    open( GRAPH, "> $gpfile" );
    print GRAPH <<END;
set term post portrait enhanced color 10
set key right
set size 1,0.5
set grid
set ylabel \'Area specific resistance ({/Symbol W} cm^2)\'
set xlabel \'Temperature ^oC\'
set out \'$psfile\'
#set xr[0:]
#set yr[0:]
END

    $plotcmd   = "plot ";
 
    @filenames = ("rminvalues");

    for (@filenames) {
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $xcol    = $col{$xtype} + 1;
        $ycol    = $col{$ytype} + 1;
        $plotcmd =
          $plotcmd . "\'" . $subdir . "/" . $_
          . "\'  u (\$"
          . $xcol . "):(\$"
          . $ycol
          . ") tit \'"
          . $_
          . "\'\\\n";
    }
    @filenames = ("rstartvalues");

    for (@filenames) {
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $xcol    = $col{$xtype};
        $ycol    = $col{$ytype};
        $plotcmd =
          $plotcmd . "\'" . $subdir . "/" . $_
          . "\'  u (\$"
          . $xcol . "):(\$"
          . $ycol
          . ") tit \'"
          . $_
          . "\'\\\n";
    }

    print GRAPH $plotcmd;
    close(GRAPH);
    $cstr = "$GNUPLOT $gpfile";
    system($cstr);
    $cstr = "ps2png $psfile $pngfile";
    system($cstr);
}

sub arrhenius_temp_variation {
        $iline=0;

    $plotcmd   = "plot ";
 
    @filenames = ("rminvalues");

    for (@filenames) {
	$gpfile=$gppre."_".$_.".gp";
	$tablefile=$tablepre."_".$_;
$psfile   = $plotdir . "/../ps/arrhenius_".$_.".ps";
$pngfile   = $plotdir . "/../png/arrhenius_".$_.".png";

    open( GRAPH, "> $gpfile" );
    print GRAPH <<END;
set term post portrait enhanced color 10
set key right
set size 1,0.5
set grid
set ylabel \'log(1/(Area specific resistance))\'
set xlabel \'1000/Temperature K\'
set out \'$psfile\'
#set xr[0:]
#set yr[0:]
END



        $xcol    = $col{$xtype} + 1;
        $ycol    = $col{$ytype} + 1;


$awkcmd=" awk '{print " 
          . " (1000.0/(\$"
          . $xcol . "+273.0) ),((log(1.0/\$"
          . $ycol
	      . "))) }' "
		  .  $subdir . "/" .$_ 
    ." > $tablefile";

	system($awkcmd);
    $cstr = "/usr/local/bin/activation_energy < $tablefile";
    $res=`$cstr`;
	chomp($res);
        $iline++;
        if ( $iline > 1 ) { $plotcmd = $plotcmd . ","; }
        $plotcmd =
          $plotcmd . "\'" . $tablefile. "'" 
          . " tit \'"
	.$res
. "\'\\\n";
    }
    print GRAPH $plotcmd;
    print GRAPH "\n\n";

    close(GRAPH);
    $cstr = "$GNUPLOT $gpfile";
    system($cstr);
    $cstr = "ps2png $psfile $pngfile";
    system($cstr);
}

