#!/usr/bin/perl -wT
#$Id: ajax_interface.cgi,v 1.45 2023/08/24 06:50:56 sqko Exp $
use strict;
use warnings;
use RFC::Main;
use RFC::Rig;
use RFC::RFCCGI qw (get_CGI_value_clean);
use CGI qw(:standard :netscape);
use AFM qw();
use Sys::Hostname qw(hostname);
use SocketClient;
use LWP::UserAgent;
use Unicode::String qw(latin1 utf8);
my $u = &RFC::RFCCGI::get_user();
my $p = &RFC::RFCCGI::get_pass();
my $allow = 0;
my @authids = &get_cv('global','data_access_authorisationid');

my $cred = "&name=$u&pass=$p";

my $ac = get_CGI_value_clean('action');
my $f = get_CGI_value_clean('furnace');
my $run = get_CGI_value_clean('runnr');
my $rig = get_CGI_value_clean('rig');
my $rignr = $rig;
$rignr = $f unless ($rignr);
if ($rignr)
{
    $allow = &RFC::RFCCGI::rig_data_test_access_allow($rignr,$run);
}
else
{
    $allow = &RFC::RFCCGI::rig_data_access_allow();
}


my $ajax = 1;
$ajax = 0 if (param('noajax'));
foreach my $i ($f,$run,$rig)
{
    if ($i && $i =~ /(\d+)/)
    {
	$i = $1;
    }
    else
    {
	$i = 0;
    }
}
my @list = ();
my $ssl = 0;
$ssl = 1 if (CGI::https());
my $listserver = get_cv('servers','listserver');
if ($listserver)
{
    chomp $listserver;
    my $str = &RFC::Main::report_client($listserver,'servers');
    my @l = split(/\t/,$str) if ($str && $str !~ /ERROR/);
    foreach (@l)
    {
	if (/([\w\.\-]+)/)
	{
	    push @list,$1;
	}
    }
}



