#!/usr/bin/perl -T
#$Id: util.cgi,v 1.2 2011/01/13 13:57:10 sofc Exp $
use strict;
use warnings;
use RFC::Main;
use RFC::RFCCGI qw(:cgi :html);
use RFC::Header;
use CGI qw(:standard :netscape);
my @gasses = ('Ar','CO2','CO','CH4','O2','H2','H2O');  #### Used for ch4 ###

if (!defined(param))
{
    &print_header("Please log in to the $name");
    print '<center>';
    RFC::RFCCGI::login();
    print '</center>';
    &print_end;
}
else
{
    if (&login_ok())
    {	
	print_header("Cell test utilities");
	print RFC_start_html(-title=>"Cell test utilities", -style=>{src=>'/celltest/RFCcontrol.css'});
        top_nav_bar_start;
        top_no_button;
        top_no_button;
        top_no_button;
        tab_newrow;
        &js_back();
        top_js_return('#006600','white');
        top_nav_bar_button('','ch4','','Calculate Emf with ch4','s6');
        top_nav_bar_button('','comp','','Impedance compensation','s3');
        top_nav_bar_button('','fu','','Fuelf utilisation correction','s5');
        top_nav_bar_button('main.cgi','','','To menu','s4');
        end_top_bar;	
	param(-name=>'action',-value=>'') unless (param('action'));
        $_ = param('action');
      CASE:
        {
            ### Insert case statements ###
	    /^ch4$/ and do {&ch4; last CASE;};
	    /^calc_ch4$/ and do {&calc_ch4; last CASE;};
	    /^fu$/ and do {&fu; &end_fu; last CASE;};
	    /^calc_fu$/ and do {&fu; &calc_fu; &end_fu; last CASE;};
	    /^comp/ and do {&comp; last CASE;};
	    /^pO2/ and do {&pO2; last CASE;};
            ### Default response ####
            &main;
        }
        print end_html;
    }		
    else	
    {   
	&not_auth;
    }
}
exit;

sub main
{
    &fu();
    &end_fu();
}


sub fu
{
    print start_form(-name=>'fu');
    &action('calc_fu');
    print '<table border="0px" class="tabel">';
    print '<tr style="height:1px;">';
    print '<td width="10%"></td>';
    print '<td width="15%"></td>';
    print '<td width="7%"></td>';
    print '<td width="8%"></td>';
    print '<td width="15%"></td>';
    print '<td width="7%"></td>';
    print '<td width="8%"></td>';
    print '<td width="15%"></td>';
    print '<td width="7%"></td>';
    print '<td width="8%"></td>',"\n";
    print '</tr><tr><td colspan=10 class=heading height=50>';
    print 'Calculation of fuel utilisation correction of cell resistance';
    print '</td></tr>';
    print '<tr><td colspan=10 class=heading height=40>';
    print 'Anode gas composition:';
    print '</td></tr>';
    &gasrow('h2','24','ch4','0','o2','0');
    &gasrow('co','0','co2','0','n2','0');
    &gasrow('nh3','0');
    print '<tr><th></th><th>Water enabled</th><td>';
    print checkbox(-name=>'enabled',-label=>'',-value=>'1',-checked=>'1',-onchange=>'change_water("enabled","water")');
    print '</td><td></td><th>Water temp</th><td>';
    print textfield(-name=>'water',-value=>'30',-class=>'textfield');
    print '</td><th>C</th></tr>';
    print '<tr><td colspan=10 class=heading height=40>';
    print 'Cathode gas composition:';
    print '</td></tr>';
    &gasrow('air','140','o2_cathode','0','n2_cathode','0');
    print '</tr><tr><td colspan=10 class=heading height=40>';
    print 'Other parameters';
    print '</td></tr>';
    &row('current',16,'A','cell area','16','cm<sup><small>2</small></sup>','segments',20,'');
    &row('temperature',850,'C','pO2 in',1070,'mV','pO2 temp','850','C');
    print '<tr><th>';
    print '</th><th allign=right>';
    print ucfirst("Cell voltage : ");
    print '</th><td>';
    print textfield(-name=>'U',-value=>600,-class=>'textfield');
    print '</td><th>';
    print 'mV';
    print '</th><th allign=right>';
    print ucfirst("Open circuit voltage : ");
    print '</th><td>';
    print textfield(-name=>'emf',-value=>1056,-class=>'textfield');
    print '</td><th>';
    print 'mV';
    print '</th><th>';
    print 'Use measured OCV:';
    print '</th><td>';
    print checkbox(-name=>'useemf',-label=>'',-checked=>'1',-value=>'1',-onchange=>'change_water("useemf","emf")');
    print '</td></tr>';
}

