#!/usr/bin/perl
use strict;
use warnings;
use RFC::Header;
my $out = '/tmp/pO2'.$$.'.txt';
my $gp = '/tmp/pO2'.$$.'.gp';
chdir '/tmp';
while (@ARGV)
{
    my $maxy = 1;
    my $f = shift;
    exit unless -e($f);
    open MYIN,'<',$f or die "Could not open file $f: $!\n";
    my $temp = <MYIN>;
    chomp $temp;
    my @dat = <MYIN>;
    close MYIN;
    open OUT,'>',$out or die "Could not open file $out for writing: $!\n";
    foreach (@dat)
    {
	my @l = split(/[\s\t]+/,$_);
	my $emf = -$l[1]/1000;
	my $po2 = `/usr/local/bin/pO2_leak --emf $emf --cell $temp --command po2`;
	$po2 = $po2*1e6;
	print OUT "$l[0]  $po2";
	if (@l > 2)
	{
	    $maxy = abs($l[2]) if (abs($l[2]) > $maxy);
	    print OUT "  $l[2]";
	}
	print OUT "\n";
    }
    close OUT;
    my $out1 = $RFC::Header::publicdir.'/tmp/ing1_'.$$.'.png';
    my $out2 = $RFC::Header::publicdir.'/tmp/ing2_'.$$.'.png';
    open GP,'>',$gp or die "Could not open file $gp for writing: $!\n";
    $maxy = $maxy * 1.05;
    print GP <<END;

set term pngcairo size 600,300    
#set size 1,0.55
set xrange[:]
set yrange[0:]
set xlabel 'N2 flow (L/hour)'
set ylabel 'Oxygen leak (mmol/h)'
set out '$out1'

pO2(x) = fP0 * P0 + (fdn * dn) * x
fP0 = 1
P0 = 4
fdn = 1
dn = 60
fit pO2(x) '$out' u (1/\$1):2 via fdn,fP0
set label sprintf('Po = %.3f ppm',P0 * fP0) at 15,5
R = 0.0821
T = 273.15 + $temp
P = 1
X = 1e-3 * dn * fdn * R * T / P
leaklimit(x) = 15
avgleak(x) = X

dnmax = 15.0 * P * 1e3 /(R * T)
pO2_m(x) = fP0 * P0 + dnmax * x
leak(x,y) = (y - fP0 * P0) * R * T * 1e-3 * x / P

#set label 'Leak = %.2f mmol/h',X at 15,15
#set label 'Limit = 15 mmol/h' at 15,10
#plot '$out' u (1/\$1):2 w linesp lt 3 tit 'Data', pO2(x) tit 'Fit', pO2_m(x) lt 1 tit 'Limit', '$out' u (1/\$1):(leak(\$1,\$2)) tit 'Leak'
plot '$out' u 1:(leak(\$1,\$2)) w linesp lt 3 tit 'Data', avgleak(x) tit 'Fit', leaklimit(x) lt 1 tit 'Limit'
f(x) = 1
set nolabel
set ylabel 'Emf (mV) (air vs air)'
set yrange [-$maxy:$maxy]
set out '$out2'
set xlabel 'Air flow (L/hour)'
plot f(x) lt 1 tit 'Limit', -f(x) lt 1 notitle, '$out' u 1:3 w linesp lt 3 tit 'Data'
set out ''

END
	
    close GP;

    system("/usr/bin/gnuplot $gp");
    print $out1,"\n";
    print $out2,"\n";
}
unlink $out if (-e $out);
unlink $gp if (-e $gp);
exit;
