#!/usr/bin/perl -T
#$Id: get_gas_use.cgi,v 1.10 2021/01/26 08:31:21 sqko Exp $
use strict;
use warnings;
use CGI qw(:standard :netscape);

use RFC::Rig;
print header(-access_control_allow_origin => '*',-content_type=>'text/plain',-charset=>'utf-8');
unless (param())
{
    print <<END;

Oops.. no parameters, displaying interface definitions!

This interface can be used to report gas use for the current test running on the server.

in order to get the info the following paramteres must be specified

rig:   Rig number (integer)
match: date string [optional] Format: YYYY:DD

If the match parameter is specified, only data from days which matches the specified date string will be included
So if the match string 2020:10 is speficied only data from October 2020 will be included 


The response will look something like this:

15test123
12345 x-1
2020:11
co     295.800
o2     183.369
n2     0.000
sweep  0.000
h2     827.972
ar     0.000
air    0.000
backup 0.000
co2    2.727


Where the first 3 lines specify the test number, the project number and the match-date.
The project number and / or the match line may be blank.

The exact number of lines will vary depending on the number og gasses configured for the rig in question.

Remember that the tool report the gas use, thus if a gas is called co2_inlet and it is not correctly 
configured (that is the gas has not been specified as co2 but left at the default n2), then the gas flow for this
gas line will be reported as n2 and not co2 as the gas name indicate it should be!  

The gas use will be reported in liters!

Note that only IP-addresses listed in the main configuration file section 'global' under 'allowed_ip' can use this service.

END

    exit;
}


my $r = param('rig');
my %gasses = ();
my %include = ();
my %flow = ();
my %time = ();
my %total = ();
my %minflow = ();
my @ip_allow = &RFC::Main::get_cv('global','allowed_ip');
my $ok = 0;
foreach my $ip (&RFC::Main::get_cv('global','allowed_ip'))
{
    $ok = 1 if ($ENV{'REMOTE_ADDR'} eq $ip);
}
unless ($ok)
{
    print "Access deined!\n";
    exit;
}
unless ($r)
{
    print "No rig specified!\n";
    exit;
}
my $rig = RFC::Rig->new($r);
unless ($rig)
{
    print "Rig $r not valid!\n";
    exit;	
}
my @gasses = $rig->list_devices('gas');
foreach my $g (@gasses)
{
    my $d = $rig->get_device('gas',$g);
    next unless ($d);
    my $gas = $d->gas();
    $gasses{$g} = $gas;
    $total{$g} = 0;
    $minflow{$g} = $d->cutoff_set();
    $include{$g} = $d->include_tally();
}
my $dir = $rig->webdir();
my $htacc = $dir.'.htaccess';
if (-e $htacc)
{
    exit;
}

opendir(DIR, $dir);
my @files = sort {$a cmp $b} grep(/raadata\..*/,readdir(DIR));
closedir(DIR);
my $match = param('match');
if ($match && $match =~ /([\d\:]+)/)
{
    $match = $1;
}
else
{
    $match = '';
}
if (@files)
{
    ## Use raadata files if they exists (will me most accurate)
    foreach my $f (@files)
    {
	if ($match)
	{
	    next unless ($f =~ /$match/);
	}
	next unless (-e $dir.$f);
	open MYIN,'<',$dir.$f or die "Could not open file $f for reading $!\n";
	while (my $line = <MYIN>)
	{
	    my @l = split(/[\s\t]+/,$line);
	    for (my $x = 0; $x < @l; $x+=4)
	    {
		foreach my $g (@gasses)
		{
		    next unless ($l[$x] eq $g);
		    ## sanitize gas flows, set to 0 if less than 0 or above 100 m3/hour (likely erroneous measurements) ##
		    $l[$x+3] = 0 if ($l[$x+3] < 0);
                    $l[$x+3] = 0 if ($l[$x+3] > 100000);
		    if ($flow{$g})
		    {
			$total{$g} += ($flow{$g} + $l[$x+3]) * ($l[$x+2] - $time{$g}) / (2 * 3600);
		    }
		    if ($l[$x+3] < $minflow{$g})
		    {
			$flow{$g} = 0;
		    }
		    else
		    {
			$flow{$g} = $l[$x+3];
		    }
		    $time{$g} = $l[$x+2];
		}
	    }
	}
	close MYIN;
    }
}
else
{
    ## Use jdata file instead ##
    my $f = $dir.'jdata';
    if (-e $f)
    {
	my $time;
	open MYIN,'<',$f or die "Could not open file $f for reading $!\n";
	while (my $line = <MYIN>)
	{
	    next if ($match && $line !~ /$match/);
	    my @l = split(/[\s\t]+/,$line);
	    for (my $x = 0; $x < @l; $x+=2)
	    {
		foreach my $g (@gasses)
		{
		    next unless ($l[$x] eq $g);
		    ## sanitize gas flows, set to 0 if less than 0 or above 100 m3/hour (likely erroneous measurements) ##
		    $l[$x+1] = 0 if ($l[$x+1] < 0);
                    $l[$x+1] = 0 if ($l[$x+1] > 100000);
		    if ($flow{$g})
		    {
			$total{$g} += ($flow{$g} + $l[$x+1]) * ($l[3] - $time) / (2 * 3600);
		    }
		    if ($l[$x+1] < $minflow{$g})
		    {
			$flow{$g} = 0;
		    }
		    else
		    {
			$flow{$g} = $l[$x+1];
		    }
		}
	    }
	    $time = $l[3];
	}
	close MYIN;
    }
}

my %gasflow = ();
foreach my $g (@gasses)
{
    if ($gasflow{$gasses{$g}})
    {
	$gasflow{$gasses{$g}} += $total{$g};
    }
    else
    {
	$gasflow{$gasses{$g}} = $total{$g};
    }
}

my $f = $dir.'info.txt';
my $project = '';
open MYIN,'<',$f or die "Could not open file $f for reading $!\n";
while (my $st = <MYIN>)
{
    if ($st =~ /^PROJECT[\s\t]+\#[\s\t]+([\w\s\.\-\:\(\)]+)/)
    {
	$project = $1;
	chomp $project;
	last;
    }
}
close MYIN;
## Print info and gas use ##
print $rig->name().'test'.$rig->session()."\n";
print $project,"\n";
print $match,"\n";
for my $gas (keys %gasflow)
{
    next unless ($include{$gas});
    printf("%s\t%.3f\n",$gas,$gasflow{$gas});
}

