#!/usr/bin/env perl
use strict;
use warnings;
use Fcntl 'O_RDONLY';
use Tie::File;
use Term::ANSIColor;
my $dir = $ARGV[0] // die("you must give a source directory");
my $n = $ARGV[1] // die("you must give a line number");
my $filestub = 'paramspace.dat';
my $file = $dir.'/'.$filestub;

if(!-s -f -r $file)
{
    print STDERR "Cannot file $file or it has zero size.\n";
    exit;
}
if($n<1)
{
    print STDERR "Line number must be >= 1\n";
    exit;
}

print "Run paramspace at $file line $n\n";

my @paramspace;
tie @paramspace,'Tie::File',$file,mode=>O_RDONLY,recsep=>"\n" 
    or die("cannot open $file for reading");


my $system = $paramspace[$n-1];
$system=~s/^\s+//; # just in case
print "System is $system\n";

my ($M0,$M1,$a,$P,$stellar_type,$lifetime,$final_eccentricity,$prob) =
    split(/\s+/,$system);

my $args = `$ENV{HOME}/progs/stars/binary_c/src/perl/scripts2/cbdiscs.pl show_opts outdir=/dev/null | grep BSE_OPTIONS`;
$args=~s/^BSE_OPTIONS\s+//;
$args=~s/\s+$//;
$args=~s/extra//;
$args=~s/--z/--metallicity/;
$args=~s/--log_fins \d//;
$args=~s/--disc_log\s+\S+//g;
$args=~s/ -- //g;
    
$args = "$args --M_1 $M0 --M_2 $M1 --separation $a --orbital_period 0 --probability $prob --eccentricity 0 --metallicity 0.02 ";
print "ARGS\n$args\n";

my $valgrind = 'valgrind --main-stacksize=30000000 --max-stackframe=30000000 --read-var-info=yes --track-origins=yes --tool=memcheck --leak-check=full --show-reachable=yes --freelist-vol=100000000 --partial-loads-ok=no --undef-value-errors=yes -v --vgdb-error=1';
$valgrind='';

my $pwd = `pwd`; chomp $pwd;

if($pwd eq '/home/izzard/progs/stars/binary_c')
{
    # new build
    $args .= ' --disc_log 2 '; 
}
else
{
    # old build
    $args =~ s/--cbdisc_adapt_Rin_to_L2 \d//;
    $args =~ s/--cbdisc_fail_ring_inside_separation \d//;
    $args =~ s/--cbdisc_inner_edge_stripping \d//;
    $args =~ s/--cbdisc_outer_edge_stripping \d//;
}

$args .= " --comenv_disc_mass_fraction 0.1 --comenv_disc_angmom_fraction -3 ";

# run the system
my $cmd = "$valgrind tbse $args --internal_buffering 0 --log_filename /tmp/disc.log  |grep -v DISC_ |grep -v POSTAGB | grep -v XYIELD|grep -v SINGLE_STAR ";

print "exec: \n\n",color('red'),$cmd,color('white'),"\n\n";
print `$cmd`;

print "You should have lifetime = $lifetime\n";