#!/usr/bin/perl
#$Id: get_impedance_data,v 1.4 2012/10/03 11:19:26 sofc Exp $
use warnings;
use strict;
use RFC::Rig;
use RFC::Main;
use RFC::Header;
use SemaforeFile;
use AFM qw ();
use Carp;
use File::Copy;
my $VERSION = 2.0.1;
my $PROGRAM = 'get_impedance_data';

my $debug = 0;
my $showall = 0;
for my $string (@ARGV)
{
    if ($string =~ /--version/)
    {
        warn "$PROGRAM is: $VERSION\n";
        exit 0;
    }
    if ($string =~ /--debug/)
    {
        $debug = 1;
    }
    if ($string =~ /--verbose/)
    {
	$showall = 1;
    } 
}

my $r = RFC::Rig->new(shift);
$r->check_run();
my $rig = $r->name;

my $testno = $r->session();;
if ( @ARGV )
{
    my $ttestno = shift;
    $ttestno =~ /(\d+)/;
    $testno = $1;
}

my $impdir = $RFC::Header::publicdir.'rig'.$rig.'/'.$rig.'test'.$testno.'/impedance/';
my $jdata = $impdir;
$jdata =~ s/impedance\//jdata/;
my $jdfile = SemaforeFile->new($jdata);
my $impdata = $impdir.'imp_data';
my $impj = $impdir.'imp_jdata';
opendir MYDIR,$impdir or die "Could not open dir $impdir $!";
my @list = grep(/i2b$/i,readdir(MYDIR));
closedir(MYDIR);
if (scalar(@list) < 1)
{
    exit;
}
my @jdata = $jdfile->readlines();
my @gasses = ('h2','o2','ch4','air','backup'); ## DEFAULT ####
my $gstr = &AFM::get_usercv_test($rig,$testno,'report','gas_names_ivtable');
$gstr = &AFM::get_usercv($rig,'report','gas_names_ivtable') unless ($gstr);
my $currentlabel = &AFM::get_usercv_test($rig,$testno,'IV_control','current_label');
my $voltlabel = &AFM::get_usercv_test($rig,$testno,'IV_control','voltage_label');
$currentlabel = 'current' unless ($currentlabel); ## Default value for backwards compatibility ###
$voltlabel = 'cell_voltage' unless ($voltlabel);  ## Default value for backwards compatibility ###
my $templabel = &AFM::get_usercv_test($rig,$testno,'IV_control','temp_label');
$templabel = 'T_center' unless ($templabel);
@gasses = split(/\s*\,\s*/,$gstr) if ($gstr);
my @relaylist = ();
my $relstr = &AFM::get_usercv_test($rig,$testno,'report','relay_names_ivtable');
@relaylist = split(/\s*\,\s*/,$relstr) if ($relstr);



my $cstr=" sort -n | awk \'{\$1=\"\";print}\'";
my $file2 = $impdata . '.sort';
my $file3 = $impj . '.sort';
open(SORTS, "| $cstr > $file2");
open(SORTSJ, "| $cstr > $file3");