unless ($ac)
{
    print header(-access_control_allow_origin => '*',-content_type=>'text/plain',-charset=>'utf-8');
    print <<END;

Oops.. no parameters, displaying interface definitions!

Common parameters:

Parameter 'action', determines which function to call (each described below)
Generally, the script returns OK on the first line if input is valid, and an errorstring if not.
Thus remember to check for the 'OK' string as part of the ajax response function.

If password protection is implemented the following additional parameters may be nescesarry for some of the functions.:
'name' Username, text
'pass' Session key, text
'time' Time of last login, text
'jscheck', integer (must be 1)


Function description based on 'action' parameter:

Action 'server_name'
No parameters
Returns a string with the servers name (if no specific name is specified in the configuration file, it returns the hostname)

Action 'equipmentid'
Returns the equipment id (if it is defined) for the rig in question
Parameters:
'furnace'  Rig number, integer 


Action 'show_details':
Returns a http redirect / refresh header pointing to the resulting server and directory
Parameters:
'furnace'  Rig number, integer 
'testnr'   Test number to display, integer


Action 'get_test_location':
Unlike 'show_details', this function call tests that the test specified actually is a 
valid test number on the server where the rig was found as it is not safe to assume that all test numbers less
than the current test are valid.
Returns a http redirect / refresh header pointing to the resulting server and directory
Parameters:
'furnace'  Rig number, integer 
'testnr'   Test number to display, integer

Action 'furnaces':
No parameters
Displays a list of possible rigs (all in cluster).

Action 'rigs':
No parameters
Displays a list of possible rigs (all in cluster).

Action 'rigs_equipmentid'
No parameters
Displays a list of possible rigs inclucing potential equipmentids (all in cluster).

Action 'furnaces_equipmentid'
No parameters
Displays a list of possible rigs inclucing potential equipmentids (all in cluster).

Action 'is_furnace':
Parameters:
'furnace'  Rig number to check if it exists, integer

Action 'is_rig':
Parameters:
'rig'  Rig number to check if it exists, integer


Action 'active_furnace':
Parameters:
'furnace'  Rig number to check if it is valid for new data, integer

Action 'active_rig':
Parameters:
'rig'  Rig number to check if it is valid for new data, integer


Action 'run_list':
Parameters:
'furnace'  Rig number, integer
Returns a list of valid test numbers for the specified rig on any of the servers on the cluster.

Action 'is_run':
Parameters:
'furnace'  Rig number, integer
'runnr'    Test number to check, integer
Checks if the runnumber specified is valid for the rig in question on any of the servers on the cluster.


Action 'imp_list':
Parameters:
'furnace'  Rig number, integer
'runnr'    Test number to check, integer
Returns a list of impedance files for the test in question from the correct servers on the cluster.


Action 'imp_file':
Parameters:
'furnace'  Rig number, integer
'runnr'    Test number to check, integer
'filenr'   File number to get, use the line number from the list returned by imp_list (linenr is first integer on the line). 
Retruns the content of the impedance file specified from the corresponding server on the cluster.
Note, that if a .htaccess file exist in the test directory, nothing is returned for that test (as data could be confidential and thus only accessible from certain users).


Action 'iv_list':
Parameters:
'furnace'  Rig number, integer
'runnr'    Test number to check, integer
Returns a list of iv curves for the test in question from the correct servers on the cluster.
Note that only tests where the make_iv_curves.pl program has been run will return any data!


Action 'iv_file':
Parameters:
'furnace'  Rig number, integer
'runnr'    Test number to check, integer
'filenr'   File number to get, use the line number from the list returned by imp_list (linenr is first integer on the line). 
Returns the content of the iv curve file specified from the corresponding server on the cluster.
Note, that if a .htaccess file exist in the test directory, nothing is returned for that test (as data could be confidential and thus only accessible from certain users).

Action 'run':
Parameters:
'furnace'  Rig number, integer
'runnr'    Test number, integer
Returns the temperature, ramprate and dwelltime for the specified run
As most RFCcontrol tests are non-trivial, the function returns 0,0,0 and a warning for manual check.


Action 'rig_session':
Parameters:
'rig'  Rig number, integer
'runnr'    Test number, integer
Checks if the specified rig and test number exists on THIS server.


Action 'rig_session_list':
Parameters:
'rig'  Rig number, integer
Returns a list of test numbers for the specified rig on THIS server (only returns valid tests for which the test directory exists)


Action 'rig_imp_list':
Parameters:
'rig'  Rig number, integer
'runnr'    Test number, integer
Returns a list of impedance files from a valid rig and test on THIS server.
Note, that if a .htaccess file exist in the test directory, nothig is returned (as data could be confidential and thus only accessible from certain users).

Action 'rig_imp_file':
'rig'  Rig number, integer
'runnr'    Test number to check, integer
'filenr'   Fime number to get, use the line number from the list returned by imp_list (linenr is first integer on the line). 
Retruns the content of the impedance file specified (must exist on THIS server).
Note, that if a .htaccess file exist in the test directory, nothing is returned (as data could be confidential and thus only accessible from certain users).


Action 'rig_iv_list':
Parameters:
'rig'  Rig number, integer
'runnr'    Test number, integer
Returns a list of iv curves from a valid rig and test on THIS server.
Only tests where the make_iv_curves.pl program has been run will return any data!
Note, that if a .htaccess file exist in the test directory, nothig is returned (as data could be confidential and thus only accessible from certain users).

Action 'rig_iv_file':
'rig'  Rig number, integer
'runnr'    Test number to check, integer
'filenr'   Fime number to get, use the line number from the list returned by imp_list (linenr is first integer on the line). 
Retruns the content of the iv curve file specified (must exist on THIS server).
Note, that if a .htaccess file exist in the test directory, nothing is returned (as data could be confidential and thus only accessible from certain users).




END
    exit;
}

foreach ($f,$rig)
{
    $_ = '' unless (defined($_));
}

print header(-access_control_allow_origin => '*',-charset=>'utf-8');



if ($ac eq 'server_name')
{
    my $name = &get_cv('global','server_name');
    $name = hostname unless ($name);
    print $name;
    exit;
}


