#!/usr/bin/perl
# Wrapper script for running NRG iteration codes
# Part of "NRG Ljubljana"
# Rok Zitko, rok.zitko@ijs.si, Dec 2007
# $Id: nrgrun 859 2009-10-08 16:33:47Z zitko $

# Checks for the presence of 'param' and 'data' files. stdout and stderr
# are redirected to log and log2, but stdout also goes to the console
# (using tee).

print '$Id: nrgrun 859 2009-10-08 16:33:47Z zitko $'."\n";

use warnings;
use strict;
use FindBin;

if (!-e "param") {
    die "Parameter file not found. Aborting.\n";
}

if (!-e "data") {
    die "Data file not found. Aborting.\n";
}

# Any required prefix, such as "LD_LIBRARY_PATH=/usr/mylibs/"
my $prefix = "";
my $exe = "nrg";

open (F, "data") or die "Can't open the data file.";
my $firstline = <F>;
my $secondline = <F>;
my $thirdline = <F>;
close(F);

if ($thirdline =~ /COMPLEX/) {
    $exe = "nrgcmpl";
}

# The path to the directory where the executables reside.
# Try script directory, subdir /src and subdir /nrgbin.
my $pathexe = "";
my $test;

$test = "$FindBin::Bin/$exe";
if (-e $test) {
    $pathexe = $test;
}

$test = "$FindBin::Bin/src/$exe";
if (-e $test) {
    $pathexe = $test;
}

$test = "$FindBin::Bin/nrgbin/$exe";
if (-e $test) {
    $pathexe = $test;
}

if ($pathexe eq "") {
    die "Can't find the executable.\n";
}
  
# Note: we prefix \ to time in order to run /usr/bin/time rather
# than the bash built-in command of the same name...
my $cmd = "$prefix \\time $pathexe @ARGV 2>log2 | tee log";
print "Invoking: $cmd\n";
my $return = system($cmd);

if ($return != 0) {
    print "WARNING: Returned with errorcode $return\n";
}