for my $file (@list)
{
    my $rs = 0;
    my $rp = 0;
    my $rtot = 0;
    my $time = 0;
    my $temp = 0;
    my $H2 = -1;
    my $Air = -1;
    my $CH4 = -1;
    my $backup = -1;
    my $O2 = -1;
    my $volt = 0;
    my $current = 0;
    my $filetimest = '';
    my $f = SemaforeFile->new($impdir.$file);
    my @res = $f->readlines();
    my $mode = 0;
    my @dataline = ();
    for my $line (@res)
    {
	if ($line =~ /^\s*\d+\s+\w+\s+\d+\s+[\d\:]+\s*$/)
	{
	    $line = &convert($line);
	}
	if ($line =~ /^:*\d+:/)
	{
	    if ($line =~ /^:*\d+:\d+:\d+:\d+:\d+:\d+/)
	    {
		$line =~ /^:*(\d+):(\d+):(\d+):(\d+):(\d+):(\d+)/;
		my $yyyy = $1;
		my $mo = &my_add_zero($2+0);
		my $dd = &my_add_zero($3+0);
		my $hh = &my_add_zero($4+0);
		my $mm = &my_add_zero($5+0);
		my $ss = &my_add_zero($6+0);
		$filetimest = $yyyy.$mo.$dd.$hh.$mm.$ss;
	    }
	    else
	    {
		$line =~ /^:*(\d+):(\d+):(\d+):(\d+):(\d+)/;
		my $yyyy = $1;
		my $mo = &my_add_zero($2+0);
		my $dd = &my_add_zero($3+0);
		my $hh = &my_add_zero($4+0);
		my $mm = &my_add_zero($5+0);
		my $ss = '00';
		$filetimest = $yyyy.$mo.$dd.$hh.$mm.$ss;
	    }
	}
	if (($mode) &&($line !~ /\s*[\d\.eE\+\-]+\s+[\d\.\-\+eE]+\s+[\-\d\.\+eE]+\s*/))
	{
	    $mode = 0;
	}
	if ($mode)
	{
	    push @dataline, $line;
	}
	if ($line =~ /^\s*\d+\s*$/)
	{
	    $mode = 1;
	}
    }
    my $rcount = 1;
    while (($rtot == 0) && ($rcount < scalar(@dataline)))
    {
	if ($dataline[scalar(@dataline)-$rcount] =~ /\s*[\d\.\+\-eE]+\s+([\-\d\.\+eE]+)/)
	{
	    $rtot = $1+0;
	}
	$rcount++; 
    }
    my $oldZr = 0;
    my $oldZi = 0;
    my $Zr = 0;
    my $Zi = 0;
    my $found = 0;
    if ($dataline[0] && $dataline[0] =~ /\s*[\d\.\+\-eE]+\s+([\d\-\.\+eE]+)\s+([\-\.\d\+eE]+)/)
    {
	$rs = $1;
    }
    print $filetimest,"\n" if ($debug);
    my $notfound = 1;
    my $jdat = '';
    my %flow = ();
    for (my $x = 0; $x < scalar(@jdata);$x++)
    {
	if ($notfound)
	{
	    $jdata[$x] =~ /\s+(\d+):(\d+):(\d+):(\d+):(\d+):(\d+)\s+/;
	    my $jdatatid = $1.$2.$3.$4.$5.$6;
	    if ($jdatatid > $filetimest)
	    {
		print $jdata[$x] if ($debug);
		$jdata[$x] =~ /^([\d\.]+)/;
		$time = $1;
		$time = sprintf("%.2f",$time);
		if ($jdata[$x] =~ /\s+$templabel\s+([\d\.\-eE\+]+)/)
		{
		    $temp = $1;
		}
		else
		{
		    $temp = ' ';
		}
		$temp = sprintf("%.5g",$temp) if ($temp =~/\d/);
		for my $gas (@gasses)
		{
                    if ($jdata[$x] =~ /\s+$gas\s+([\d\.\-eE\+]+)/)
                    {
                        my $flow = $1;
                        $flow = 0 if ($flow < 0);
                        $flow{$gas} = sprintf("%.1f",$flow);
                    }
                }
		for my $gas (@relaylist)
		{
                    if ($jdata[$x] =~ /\s+$gas\s+([\d\.\-eE\+]+)/)
                    {
                        my $flow = $1;
                        $flow = 0 if ($flow < 0);
                        $flow{$gas} = sprintf("%i",$flow);
                    }
                }
		if ($jdata[$x] =~ /\s+$voltlabel\s+([\d\.\-\+eE]+)/i)
		{
		    $volt = $1;
		}
		else
		{
		    $volt = ' ';
		}
		$volt = sprintf("%.2f",$volt) if ($volt =~ /\d/);
		if ($jdata[$x] =~ /\s+$currentlabel\s+([\d\.\-eE\+]+)/)
		{
		    $current = $1+0;
		    if (($current < 0.1) && ($current > -0.1)) {$current = 0};
		    $current = sprintf("%.2f",$current);
		}
		else
		{
		    $current = ' ';
		}
                if ($debug)
                {
                    print "temp: $temp";
                    for my $gas (@gasses,@relaylist)
                    {
                        print "   $gas: $flow{$gas}";
                    }
                    print "  $voltlabel $volt  $currentlabel $current\n" if ($debug);
                }
                $notfound = 0;
                $jdat = $jdata[$x];
	    }
	}
    }
    my $bfclname = $file;
    chomp $bfclname;
    chomp $jdat;
    $rp = $rtot-$rs;
    $rs = sprintf("%.4g",$rs);
    $rp = sprintf("%.4g",$rp);
    $bfclname =~ s/.*\/impedance\///;
    my $outputst = "$time  $bfclname  Time:$time  ".ucfirst($templabel).":$temp  ".ucfirst($voltlabel).":$volt";
    for my $gas (@gasses,@relaylist)
    {
	$flow{$gas} = '-1' unless defined($flow{$gas});
        $outputst.= "   $gas:$flow{$gas}";
    }
    $outputst .= "  ".ucfirst($currentlabel).":$current  Rs:$rs   Rp:$rp";
    print SORTSJ $time,' ',$bfclname,' ',$jdat,"\n";
    print SORTS $outputst,"\n" unless ($showall);
    print SORTS $outputst,'  \#\#\#  ',$jdat,"\n" if ($showall); 
}
close(SORTS); 
close(SORTSJ);
copy($file2,$impdata) or die "Could not copy file $file2 to $impdata $!\n";
copy($file3,$impj) or die "Could not copy file $file3 to $impj $!\n";
unlink($file2);
unlink($file3);
exit; 




sub my_add_zero($)
### Function which adds leading zerros if the input number is ####
### less than 10                                              ####
{
    my $number = $_[0];
    if ($number < 10)
    {
	$number = join('','0',$number);
    };
    return $number;
}

sub convert()
{
    my $input = $_[0];
    $input =~ /^\s*(\d+)\s+(\w+)\s+(\d+)\s+([\d\:]+)/;
    my $day = $1;
    my $m = $2;
    my $year = $3;
    my $time = $4;
    if ($m =~ /jan/i) {$m = 1};
    if ($m =~ /feb/i) {$m = 2};
    if ($m =~ /mar/i) {$m = 3};
    if ($m =~ /apr/i) {$m = 4};
    if ($m =~ /may/i) {$m = 5};
    if ($m =~ /jun/i) {$m = 6};
    if ($m =~ /jul/i) {$m = 7};
    if ($m =~ /aug/i) {$m = 8};
    if ($m =~ /sep/i) {$m = 9};
    if ($m =~ /okt/i) {$m = 10};
    if ($m =~ /nov/i) {$m = 11};
    if ($m =~ /dec/i) {$m = 12};
    my $res = ":$year:$m:$day:$time";
    $res =~ s/:0/:/g;
    return $res;  
}