sub end_fu
{
    print '<tr><td colspan=10 height=10></td></tr>';
    print '<tr><td colspan=4></td><td colspan=2>';
    &print_hidden();
    print submit(-class=>'s3',-name=>'action',-value=>'Calculate',-style=>'width:100;');
    print '</table>';
    print end_form();
}

sub row()
{
    print '<tr><th>';
    while (@_)
    {
        my $id = shift;
        my $val = shift;
        my $unit = shift;
        print '</th><th allign=right>';
        my $label = ucfirst($id);
        $label =~ s/(\d+)/<sub><small>$1<\/small><\/sub>/g;
        print $label,' : ';
        print '</th><td>';
        print textfield(-name=>$id,-value=>$val,-class=>'textfield');
        print '</td><th>';
        print $unit;
    }
    print '</th></tr>';
}

sub outrow()
{
    print '<tr><th>';
    while (@_)
    {
        my $id = shift;
        my $val = shift;
        my $unit = shift;
        print '</th><th allign=right>';
        my $label = ucfirst($id);
        $label =~ s/(\d+)/<sub><small>$1<\/small><\/sub>/g;
        print $label,' : ';
        print '</th><th>';
        print $val;
        print '</th><th>';
        print $unit;
    }
    print '</th></tr>';
}

sub gasrow()
{
    print '<tr><th>';
    while (@_)
    {
        my $id = shift;
        my $val = shift;
        print '</th><th align=right>';
        my $label = uc($id);
        $label =~ s/(\d+)/<sub><small>$1<\/small><\/sub>/g;
        print $label,' : ';
        print '</th><td>';
        print textfield(-name=>$id,-value=>$val,-class=>'textfield');
        print '</td><th>';
        print 'L/hour';
    }
    print '</th></tr>';
}



sub calc_ch4
{
    my $cstr = '/usr/local/bin/ch4_args.pl --command par_all';
    my %input = &get_input;
    my %out = ();
    if ($input{'cell'} > 1200)
    {
        print h2({-class=>'alert'},"Temperature above 1200C entered, setting temperature to 1200C.");
        $input{'cell'} = 1200;
    }
    if ($input{'cell'} < 300)
    {
        print h2({-class=>'alert'},"Temperature below 300C entered, setting temperature to 300C.");
        $input{'cell'} = 300;
    }
    for my $key (sort keys %input)
    {
        $cstr = $cstr . ' --'.$key. ' '.$input{$key};
    }
    my $result = '';
    my @res = `$cstr`;
    $out{'temp'} = $input{'cell'};
    $out{'P'} = $input{'P'};
    $res[6] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'H2'} = $1;
    $res[7] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'H2O'} = $1;
    $res[3] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'CH4'} = $1;
    $res[5] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'CO2'} = $1;
    $res[4] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'CO'} = $1;
    $res[8] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'O2'} = $1;
    $res[2] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'C_a'} = $1;
    $res[0] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'OCV'} = $1;
    $res[1] =~ /\s+([\-\.\deE\-\+]+)/;
    $out{'OCV_O2'} = $1;
    $out{'Ar'} = 0;
    my $total = 0;
    for my $gas (@gasses)
    {
        $total += $out{$gas};
    }
    $out{'Ar'} = 1 - $total;
    print '<center>';
    print start_form;
    &action('ch4');
    print h2('Calculation resulted in the following gas partial pressures:');
    print '<CENTER><TABLE BORDER=0 CELLPADDING=0 CELLSPACING=10><TR VALIGN=TOP><TH>';
    print ' Input mole fractions </TH><TH> Eqlibrium partial pressures </TH></TR><TR><TH>';
    print '<CENTER><TABLE BORDER=0 CELLPADDING=0 CELLSPACING=5><TR ALIGN=CENTER VALIGN=CENTER><TH>';
    print 'Gas </TH><TH> mole fraction </TH></TR>';
    for my $gas (@gasses)
    {
        print '<TR><TH> '.$gas.' </TH><TH>'.textfield(-name=>$gas,-value=>'0.1',-size=>'8',-force=>'0') .'</TH></TR>';
    }
    print '</TABLE></CENTER>';
    print '</TH><TH>';
    print '<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=5><TR ALIGN=CENTER VALIGN=CENTER><TH>';
    print 'Gas </TH><TH> Partial pressures </TH></TR>';
    for my $gas (@gasses)
    {
        print '<TR><TH> '.$gas.' </TH><TH>'.textfield(-name=>"out$gas",-value=>sprintf("%.4e",$out{$gas}),-size=>'14',-force=>'1') .'</TH></TR>';
    }
    print '</TABLE>';
    print '</TH></TR>';
    print '</TABLE></CENTER>';
    print h3("$input{'calc'} was used to add the mole fractions up to 1!");
    print h3("The oxygen potential versus air and pure oxygen for the gas at $out{'temp'} C and $out{'P'} atm is:");
    print '<CENTER><TABLE BORDER=0 CELLPADDING=0 CELLSPACING=5><TR ALIGN=CENTER VALIGN=CENTER><TH>';
    print ' versus air: </TH><TH> versus oxygen: </TH><TH> Carbon activity </TH></TR>';
    print '</TR><TH> '.$out{'OCV'}.' mV </TH><TH> '.$out{'OCV_O2'}.' mV </TH><TH> '.$out{'C_a'}.'</TH></TR>';
    print '</TABLE></CENTER>';
    print hidden(-name=>'cell',-vlaue=>'1000',-force=>'0');
    print hidden(-name=>'P',-value=>'1',-force=>'0');
    print_hidden();
    print submit(-class=>'s3',-name=>'action',-value=>'ok',-style=>'width:300px;');
    print end_form;
    print '</center>';
}

