#!/usr/bin/perl
# $Id: plot_leak.pl,v 1.2 2013/02/21 13:30:31 sqko Exp $
use strict;
use warnings;
use AFM;

my $VERSION = 0.01;
my $PROGRAM = 'new_leak.pl';


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

my $usernumber = $<;
my $username = &AFM::get_user_name($usernumber);
my $testusername = 'rig'.$ARGV[0];
if ($username ne $testusername)
{
    print "wrong user: $username !\n";
    print "To access data for rig $ARGV[0] you must be user rig$ARGV[0]!\n";
    exit 1;
}

my $rig = $ARGV[0];
if ( !&AFM::check_rig_nr($rig) ) 
{
    print "Rig $rig is not valid!\n";
    exit 1;
}
my $test = &AFM::get_test_nr($rig);
if (scalar(@ARGV) > 1) 
{
    my $string = $ARGV[1];
    $string =~ /(\d+)/;
    my $ttest = $1;
    if (defined($ttest))
    {
	$test = $ttest+0;
    }
}

my $datadir = $AFM::publicdir.'rig'.$rig.'/'.$rig.'test'.$test.'/';
my $proglog = $datadir.'proglog';
my $jdata = $datadir.'jdata';
my $str = `/usr/bin/head -1 $jdata`;
chomp $str;
my @l = split(/[\s\t]+/,$str);
my $ucol = 0;
for(my $x = 0; $x < @l; $x++)
{
    $ucol = $x+1 if ($l[$x] =~ /utime/);
}
my @measure = ();

