#! /usr/bin/perl
# $Id: ASR.pl,v 1.1 2006/03/28 08:10:40 skoch Exp $

### This script calculates the area specific resistance corrected
### for fuel utiliszation using OCV_corr and the last measured data 
### for the input rig. The script uses the theoretical OCV based on
### the water temperature and gas flows.

use AFM;
use strict;
use warnings;
my $VERSION = 0.1;
my $PROGRAM = 'ASR.pl';
if (scalar(@ARGV) > 0)
{
    for(my $x = 0; $x < scalar(@ARGV);$x++)
    {
	if ($ARGV[$x] =~ /--version/)
	{
	    print "$PROGRAM is: $VERSION\n";
	    exit 0;
	}
    } 
}

if (scalar(@ARGV) < 1)
{
    exit 0;
}
my $trig = $ARGV[0];
$trig =~ /(\d+)/;
my $rig = $1;
$rig += 0;
if (!&AFM::check_rig_nr($rig))
{
    die "$rig is not a valid rig number!\n";
} 
my $test = &AFM::get_test_nr($rig);
my $file = '/home/rig'.$rig.'/'.$rig.'test'.$test.'/raadata.';
my @date = &AFM::get_time('now');
my $string = '';
for (my $x = 0; $x < 2;$x++)
{
    $string = $string.&AFM::add_zero($date[$x]).':';
}
$string = $string.&AFM::add_zero($date[2]);
$file = $file . $string;
$string = `tail -n 1 $file`;
exit unless ($string);
my %d = &split_data($string);
my @input = ('T_center','bottle_temp','air','h2','o2','current','cell_voltage');
my @icommand = ('--cell','--water','--O2flow','--H2flow','--O2_add','--I','--U');
my $out = '/usr/local/bin/OCV_corr --command ASR ';
for (my $x = 0; $x < scalar(@input);$x++)
{
    $d{$input[$x]} = 0 if (($d{$input[$x]}) && ($input[$x] eq 'o2') && ($d{$input[$x]} < 1));
    $d{$input[$x]} *= -1 if (($d{$input[$x]}) && ($input[$x] eq 'cell_voltage'));
    $out = $out . " $icommand[$x] $d{$input[$x]}" if ($d{$input[$x]});
}
my $area = &get_usercv($rig,'main','cell_area');
$out = $out . ' --A '.$area;
$out = `$out`;
print $out; 



sub split_data($)
{
    my $data = shift;
    my %res = ();
    my @l = split(/\s+/,$data);
    for (my $x = 0; $x < @l; $x+=2)
    {
	$res{$l[$x]} = $l[$x+1]; 
    }
    return %res;
}