sub get_input
{
    my %temp = ();
    for my $gas (@gasses)
    {
        if (defined(param($gas)))
        {
            my $test = param($gas);
            $test =~ /([\d\.]+)/;
            $temp{$gas} = $1;
        }
        ### Make sure that all gasses return a defined value ###
        $temp{$gas} = 0 unless ($temp{$gas});
    }
    if (defined(param('calc')))
    {
        my $test = param('calc');
        $test =~ /([\w]+)/;
        $temp{'calc'} = $1;
    }
    if (defined(param('P')))
    {
        my $test = param('P');
        $test =~ /([\d\.]+)/;
        $temp{'P'} = $1;
    }
    if (defined(param('cell')))
    {
        my $test = param('cell');
        $test =~ /([\d\.]+)/;
        $temp{'cell'} = $1;
    }
    return %temp;
}

sub ch4
{
    print start_form;
    print_hidden();
    &action('calc_ch4');
    print '<CENTER><TABLE BORDER=0 CELLPADDING=0 CELLSPACING=5><TR ALIGN=CENTER VALIGN=CENTER><TH>';
    print 'Gas </TH><TH> mole fraction </TH></TR>';
    for my $gas (@gasses)
    {
        print '<TR><TH> '.$gas.' </TH><TH>'.textfield(-name=>$gas,-value=>'0.1',-size=>'8',-force=>'0') .'</TH></TR>';
    }
    print '<TR><TH> Rest gas </TH><TH>'.popup_menu(-name=>'calc',-values=>[@gasses],-default=>$gasses[0],-force=>'0').'</TH></TR>';
    print '<TR><TH> Temperature (C) </TH><TH>'.textfield(-name=>'cell',-value=>'850',-size=>'8',-force=>'0') .'</TH></TR>';
    print '<TR><TH> Pressure (atm) </TH><TH>'.textfield(-name=>'P',-value=>'1',-size=>'8',-force=>'0') .'</TH></TR>';
    print '</TABLE></CENTER>';
    print p({-class=>'C'},'Use rest gas if the mole fractions do not themselves add up to 1');
    print p({-class=>'C'},'It is advisable to use Argon for this as it is an inert gas.');
    print center(h2({-class=>'alert'},'Remember that mole fractions must not add up to more than one!'));
    print center(submit(-class=>'s3',-name=>'action',-value=>'calculate emf',-style=>'width:300px;'));
    print end_form;
}

