#!/usr/bin/perl
# $Id: long_term_degradation,v 1.2 2006/03/29 07:43:41 skoch Exp $
use strict;
use warnings;
use AFM;

my $VERSION = 0.01;
my $PROGRAM = 'long_term_degradation';
my $debug = 0;

if ( scalar(@ARGV) < 4 ) 
{
    print "Usage: $PROGRAM [rig] [test] [start_time] [end_time]\n"; 
    exit 1;
}
if ($ARGV[scalar(@ARGV)-1] =~ /--debug/)
{
    $debug = 1;
    pop @ARGV;
}

my $usernumber = $<;
my $username = &AFM::get_user_name($usernumber);
my $testusername = 'rig'.$ARGV[0];
if ($username ne $testusername)
{
    print "wrong user: $username !\n";
    print "To access data for rig $ARGV[0] you must be user rig$ARGV[0]!\n";
    exit 1;
}

my $rig = $ARGV[0];
if ( !&AFM::check_rig_nr($rig) ) 
{
    print "Rig $rig is not valid!\n";
    exit 1;
}
my $testno = &AFM::get_test_nr($rig);
if (scalar(@ARGV) > 1) 
{
    my $string = $ARGV[1];
    $string =~ /(\d+)/;
    my $ttest = $1;
    if (defined($ttest))
    {
	$testno = $ttest+0;
    }
}

my $starttime = $ARGV[2]+0;
my $endtime = $ARGV[3]+0;

my $dir = $AFM::publicdir.'rig'.$rig.'/'.$rig.'test'.$testno.'/';
my $file = $dir.'degradation';

if ($starttime == $endtime)
{
    unlink $file;
    exit;
}

my $command = "/usr/local/bin/degradation_rate $rig $testno $starttime $endtime";
my $res = `$command`;
open OUT,'>',$file or die "Could not open file $file!!\n";
print OUT "Start: $starttime h End: $endtime,  $res";
close OUT;
print $res if ($debug);
exit;
 
