#!/usr/bin/perl
# $Id: jdata_CO2_to_CH4,v 1.1 2006/03/29 07:21:17 skoch Exp $
my $VERSION = 0.1;
my $PROGRAM = 'jdata_CO2_to_CH4';

use AFM;
use strict;

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

if ($ARGV[scalar(@ARGV)-1] =~ /--debug/)
{
    $debug = 1;
    pop @ARGV;
}  
if ($ARGV[scalar(@ARGV)-1] =~ /--test/)
{
    $debug = 1;
    $test = 1;
    $do = 0;
    pop @ARGV;
}  
if ($ARGV[scalar(@ARGV)-1] =~ /--debug/)
{
    $debug = 1;
    pop @ARGV;
}  

if (scalar(@ARGV) < 2)
{
    print "Not enough parameters for $PROGRAM\nUse: $PROGRAM \$rig \$test\n";
    exit 1;
}

my $rig = 0;
if ( scalar(@ARGV) > 0 ) 
{
    my $rigno = $ARGV[0];
    $rigno =~ /(\d+)/;
    $rig = $1;
}
&check_run($rig);

my $testno = 1;
if ( scalar(@ARGV) > 1 ) 
{
    my $ttestno = $ARGV[1];
    $ttestno =~ /(\d+)/;
    $testno = $1;
}

my $prg = '/usr/local/bin/jdata_conv.pl '.$rig.' '.$testno.' ';
my $dir = $AFM::publicdir.'rig'.$rig.'/'.$rig.'test'.$testno.'/';
my $jdata1 = $dir.'jdata1';
my $jdata = $dir.'jdata';

### Creating backups ###
print "#### creating backup ###\n";
my $cmd = $prg.'"A" h2_org h2 > '.$jdata1;
print $cmd,"\n" if ($debug);
system($cmd) if ($do);
system("/bin/cp $jdata1 $jdata") if ($do);
my $cmd = $prg.'"A" o2_org o2 > '.$jdata1;
print $cmd,"\n" if ($debug);
system($cmd) if ($do);
system("/bin/cp $jdata1 $jdata") if ($do);
my $cmd = $prg.'"A" ch4_org ch4 > '.$jdata1;
print $cmd,"\n" if ($debug);
system($cmd) if ($do);
system("/bin/cp $jdata1 $jdata") if ($do);
### Doing conversion ###

my $cutoff = &AFM::get_usercv_test($rig,$testno,'gas_ch4','cutoff_report')+0;
$cutoff = &AFM::get_config_value_old($rig,'ch4_cutoff',$testno)+0 unless ($cutoff);
my $CO2factor = 1;
if (scalar(@ARGV) > 2)
{
    $cutoff = $ARGV[2]+0;
}
print "#### creating CH4 flow ###\n";
my $cmd = $prg."\"IF\{A > $cutoff \; A * $CO2factor ; 0\}\" ch4 ch4_org > $jdata1";
print $cmd,"\n" if ($debug);
system($cmd) if ($do);
system("/bin/cp $jdata1 $jdata") if ($do);
print "#### creating O2 flow ###\n";
my $cmd = $prg."\"IF\{A > $cutoff \; A * $CO2factor ; B\}\" o2 ch4_org o2_org > $jdata1";
print $cmd,"\n" if ($debug);
system($cmd) if ($do);
system("/bin/cp $jdata1 $jdata") if ($do);
print "#### creating H2 flow ###\n";
my $cmd = $prg."\"IF\{A > $cutoff \; B + A * -2 * $CO2factor ; B\}\" h2 ch4_org h2_org > $jdata1";
print $cmd,"\n" if ($debug);
system($cmd) if ($do);
system("/bin/cp $jdata1 $jdata") if ($do);
print "#### Done ####\n";
system("/bin/rm $jdata1");    

exit;



