#!/usr/bin/perl
# $Id: degradation_rate,v 1.1 2006/03/28 13:20:05 skoch Exp $
use AFM;
use strict;
use warnings;
my $PROGRAM = 'degradation_rate';

my $deltat = 2;

if (scalar(@ARGV) < 4)
{
    warn "Usage: $PROGRAM \$rig \$test \$start_time \$end_time\n";
    warn "Where \$start_time and \$end_time is in hours after the test began\n";
    die "\n";
}
my $rig = $ARGV[0]+0;
if (!&AFM::check_rig_nr($rig))
{
    die "Wrong rig $rig !!\n";
}
my $test = $ARGV[1];
$test =~ /(\d+)/;
$test = $1+0;
if (($test < 1) || ($test > &AFM::get_test_nr($rig)))
{
    die "Illegal test nr: $test!!\n";
}
my $startt = $ARGV[2];
my $endt = $ARGV[3];
$startt =~ /([\d.]+)/; 
$startt= $1+0;
$endt =~ /([\d\.]+)/; 
$endt = $1+0;

my $jdata = $AFM::publicdir.'rig'.$rig.'/'.$rig.'test'.$test.'/jdata';

my $trueend = `/usr/bin/tail -1 $jdata`;
$trueend =~ /^\s*([\d\.]+)/;
$trueend = $1+0;

if (($startt >= $endt) || ($endt > $trueend))
{
    die "Wrong times, \$starttime must be less than \$endtime and not\nlarger than the end time of the test as found in\n$jdata!\n";
}
my $header = `/usr/bin/head -1 $jdata`;
chomp $header;
my @list = split(/\s+/,$header);
my $id = 0;
for (my $x = 0; $x < scalar(@list); $x++)
{
    if ($list[$x] =~ /cell_voltage/)
    {
	$id = $x+2;
    }
}
my $cmd = "/bin/awk \'\{print \$1 \"  \"  \$$id;}\' $jdata";
@list = `$cmd`;
my $sumUs = 0;
my $nxs = 0;
my $sumUe = 0;
my $nxe = 0;
for my $str (@list)
{
    my ($t,$u) = split(/\s+/,$str);
    if (($t > ($startt-$deltat)) && ($t < ($startt+$deltat)))
    {
	$sumUs += $u;
	$nxs++;
    }
    if (($t > ($endt-$deltat)) && ($t < ($endt+$deltat)))
    {
	$sumUe += $u;
	$nxe++;
    }
}
my $Us = $sumUs / $nxs;
my $Ue = $sumUe / $nxe;
my $dU = ($Us - $Ue) * 1000/($endt - $startt);
$Us = &chop($Us);
$Ue = &chop($Ue);
$dU = &chop($dU);
print "Start: $Us mV  End: $Ue mV  Degradation: $dU myV/h\n";
exit;

sub chop($)
{
    my $sign = 1;
    my $x = $_[0];
    if ($x < 0){$sign = -1}; 
    my $res = $x;
    if ($x > 1)
    {
	if ($x =~ /(\d+\.\d\d)/)
	{
	    $res = $1+0;
	}
    }
    else
    {
	if ($x =~ /(\d+\.\d\d\d)/)
	{
	    $res = $1+0;
	}
    }
    $res = $res * $sign;
    return $res;
}