open DATA, $proglog or die "could not open file $proglog\n";
while (!eof(DATA))
{
    my $str = <DATA>;
    if ($str =~ /leak measurement\s*\#\s*(\d+)/i)
    {
	push @measure, $1;
	print $str if ($debug);
    }
}
close DATA;
my @leaklines = ();

for my $line (@measure)
{
    my $notfound = 1;
    open DATA, $jdata or die "Could not open file $jdata\n";
    while (($notfound) && (!eof(DATA)))
    {
	my $str = <DATA>;
	my @list = split(/\s+/,$str);
	if ($list[$ucol] > $line)
	{
	    $notfound = 0;
	    push @leaklines, &get_leak($str).'    #'.$line."\n";
	    $str = <DATA>;
	    push @leaklines, &get_leak($str).'    #'.$line."\n";
	    $str = <DATA>;
	    push @leaklines, &get_leak($str).'    #'.$line."\n";
	}
    }
    close DATA;
}
my $outdir = $datadir.'leak/';
if (!(-d($outdir)))
{
    system("/bin/mkdir $outdir");
}
my $outfile = $outdir.'leaklines';
open OUT, '>', $outfile or die "Could not open output file $outfile\n"; 
print OUT @leaklines;
close OUT;

### Finding mean air flow###
my $cmd = '/bin/awk \'{print $20 }\' '.$outfile;
my @list = `$cmd`;
@list = sort(@list);
my $n = @list;
my $Mair = 0;
if ($n/2 == int($n/2))
{
    $Mair = ($list[($n/2)-1] + $list[$n/2])/2;
}
else
{
    $Mair = $list[int($n/2)];
}
### Finding mean H2 flow###
$cmd = '/bin/awk \'{print $16 }\' '.$outfile;         
@list = `$cmd`;
@list = sort(@list);
my $Mh2 = 0;
$n = @list;
if ($n/2 == int($n/2))
{
    $Mh2 = ($list[($n/2)-1] + $list[$n/2])/2;
}
else
{
    $Mh2 = $list[int($n/2)];
}
my $output = $outdir.'constair';
open DATA,'<',$outfile or die "Could not open file $outfile\n";
open OUT,'>',$output or die "Coudl not open output file $outfile\n"; 
while (my $str = <DATA>)
{
    $str =~ /air\s+([\d\.\-]+)/i; 
    my $air = $1+0;
    if (($air < $Mair+$Mair*0.05) && ($air > $Mair-$Mair*0.05))
    {
	print OUT $str;
    } 
}
close OUT;
close DATA;
$output = $outdir.'consth2';
open DATA, $outfile or die "Could not open file $outfile\n";
open OUT, "> $output" or die "Coudl not open output file $outfile\n"; 
while (!eof(DATA))
{
    my $str = <DATA>;
    $str =~ /H2\s+([\d\.\-]+)/i; 
    my $air = $1+0;
    if (($air < $Mh2+$Mh2*0.05) && ($air > $Mh2-$Mh2*0.05))
    {
	print OUT $str;
    } 
}
close OUT;
close DATA;
$cmd = '/bin/awk \'{print $16 " " $24 " " $27 " " $30 }\' '.$outdir.'constair | /bin/sort -n > '.$outdir.'sorth2_'.$Mair;         
system($cmd);
$cmd = '/bin/awk \'{print $20 " " $24 " " $27 " " $30 }\' '.$outdir.'consth2 | /bin/sort -n > '.$outdir.'sortair_'.$Mh2;         
system($cmd);

my $pngdir = $outdir.'png/';
if (!(-d($pngdir)))
{
    system("/bin/mkdir $pngdir");
}
my $psdir = $outdir.'ps/';
if (!(-d($psdir)))
{
    system("/bin/mkdir $psdir");
}
my $GNUPLOT = '/usr/bin/gnuplot';
my $gpfile = $outdir.'leakH2.gp';

my $area = &AFM::get_config_value_old($rig,'area',$test); 
$area = &AFM::get_usercv_test($rig,$test,'main','cell_area') unless ($area);
$area = 1 unless ($area); ### Default ###

my $pngpoints    = "points pointtype 7 pointsize 0.15";
my $pspoints     = "points pointtype 7 pointsize 0.15";
my $res_pspoints = "points pointtype 2 pointsize 0.75";
my $ph2points    = "points pointtype 5 pointsize 0.15";
my $ppoints      = $pspoints;
 
my $Mh2m = int($Mh2+0.5);
my $Mairm = int($Mair+0.5);
my $termtype = "post portrait enhanced color 10";
my $psfile = $psdir.'leak_h2var.ps';
open GP, "> $gpfile" or die "Coudl not open gnuplot file $gpfile\n";
my $plotfile = $outdir.'sorth2_'.$Mair;
chomp $plotfile;
    print GP <<END;
set term $termtype
set out \'$psfile\'
set size 1,0.35
set xtics nomirror
set ytics nomirror
set ylabel "Leak (mA/cm^2)"
set xlabel "H_2 flow (L/h)"
set title "Leak current at $Mairm L/h air"
f(x) = x<0?1/0:x
set yr[0:]
set xr[0:]
pl '$plotfile' u 1:(f(\$2) * 1000/$area) tit 'pO_2 in' w points, ''  u 1:(f(\$3) * 1000/$area) tit 'Cell' w points, '' u 1:(f(\$4) * 1000/$area) tit 'pO_2 out' w points 
END
    close GP;
$cmd = "$GNUPLOT $gpfile";
system($cmd);


$gpfile = $outdir.'leakair.gp';
    $plotfile = $outdir.'sortair_'.$Mh2;
chomp $plotfile;
$psfile = $psdir.'leak_airvar.ps';
open GP, "> $gpfile" or die "Coudl not open gnuplot file $gpfile\n";
print GP <<END;
set term $termtype
set out \'$psfile\'
set size 1,0.35
set xtics nomirror
set ytics nomirror
set ylabel "Leak (mA/cm^2)"
set xlabel "air flow (L/h)"
set title "Leak current at $Mh2m L/h H_2"
set yr[0:]
set xr[0:]
f(x) = x<0?1/0:x
pl '$plotfile' u 1:(f(\$2) * 1000/$area) tit 'pO_2 in' w points, ''  u 1:(f(\$3) * 1000/$area) tit 'Cell' w points, '' u 1:(f(\$4) * 1000/$area) tit 'pO_2 out' w points 
END
$cmd = "$GNUPLOT $gpfile";
system($cmd);

$cmd = '/usr/local/bin/ps2png ';
my $command = $cmd.$psdir.'leak_h2var.ps'." $pngdir".'leak_h2var.png';
print $command,"\n" if ($debug);
system($command);
$command = $cmd.$psdir.'leak_airvar.ps'." $pngdir".'leak_airvar.png';
print $command,"\n" if ($debug);
system($command);

exit;

sub get_leak($)
{
    my $str = $_[0];
    my $po2i = get_data($str,'O2_in');
    my $poto =get_data($str,'O2_out');
    my $OCV = get_data($str,'cell_voltage');
    my $Tcell = get_data($str,'T_center');
    my $ti = get_data($str,'T_in');
    my $to = get_data($str,'T_out');
    my $H2 = get_data($str,'h2');
    my $O2 = get_data($str,'o2');
    my $air = get_data($str,'air');
    my $ch4 = get_data($str,'ch4');
    my $water = get_data($str,'bottle_temp');
    my $current = get_data($str,'current');
    my $wet = get_data($str,'bottle_temp_enabled');
    my $o2cutof = &AFM::get_config_value_old($rig,'o2_cutoff',$test);
    my $ch4cutof = &AFM::get_config_value_old($rig,'ch4_cutoff',$test);
    $o2cutof = &AFM::get_usercv_test($rig,$test,'gas_o2','cutoff_report',$test) unless ($o2cutof);
    $ch4cutof = &AFM::get_usercv_test($rig,$test,'gas_ch4','cutoff_report') unless ($ch4cutof);
    $o2cutof += 0;
    $ch4cutof += 0;
    if ($O2 < $o2cutof){$O2 = 0};
    my $leaki = 'NA';
    my $leakc = 'NA';
    my $leako = 'NA';
    my $command = '/usr/local/bin/leak --command I --H2flow '.$H2.' --O2_add '.$O2.' --water '.$water;
    $po2i = $po2i/1000;
    $OCV = -$OCV/1000;
    $poto = $poto/1000;
    $command .= ' --dry 1' unless ($wet);
    my $cmd = $command .' --cell '.$ti.' --emf '.$po2i;
    print $cmd,"\n" if ($debug);
    if ($ch4 < $ch4cutof)
    {
	$leaki = `$cmd`+0;
	$leaki = &rem_dig($leaki);
    }
    
    $cmd = $command .' --cell '.$Tcell.' --emf '.$OCV;
    print $cmd,"\n" if ($debug);
    if ($ch4 < $ch4cutof)
    {
	$leakc = `$cmd`+0;
	$leakc = &rem_dig($leakc);
    }
    
    $cmd = $command .' --cell '.$to.' --emf '.$poto;
    print $cmd,"\n" if ($debug);
    if ($ch4 < $ch4cutof)
    {
	$leako = `$cmd`+0;
	$leako = &rem_dig($leako);
    }
    my $res = "water $water T $Tcell Tin $ti  Tout $to  OCV $OCV  O2in $po2i  O2out $poto  H2 $H2  O2 $O2  air $air CH4 $ch4 ";
    $res = $res . "Leak_in: $leaki A    Leak_cell: $leakc A    Leak_out: $leako A";
    return $res;
}

sub get_data($$)
{
    my $data = $_[0];
    my $id = $_[1];
    $data =~ /\s+$id\s+([\+\-\d\.eE]+)/;
    return $1+0;
}

sub rem_dig($)
{
    my $x = $_[0];
    if ($x=~ /(^\-*\d\.\d\d\d)/){return $1+0};
    if ($x=~ /(\-*\d\d\.\d\d)/){return $1+0};
    if ($x=~ /(\-*\d\d\d\.\d)/){return $1+0};
    return $x;
}