if ($ac eq 'get_test_location')
{
    my $server = '';
    my $test = get_CGI_value_clean('testnr');
    if (!$f || !$test)
    {
	print "Warning\nNo rig or test number specified!\n";
	exit;	
    }
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'is_test',$f,$test);
	next unless ($str);
	$server = $s;
	last;
    }
    if (!$server || !$f)
    {
	print "Warning\nNo rig found!\n";
	exit;
    }
    my $url =  $server.'/rig'.$f.'/'.$f.'test'.$test.'/';
    my $string = '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=http://'.$url.'">';
    $string = '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=https://'.$url.'">' if ($ssl);
    print $string,"\n";
    exit;
}


if ($ac eq 'show_details')
{
    my $server = '';
  OUTER:
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'active_rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach my $r (@l)
	    {
		next unless ($f == $r);
		$server = $s;
		last OUTER;
	    }
	}
    }
    if (!$server)
    {
	print "Warning\nNo rig found!\n";
	exit;
    }
    my $test = get_CGI_value_clean('testnr');
    my $url =  $server.'/rig'.$f.'/'.$f.'test'.$test.'/';
    my $string = '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=http://'.$url.'">';
    $string = '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=https://'.$url.'">' if ($ssl);
    print $string,"\n";
    exit;
}

if ($ac eq 'equipmentid')
{
    print "OK\n";
    my $r = param('furnace');
    $r = param('rig') unless ($r);
    my $rig = RFC::Rig->new($r);
    my $id = $rig->get_cv('main','equipmentid');
    $id = '' unless ($id);
    print $id,"\n";
}


if ($ac eq 'testnr')
{
    print "OK\n";
    my $r = param('furnace');
    $r = param('rig') unless ($r);
    my $rig = RFC::Rig->new($r);
    my $id = $rig->session();
    $id = '' unless ($id);
    print $id,"\n";
}


if ($ac eq 'furnaces' || $ac eq 'rigs')
{
    print "OK\n";
    my @rigs = ();
    foreach my $s (@list)
    {
        my $str = &RFC::Main::report_client($s,'rigs');
        if (defined($str))
        {
            chomp $str;
            chomp $str;
            chomp $str;
            push @rigs,split(/\t/,$str);
        }
    }
    print join("\n",(sort {$a <=> $b} @rigs)),"\n";
    exit;
}


if ($ac eq 'furnaces_equipmentid' || $ac eq 'rigs_equipmentid')
{
    print "OK\n";
    my %ids = ();
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    foreach my $r (split(/\t/,$str))
	    {
		my $ua = LWP::UserAgent->new();
		$ua->timeout(60);
		my $url = 'http://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=equipmentid&furnace=' . $r .$cred;
		$url = 'https://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=equipmentid&furnace=' . $r .$cred if ($ssl);
		my $request = new HTTP::Request('GET',$url);
		my $response = $ua->request($request);
		my $content = $response->content();
		my $res = $content if ($content);
		if ($res && $res =~ /OK/ && $res =~ /(\d+)/)
		{
		    if (exists($ids{$r}))
		    {
			warn "Warning: multiple rigs in the cluster detected with rig number $r!\n";
		    }
		    else
		    {
			$ids{$r} = $1;
		    }
		}
	    }
	}
    }
    foreach my $r (sort {$a <=> $b} keys %ids)
    {
	my $id = $ids{$r};
	$id = '' unless ($id);
	print $r,"\t",$id,"\n";
    }
    exit;
}

if ($ac eq 'is_furnace' || $ac eq 'is_rig')
{
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach (@l)
	    {
		next unless ($_ == $f || $_ == $rig);
		print "OK\n";
		print "1\n";
		exit;
	    }
	}    
    }
    print "Warning\n";
    print "No furnace found\n";
    exit;
}

if ($ac eq 'active_furnace' || $ac eq 'active_rig')
{
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'active_rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach (@l)
	    {
		next unless ($_ == $f || $_ == $rig);
		print "OK\n";
		print "1\n";
		exit;
	    }
	}    
    }
    print "Warning\n";
    print "No furnace found\n";
    exit;
}