sub pO2
{
    my @list = `/bin/ls -1 /home/http/html/tmp`;
    foreach (@list)
    {
        my $f = '/home/http/html/tmp/'.$_;
        if ($f =~ /([\w\.\/]+)/)
        {
            unlink $1;
        }
    }
    my $temp = 1000;
    $temp = param('temp') if (defined(param('temp')));
    my $data = '';
    $data = param('data') if (defined(param('data')));
    my $mode = undef;
    $mode = param('mode') if (defined(param('mode')));
    $data = "8       270     0.4\n16      278.6   0.4\n24      285     0.45\n32      294     0.4\n48      296     0.4\n56      297.6   0.4\n" unless ($data);
    my $f = '/tmp/po2_public_'.$$.'.txt';
    open MYOUT,'>',$f or die "Could not open file $f for writing $!\n";
    print MYOUT $temp,"\n";
    chomp $data;
    chomp $data;
    print MYOUT $data,"\n";
    close MYOUT;
    my @fs = `/usr/local/bin/check_monitor.pl $f`;
    unlink $f if (-e $f);
    print center(h1('pO2 monitor callibration'));
    print start_form(-name=>'pO2');
    &action('pO2');
    print '<table border="0px" class="tabel" width="100%">';
    print '<tr style="height:1px;">';
    print '<td width="5%"></td>';
    print '<td width="30%"></td>';
    print '<td width="5%"></td>';
    print '<td width="5%"></td>';
    print '<td width="60%"></td>';
    print '<td width="5%"></td>';
    print '</tr>';
    print '<tr><td></td><th> Temperature: ',textfield(-name=>'temp',-value=>'1000'),' C';
    print '</th><td colspan=2></td><th rowspan=3>';
    foreach (@fs)
    {
        /\/([\w\.\-]+)$/;
        my $img = '/tmp/'.$1;
        print '<img src="'.$img.'">';
    }
    print '<tr><td></td><th>';
    print 'Data <br>(tabulator separated, Gas flow, emf(N2), emf(air))';
    print '</th><td colspan=2></td><th>';
    print '</th></tr>',"\n";
    print '<tr><td></td><th>';
    print textarea(-name=>'data',-value=>$data,-force=>'1',-class=>'textfield',-wrap=>'off',-rows=>'25');

    print '</th></tr>',"\n";
    print '<tr><td></td><th>';
#    print 'Plot mode: ';
#    print radio_group(-name=>'mode',-values=>['Emf (mV)','pO2 (ppm)'],-default=>'pO2 (ppm)');
    print '</th><td colspan=2></td><td>';
    print_hidden();
    print submit(-class=>'s3',-name=>'test',-value=>'Calculate',-style=>'width:300px;');
    print '</table>';
    print end_form();
}


sub comp
{
    my $mdata = '';
    $mdata = param('measure') if (defined(param('measure')));
    my $cdata = '';
    $cdata = param('compensation') if (defined(param('compensation')));
    my $mode = undef;
    $mode = param('mode') if (defined(param('mode')));
    $mdata = &calc_comp($mode,$cdata,$mdata);
    print center(h1('Impedance compensation'));
    print center(p("Compensated file is returned in the 'measure file' field facilitating easy multiple compensation"));
    print start_form(-name=>'comp');
    &action('comp');
    print '<table border="0px" class="tabel" width="100%">';
    print '<tr style="height:1px;">';
    print '<td width="5%"></td>';
    print '<td width="40%"></td>';
    print '<td width="5%"></td>';
    print '<td width="5%"></td>';
    print '<td width="40%"></td>';
    print '<td width="5%"></td>';
    print '</tr>';
    print '<tr><td></td><th>';
    print 'Measure file (i2b format!)';
    print '</th><td colspan=2></td><th>';
    print 'Compensation file (i2b format!)';
    print '</th></tr>',"\n";
    print '<tr><td></td><th>';
    print textarea(-name=>'measure',-value=>$mdata,-force=>'1',-class=>'textfield',-wrap=>'off',-rows=>'25');
    print '</th><td colspan=2></td><th>';
    print textarea(-name=>'compensation',-value=>'',-force=>'1',-class=>'textfield',-wrap=>'off',-rows=>'25');
    print '</th></tr>',"\n";
    print '<tr><td></td><th>';
    print 'Compensation mode: ';
    print radio_group(-name=>'mode',-values=>['Add','Subtract','Multiply','Divide'],-default=>'Add');
    print '</th><td colspan=2></td><td>';
    print_hidden();
    print submit(-class=>'s3',-name=>'test',-value=>'Calculate',-style=>'width:150;');
    print '</table>';
    print end_form();
    print center(h3({-class=>'Alert'},"Note that the measure file and the compensation file must be measured at the same frequencies!"));
}

