#!/usr/bin/perl -wT
# $Id: CH4_vogt.pl,v 1.5 2012/10/29 12:11:06 sofc Exp $
$ENV{'BASH_ENV'} = '/bin:/usr/bin:/usr/local/bin';
$ENV{'ENV'} = '/bin:/usr/bin:/usr/local/bin';
use RFC::Rig;
use RFC::Main;
use RFC::Header;
use POSIX;
use strict;
use warnings;
use sigtrap qw(die INT QUIT);
use sigtrap qw(die untrapped normal-signals  stack-trace any error-signals);

if (@ARGV < 1)
{
    my $string = "Not enough input parameters for H2vogt.pl\n";
    $string = $string.'Usage: '.$0.'  Rig_number [opt: current]'."\n";
    $string = $string."If the \'current\' option is given, the rig is set\nto open circuit voltage upon low H2flow\nOtherwise only a mail is sent.\n";
    die "$string";
    exit 1;
}

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

my $current = 0;
foreach (@ARGV)
{
    $current = 1 if /current/i;
}

sleep(30);

my $homedir = '/home/rig'.$rig->name.'/';
my $currenttest = $rig->session;
my $datadir = $homedir . $rig->name . 'test'. $currenttest;

my $time = localtime;
my $file = $RFC::Header::publicdir.'rig'.$rig->name.'/'.$rig->name.'test'.$currenttest;
my @gaslist = ('h2','ch4','o2');
my $str = $rig->get_cv('main','vogt_gasses');
@gaslist = split(/\s*\,\s*/,$str) if ($str);
my $found = 0;
foreach (@gaslist)
{
    next unless ($_ eq 'o2');
    $found = 1;
}
push @gaslist,'o2' unless ($found);
$found = 0;
foreach (@gaslist)
{
    next unless ($_ eq 'ch4');
    $found = 1;
}
push @gaslist,'ch4' unless ($found);

$str = $rig->get_cv('main','additional_vogt_gasses_cutoff');
$str = $rig->get_cv('main','aditional_vogt_gasses_cutoff') unless ($str);
my @gaslistcut = ('ch4','o2');
if ($str)
{
    foreach (split(/\s*\,\s*/,$str))
    {
	push @gaslistcut,$_;
    }
}
my @devlist = ();
my @devlistcut = ();
foreach my $name (@gaslist)
{
    my $dev = $rig->get_device('gas',$name);
    $rig->die("Could not get device id for gas '$name'") unless ($dev);
    push @devlist,$dev if ($dev);
}
foreach my $name (@gaslistcut)
{
    my $dev = $rig->get_device('gas',$name);
    $rig->die("Could not get device id for gas '$name'") unless ($dev);
    push @devlistcut,$dev if ($dev);
}

### get flows for all gasses in list, measure 5 times, get median ###
my %flow = ();
foreach my $dev (@devlist)
{
    my @flow = ();
    for (1..5)
    {
	push @flow,$dev->read;
    }
    @flow = sort {$a <=> $b} @flow;
    my $f = @flow[POSIX::floor(0.6 + @flow/2)]; 
    $f = 0 if ($f < $dev->cutoff_set());
    $flow{$dev->name} = $f;
}

### Check for Hydrogen sulphide ##
my $h2flow = $flow{'h2'};
foreach (keys %flow)
{
    $h2flow += $flow{$_} if (/h2s/);
}
$flow{'h2'} = $h2flow;

### Check hydrogen flow ##

if (!$flow{'h2'} || $flow{'h2'} < 2.1 * $flow{'o2'})
{
    my $string = "H2 flow was below cutoff or below 2.1 of O2 flow, measured flow: ".$flow{'h2'}." L/h\n";
    &set_failure('h2_flow_error',$string,@devlistcut);
    $rig = undef;
    exit;
}

### Check for CH4 failure ##

if ($flow{'ch4'} && $flow{'ch4'} > $flow{'o2'} * 0.9)
{
    my $string = "CH4 flow above 0.9 * O2 flow, measured flow for CH4: ".$flow{'ch4'}." L/h, O2: ".$flow{'o2'}."L/h\n";
    my @list = ();
    foreach my $dev (@devlistcut)
    {
	push @list,$dev if $dev->name eq 'ch4'; 
    }
    &set_failure('ch4_flow_error',$string,@list);
    $rig = undef;
    exit;
}


## If we get here, all is ok, thus remove warning mail file entries ###
$rig->unset_warning('h2_flow_error');
$rig->unset_warning('ch4_flow_error');
$rig = undef;
exit;



sub set_failure($$@)
{
    my $type = shift;
    my $string = shift;
    my @devlist = @_;
    return if ($rig->check_warning($type));
    if ($current)
    {
	$string .= "Current set to OCV\n";
	my $str = $rig->get_cv('main','iv_control_names');
	if ($str)
	{
	    foreach my $psu (split(//,$str))
	    {
		$rig->current('ocv',$psu,$0);
	    }
	}
	else
	{
	    $rig->current('ocv');
	}
	### Stop any running program! ####
	$string .= "Stopping any running program!\n";
	RFC::Main::CGI_client($rig->name,'stop_custom');
	sleep(5);
    }
    foreach my $device (@devlist)
    {
	$device->setflow(0,$0);
	$string = $string . $device->name." flow set to 0 automatically by $0\n";
    }
    $rig->warning_mail($type,$string);
    if ($rig->get_cv('main','additional_gas_trip_program'))
    {
	my $cmd = $RFC::Header::libdir.'logprograms/'.$rig->get_cv('main','additional_gas_trip_program');
	if (-e $cmd && -x $cmd)
	{
	    system($cmd.' '.$rig->name);
	}
    }
    for my $adr (split(/\,/,get_cv('admin','system_mail_users')))
    {
	&RFC::Main::mail($adr,$string);
    }
}





