#!/usr/bin/perl
use warnings;
use strict;
##### VOLVER A PONER CLEANUP => 1 y SACAR la LIMPIEZA PREVIA
# this is used from ../tests 
use Cwd;
use Cwd 'abs_path';
use File::Spec;
use File::Temp qw / tempdir /;
use Pod::Usage;
use Getopt::Long;

  my %opt;
    GetOptions(\%opt, "help|?", "man", "flag1", "version")  ||  pod2usage(2);
    pod2usage(1)  if ($opt{help});
    if ($opt{version}){
        print "Version 3\n";
	exit;
    };
    pod2usage(-exitval => 0, -verbose => 2)  if ($opt{man});

    ## Check for too many filenames
    pod2usage("$0: Too many files given.\n")  if (@ARGV > 2);


#print " $ARGV[0] $ARGV[1]\n";

my $ac=scalar @ARGV;
if ($ac<0){
    print STDERR "Cantidad insuficiente de argumentos\n";
    exit;
}


=pod
 
=head1 NAME

    sample - Using GetOpt::Long and Pod::Usage

=head1 SYNOPSIS

    sceptre_pre [options] [file ...]

     Options:
       -help            brief help message
       -man             full documentation

=head1 OPTIONS

=over 4

=item B<-help>

    Print a brief help message and exits.

=item B<-man>

    Prints the manual page and exits.

=back

=head1 DESCRIPTION

    B<This program> will read the given input file(s) and do something
    useful with the contents thereof.
 
=cut




# use File::Basename;
# ($name,$path,$suffix) = fileparse($fullname,@suffixlist);
# $name = fileparse($fullname,@suffixlist);
# $basename = basename($fullname,@suffixlist);
# $dirname = dirname($fullname);

sub basename($) {
    my $file = shift;
    if (not $file) {$file=''}
 $file =~ s!^(?:.*/)?(.+?)(?:\.[^.]*)?$!$1!;
 return $file;
}

sub dirname($) {my $file = shift;     if (not $file) {$file=''} ; $file =~ s!/?[^/]*/*$!!; return $file; }

my $llamado=readlink($0);
my $dirllamado = dirname($llamado);
#print "$llamado $dirllamado";
#print "\n";


my $curdir = getcwd();
#print "current $curdir\n";
#y $updir = File::Spec->updir();
#updir = abs_path($updir);
#print "up      $updir\n";
my $todo = $0;
my ($volume,$directories,$nombre) = File::Spec->splitpath($todo);        
#print "$volume     $directories    $nombre\n";
my ($modo,$filesind) = ($nombre =~ /^([^_]+)_(.+)$/);
#print "$directories    $modo    $filesind\n";
#my $dir = File::Spec->catdir ($updir,'examples',$modo,$filesind);
#my $SCEPTRE1 = File::Spec->catdir ($updir,'scripts','sceptre1');

my $scep_test = "$dirllamado/../scripts/sceptre_test.pl";
# todos estos son creados y por lo tanto no necesariamente estan en el
# directorio donde se desempaqueta, si donde se ejecuto el configure
my $SCEPTRE1 =      "../src/phase1/sceptre1"; 
my $sceptre2o =     "../src/phase2/sceptre2.o";
my $LIBSCEPTRE =    "../src/phase2/libsceptre.a";
my $LIBSCEPTREAUX = "../src/auxpro/libsceptreaux.a"; 
my $SCEPTRE_DIRAC = "../src/auxpro/sceptre_dirac"; 
my $FORTRAN;
if (-e  "../pkgac.dat"){
$FORTRAN = `grep ^F77= ../pkgac.dat`;
}else{
$FORTRAN='';
}
$FORTRAN =~ s/^F77=//; $FORTRAN =~ /"(.+)"/  and $FORTRAN = $1; 
my $dir = "$dirllamado/../examples/$modo/$filesind";

my $debug = "--debug"; $debug = '';
my $diroutput = tempdir( CLEANUP => 1);
# with CLEANUP => 1 the temporary directory is erased when program is exited
# with CLEANUP => 0        it is kept
#$diroutput = "~/pruebas";
-d "$diroutput/${modo}_$filesind" or mkdir "$diroutput/${modo}_$filesind";
my $diroutputmo = "$diroutput/${modo}_$filesind";
#print "$diroutputmo\n";
system "rm $diroutputmo/* 2>/dev/null";
my $comando =
"$scep_test $debug $SCEPTRE1 $sceptre2o $LIBSCEPTRE $LIBSCEPTREAUX "
   ."$SCEPTRE_DIRAC $FORTRAN $modo $dir $filesind $diroutputmo";
my $error=system $comando;
 

   if ($error == -1) {
        print "failed to execute: $!\n";
        exit 2;
   } elsif ($error & 127) {
        printf "child died with signal %d, %s coredump\n",
               ($error & 127),  ($error & 128) ? 'with' : 'without';
        exit 3;
#  } else {
#                   printf "child exited with value %d\n", $error >> 8;
   };
$debug and print "$comando - $error\n";
exit $error >> 8;