sub calc_comp($$$)
{
    my $mode = shift;
    my $comp = shift;
    my $data = shift;
    return '' unless ($data) && ($comp) && ($mode);     ### Retrun if no imput is given ###
    my $m = '';
    $m = 'A' if ($mode =~ /Add/);
    $m = 'S' if ($mode =~ /Subtract/);
    $m = 'M' if ($mode =~ /Multiply/);
    $m = 'D' if ($mode =~ /Divide/);
    #### Set file names and command string ###
    my $dir = '/tmp/';
    my $datafile = $dir.$$.'data.i2b';
    my $outfile = $dir.$$.'data_cor.i2b';
    my $compfile = $dir.$$.'comp.i2b';
    my $cmd = &get_cv('impedance','comp_program').' -'.$m.' '.$compfile.' '.$datafile;
    eval {
        open MYOUT,'>',$datafile or die "Could not open file $datafile for writing!";
        print MYOUT $data;
        close MYOUT;
        open MYOUT,'>',$compfile or die "Could not open file $compfile for writing!";
        print MYOUT $comp;
        close MYOUT;
        ### Det default error if failed compensation ###
        $data = 'Compensation Failed!';
        ### call hio_korr to do compensation ###
        system($cmd);
        if (-e $outfile)
        {
            open MYIN,'<',$outfile or die "Could not open file $outfile!";
            my @dat = <MYIN>;
            close MYIN;
            $data = join('',@dat);
        }
        ### Cleanup after use ###
        unlink $datafile if (-e $datafile);
        unlink $compfile if (-e $compfile);
        unlink $outfile if (-e $outfile);
    };
    &errorlog($@) if ($@);
    return $data;
}