if ($ac eq 'run_list')
{
    my $res = "Warning\nNo rig found!\n";
  OUTER:
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach my $r (@l)
	    {
		next unless ($f == $r);
		my $ua = LWP::UserAgent->new();
		$ua->timeout(60);
		my $url = 'http://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_session_list&rig=' . $r .$cred;
		$url = 'https://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_session_list&rig=' . $r .$cred if ($ssl);
		my $request = new HTTP::Request('GET',$url);
		my $response = $ua->request($request);
		my $content = $response->content();
		$res = $content if ($content);
		last OUTER;
	    }
	}
    }
    print $res;
}

if ($ac eq 'is_run')
{
    my $res = "Warning\nNo rig found!\n";
  OUTER:
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach my $r (@l)
	    {
		next unless ($f == $r);
		my $ua = LWP::UserAgent->new();
		$ua->timeout(60);
		my $url = 'http://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_session&rig=' . $r . '&runnr=' . $run .$cred;
		$url = 'https://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_session&rig=' . $r . '&runnr=' . $run .$cred if ($ssl);
		my $request = new HTTP::Request('GET',$url);
		my $response = $ua->request($request);
		my $content = $response->content();
		$res = $content if ($content);
		last OUTER;
	    }
	}
    }
    print $res;
}


### Below here is info which could be confidential

unless ($allow)
{
    my $name = &get_cv('global','server_name');
    $name = hostname unless ($name);
    print "You are not allowed to access data on $name";
    exit;
}



if ($ac eq 'imp_list')
{
    my $res = "Warning\nNo rig found!\n";
  OUTER:
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach my $r (@l)
	    {
		next unless ($f == $r);
		my $ua = LWP::UserAgent->new();
		$ua->timeout(60);
		my $url = 'http://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_imp_list&rig=' . $r . '&runnr=' . $run .$cred;
		$url = 'https://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_imp_list&rig=' . $r . '&runnr=' . $run .$cred if ($ssl);
		my $request = new HTTP::Request('GET',$url);
		my $response = $ua->request($request);
		my $content = $response->content();
		$res = $content if ($content);
		last OUTER;
	    }
	}
    }
    print $res;
}



if ($ac eq 'iv_list')
{
    my $res = "Warning\nNo rig found!\n";
  OUTER:
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach my $r (@l)
	    {
		next unless ($f == $r);
		my $ua = LWP::UserAgent->new();
		$ua->timeout(60);
		my $url = 'http://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_iv_list&rig=' . $r . '&runnr=' . $run. $cred;
		$url = 'https://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_iv_list&rig=' . $r . '&runnr=' . $run .$cred if ($ssl);
		my $request = new HTTP::Request('GET',$url);
		my $response = $ua->request($request);
		my $content = $response->content();
		$res = $content if ($content);
		last OUTER;
	    }
	}
    }
    print $res;
}



if ($ac eq 'imp_file')
{
    my $filenr = get_CGI_value_clean('filenr');
    my $res = "Warning\nNo rig found!\n";
  OUTER:
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach my $r (@l)
	    {
		next unless ($f == $r);
		my $ua = LWP::UserAgent->new();
		$ua->timeout(60);
		my $url = 'http://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_imp_file&rig=' . $r . '&runnr=' . $run . '&filenr=' . $filenr .$cred;
		$url = 'https://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_imp_file&rig=' . $r . '&runnr=' . $run . '&filenr=' . $filenr .$cred if ($ssl);
		my $request = new HTTP::Request('GET',$url);
		my $response = $ua->request($request);
		my $content = $response->content();
		$res = $content if ($content);
		last OUTER;
	    }
	}
    }
    print $res;
}



if ($ac eq 'iv_file')
{
    my $filenr = get_CGI_value_clean('filenr');
    my $res = "Warning\nNo rig found!\n";
  OUTER:
    foreach my $s (@list)
    {
	my $str = &RFC::Main::report_client($s,'rigs');
	if (defined($str))
	{
	    chomp $str;
	    chomp $str;
	    chomp $str;
	    my @l = split(/\t/,$str);
	    foreach my $r (@l)
	    {
		next unless ($f == $r);
		my $ua = LWP::UserAgent->new();
		$ua->timeout(60);
		my $url = 'http://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_iv_file&rig=' . $r . '&runnr=' . $run . '&filenr=' . $filenr .$cred;
		$url = 'https://'.$s . '/cgi-bin/celltest/ajax_interface.cgi?action=rig_iv_file&rig=' . $r . '&runnr=' . $run . '&filenr=' . $filenr .$cred if ($ssl);
		my $request = new HTTP::Request('GET',$url);
		my $response = $ua->request($request);
		my $content = $response->content();
		$res = $content if ($content);
		last OUTER;
	    }
	}
    }
    print $res;
}


$rig = $f unless ($rig);



if ($ac eq 'run')
{
    print "OK\n" if ($ajax);
    print "0\n";
    print "0\n";
    print "0\n";
    print "Warning: Not a simple furnace run, check manually on server!\n";
}

if ($ac eq 'rig_session')
{
    my $r = RFC::Rig->new($rig);
    my $session = $r->session();
    if ($run >= 0 && $run <= $session)
    {
	print "OK\n" if ($ajax);
	print "1\n";
	exit;	
    }
    else
    {
	print "Warning\n";
	print "Run $run for rig $rig not valid!\n";
    }
}

if ($ac eq 'rig_session_list')
{
    my $r = RFC::Rig->new($rig);
    my $session = $r->session();
    print "OK\n" if ($ajax);
    for (my $x = 0; $x <= $session; $x++)
    {
	my $dir = $r->webdir($x);
	print $x,"\n" if (-d $dir);
    }
}

if ($ac eq 'rig_imp_list')
{
    my $r = RFC::Rig->new($rig);
    my $session = $r->session();
    if ($run >= 0 && $run <= $session)
    {
	print "OK\n" if ($ajax);
	my $htacc = $r->webdir($run).'/.htaccess';
	unless (-e $htacc)
	{ 
	    my $filename = $r->webdir($run).'/impedance/imp_data';
	    my $file = SemaforeFile->new($filename);
	    my @list = $file->readlines();
	    foreach (my $x=0; $x <  @list; $x++) 
	    {
		$list[$x] =~ s/^[\s\t]+//;
		print $x.' '.$list[$x],"\n";
	    }
	}
	exit;	
    }
    else
    {
	print "Warning\n";
	print "Run $run for rig $rig not valid!\n";
    }
}


if ($ac eq 'rig_iv_list')
{
    my $r = RFC::Rig->new($rig);
    my $session = $r->session();
    if ($run >= 0 && $run <= $session)
    {
	print "OK\n" if ($ajax);
	my $htacc = $r->webdir($run).'/.htaccess';
	unless (-e $htacc)
	{ 
	    my $filename = $r->webdir($run).'/iv/ivtable-avg';
	    my $file = SemaforeFile->new($filename);
	    my @list = $file->readlines();
	    ### Fix offset by 1 as ivcurves start at number 1 not 0... ###
	    unshift @list,0;
	    foreach (my $x=1; $x <  @list; $x++) 
	    {
		my @l = split(/[\s\t]+/,$list[$x]);
		### Format numbers ###
		foreach (@l)
		{
		    next if (/[^\d\.\-\+eE]+/);
		    if ($_ > 50)
		    {
			$_ = sprintf("%.0f",$_);
		    }
		    else
		    {
			$_ = sprintf("%.1f",$_);			
		    }
		}
		my $st = join(' ',@l);
		### Get rid of cols with 'avg' in label ###
		$st =~ s/\s\w+avg\w*\s[\d\.\-\+eE]+//g;
		if (param('filenr') && param('filenr') =~ /(\d+)/)
		{
		    print $x.' '.$st,"\n" if ($x == $1);
		}
		else
		{
		    print $x.' '.$st,"\n";
		}
	    }
	}
	exit;	
    }
    else
    {
	print "Warning\n";
	print "Run $run for rig $rig not valid!\n";
    }
}