sub calc_fu
{
    #### Get input values for gasses  ####
    my @gaslst = ('h2','co','co2','ch4','o2','nh3','n2','air','o2_cathode','n2_cathode');
    my %i = ();
    for my $gas (@gaslst)
    {
        $i{$gas} = 0;
        $i{$gas} = param($gas) if (defined(param($gas)));
        $i{$gas} =~ /([\w\.\+\-]*)/;
        $i{$gas} = $1;
    }
    my $use_ch4 = '';
    $use_ch4 = ' --use_ch4 YES' if ($i{'co'} || $i{'co2'} || $i{'ch4'});
    #### Get input values for NON-gasses  ####
    for my $gas ('current','cell area','segments','temperature','pO2 in','pO2 temp','U','emf','water','enabled','useemf')
    {
        $i{$gas} = 0;
        $i{$gas} = param($gas) if (defined(param($gas)));
        $i{$gas} =~ /([\w\.\+\-]*)/;
        $i{$gas} = $1;
    }
    ### Generate command string for use with OCV_corr ####
    my $emf = ' --emf '.-$i{'emf'}/1000;
    my $u = ' --U '.-$i{'U'}/1000;
    my $cmd = '/usr/local/bin/OCV_corr --command par_all --Air 0 --A '.$i{'cell area'};
    my $h2 = $i{'h2'};
    my $o2 = $i{'o2'};
    my $ch4 = $i{'ch4'};
    my $co = $i{'co'};
    my $co2 = $i{'co2'};
    #### Calculate anode gas flow and composition ###
    if ($use_ch4)
    {
        #### Convert to simulate internally reformed methane ####
        #### if carbon containing gasses are used            ####
        $cmd .= $use_ch4;
        $cmd .= ' --CH4 '.$ch4;
        $cmd .= ' --CO '.$co;
        $cmd .= ' --CO2 '.$co2;
    }
    $h2 += $i{'nh3'} * 3 / 2;
    my $n2 = $i{'n2'} + $i{'nh3'}/2;
    $cmd .= ' --O2_add '.$o2;
    $cmd .= ' --H2 '.$h2;
    $cmd .= ' --N2 '.$n2;
    ### Calculate cathode gas flow and composition ###
    $o2 = $i{'air'}*0.21;
    $n2 = $i{'air'}*(1-0.21);
    $o2 += $i{'o2_cathode'};
    $n2 += $i{'n2_cathode'};
    $cmd .= ' --O2_cathode '. $o2;
    $cmd .= ' --N2_cathode '.$n2;
    ### Set rest of options ###
    $cmd .= ' --I '.$i{'current'};
    $cmd .= $u;
    if ($i{'enabled'})
    {
        $cmd .= ' --water '.$i{'water'};
    }
    else
    {
        $cmd .= ' --dry 1';
    }
    $cmd .= ' --N '.$i{'segments'};
    my $po2cmd = $cmd;
    $cmd .= $emf if ($i{'useemf'});
    $cmd .= ' --cell '.$i{'temperature'};
    $po2cmd .= ' --emf '.$i{'pO2 in'}/(-1000);
    $po2cmd .= ' --cell '.$i{'pO2 temp'};
    my @res = ();
    eval {
        #### Run calculation ###
        @res = `$cmd`;
        my %out = ();
        #### Get result into hash ###
        for my $l (@res)
        {
            my ($key,$val) = split(/[\s\t]+/,$l);
            $out{$key} = $val;
            #### Preformat output numbers #####
            $out{$key} = sprintf("%.4f",$val) if ($val =~ /\d+/);
            $out{$key} = sprintf("%.5f",$val) if (($key =~ /leak/i) || ($key =~ /xh2/i)) && ($val =~ /\d+/);
        }
        if ($out{'ASR_corr'} == -32768)
        {
            print h1({-class=>'Alert'},"Undefined cell resistance, likly reason: mismatch between gas and current!");
        }
        ### Print output ###
        print '<tr><td colspan=10 class=heading height=40>';
        print 'Result of calculation based on above parameters:';
        print '</td></tr>';
        &outrow('Secant resistance',$out{'R_secant'},'&Omega;cm<sup><small>2</small></sup>','Corrected resistance',$out{'ASR_corr'},'&Omega;cm<sup><small>2</small></sup>')
	    ;
        &outrow('Efficiency',$out{'Efficiency'},'','Cell power',$out{'Power'},'W/cm<sup><small>2</small></sup>');
        &outrow('Theoretical OCV',-1*$out{'OCV_theory'},'V','Measured OCV',-1*$out{'OCV_measure'},'V','Emf of gas after cell',-1*$out{'OCV_after_cell'},'V');
        my $leak = $out{'Oxygen_leak'}*100;
        $leak = 'NA' if ($out{'Oxygen_leak'} =~ /NA/i);
        &outrow('Gas leak',$leak,'%','Fuel utilisation (cell)',$out{'FU_cell'}*100,'%','Oxygen utilisation (cell)',$out{'OxygenUtil'}*100,'%');
        print '<tr><th colspan=10 style="text-align:center;">';
        my $str = 'Reported water mole fractions assumes only H2 and H2O in anode gas! Only works correctly with air on cathode if CO, CO2 or CH4 is used!';
        $str =~ s/(\d+)/<sub><small>$1<\/small><\/sub>/g;
        print $str;
        print '</th></tr>';
        &outrow('Theoretical xH2O in',$out{'xH2O_in_theory'},'','Measured xH2O in',$out{'xH2O_in_measure'},'','Output xH2O',$out{'xH2O_out'},'');
        ### Run calculation for pO2 in ###
        @res = `$po2cmd`;
        %out = ();
        #### Get result into hash ###
        for my $l (@res)
        {
            my ($key,$val) = split(/[\s\t]+/,$l);
            $out{$key} = $val;
            #### Preformat output numbers #####
            $out{$key} = sprintf("%.4f",$val) if ($val =~ /\d+/);
            $out{$key} = sprintf("%.5f",$val) if (($key =~ /leak/i) || ($key =~ /xh2/i)) && ($val =~ /\d+/);
        }
        if ($out{'ASR_corr'} == -32768)
        {
            print h1({-class=>'Alert'},"Undefined cell resistance, likly reason: mismatch between gas and current!");
        }
        print '<tr><th colspan=10 style="text-align:center;">';
        print 'Calculations for pO2:';
        print '</th></tr>';
        $leak = $out{'Oxygen_leak'}*100;
        $leak = 'NA' if ($out{'Oxygen_leak'} =~ /NA/i);
        &outrow('Gas leak',$leak,'%','Measured pO2 in',-1*$out{'OCV_measure'},'V','Measured xH2O in',$out{'xH2O_in_measure'});
    };
    if ($@)
    {
        #### Catch errors ###
        print h1({-class=>'Alert'},"$@");
    }
}