if ($ac eq 'rig_imp_file')
{
    my $r = RFC::Rig->new($rig);
    my $session = $r->session();
    my $filenr = get_CGI_value_clean('filenr');
    if ($run >= 0 && $run <= $session)
    {
	my $htacc = $r->webdir($run).'/.htaccess';
	unless (-e $htacc)
	{ 
	    my $filename = $r->webdir($run).'/impedance/imp_data';
	    my $file = SemaforeFile->new($filename);
	    my @list = $file->readlines();
	    if ($list[$filenr] && $list[$filenr] =~ /([\w\.\-\:\,]+i2b)+\s+/)
	    {
		my $ifile = SemaforeFile->new($r->webdir($run).'/impedance/'.$1);
		if ($ifile->exist)
		{
		    print "OK\n" if ($ajax);
		    print join("\n",$ifile->readlines);
		}
		else
		{
		    print "Warning\n";
		    print "Impedance file $filenr not found for rig $rig and test $run!\n";	    
		}
	    }
	    else
	    {
		print "Warning\n";
		print "Impedance file $filenr not found for rig $rig and test $run!\n";	    
	    }
	}
	else
	{
	    print "Warning\n";
	    print "Impedance file $filenr not accessible as a .htaccess file was found for rig $rig and test $run!\n";	    	    
	}
	exit;	
    }
    else
    {
	print "Warning\n";
	print "Run $run for rig $rig not valid!\n";
    }
}


if ($ac eq 'rig_iv_file')
{
    my $filenr = get_CGI_value_clean('filenr');
    my $r = RFC::Rig->new($rig);
    my $session = $r->session();
    if ($run >= 0 && $run <= $session)
    {
	my $htacc = $r->webdir($run).'/.htaccess';
	unless (-e $htacc)
	{ 
	    my $filename = $r->webdir($run).'/iv/ivdatadir-'.$filenr.'/ivdata';
	    my $file = SemaforeFile->new($filename);
	    if ($file->exist)
	    {
		my $currentlabel = $r->get_cv_test('IV_control','current_label',$session);
		my $voltlabel = $r->get_cv_test('IV_control','voltage_label',$session);
		my $templabel = $r->get_cv_test('IV_control','temp_label',$session);
		my $presslabel = $r->get_cv_test('IV_control','pressure_label',$session);
		$presslabel = 'pressure' unless ($presslabel);
		$currentlabel = 'current' unless ($currentlabel); ## Default value for backwards compatibility ###
		$voltlabel = 'cell_voltage' unless ($voltlabel);  ## Default value for backwards compatibility ###
		$templabel = 'T_center' unless ($templabel); ## Default value for backwards compatibility ###
		my $area = $r->get_cv_test('main','cell_area',$session);
		$area =  &AFM::get_config_value_old($rig,'area',$session) unless ($area);
		$area = 1 unless ($area);
		my @lines = $file->readlines();
		if (@lines)
		{
		    my $head = $lines[0];
		    my @l = split(/[\s\t]+/,$head);
		    my %index = ();
		    for (my $x = 0; $x < @l; $x+=2)
		    {
			if ($x == 0)
			{
			    $index{'time'} = 2;
			}
			else
			{
			    $index{$l[$x]} = $x+2;
			}
		    }
		    my @list = ($area);
		    foreach my $i ($currentlabel,$voltlabel,$templabel,'R_secant','ASR_corr','Power')
		    {
			push @list,'$'.$index{$i};
		    }
		    my $str = join(',',@list);
		    my $cmd = "awk '{print $str}' $filename";
		    print "OK\n" if ($ajax);
		    print join(' ','Area','Current','Voltage','Temp','R_secant','ASR_corr','Power'),"\n";
		    system($cmd);
		}
	    }
	    else
	    {
		print "Warning\n";
		print "Iv curve $filenr not found for rig $rig and test $run!\n";	    
	    }
	}
	else
	{
	    print "Warning\n";
	    print "I-v curve $filenr not accessible as a .htaccess file was found for rig $rig and test $run!\n";	    	    
	}
	exit;	
    }
    else
    {
	print "Warning\n";
	print "Run $run for rig $rig not valid!\n";
    }
}


