#!/usr/bin/perl
use strict;

my $sims = 1000;

for  (my $n = 1; $n <= $sims; $n++) {
#warn "$n run\n";
my $number = int(rand(15000)) + 1;
$number *= 1000;
$number += 3500000;
my $command = "snps_in_intervals --input_file ClassifiedAndCleanMergesReduced.txt --default_type 'a.intergenic' --output_file shifted.txt --offset $number";
#my $command = "snps_in_intervals  --input_file test --output_file shifted.txt -O $number";

warn "run $n - $command\n";

my $head = "qtl	chr	geneid	gene.type	marker	pos	merge	happy	peak	marker.type	rmip	max.happy	max.merge	coding.function	boot.merge	boot.peak	max.boot.merge";

SpawnProcess($command);


my $command = "awk ' \$11 > 0.6 ' shifted.txt > gt5.txt";
#warn "$command";
SpawnProcess($command);
open (OUT, ">lt5.txt") || die "can't write to lt5.txt\n";
print OUT "$head\n";
close (OUT);

my $command = "awk ' \$11 < 0.5 ' shifted.txt  >> lt5.txt";
SpawnProcess($command);

my $rcommand = "R --vanilla < analyse.gt.R "; 
#print "$rcommand\n";

my @out = SpawnProcess($rcommand);
for (my $m = 38; $m <= $#out; $m++) {
print "GT\toffset $number\trun $n\t$out[$m]";

}


my $rcommand = "R --vanilla < analyse.lt.R ";
#print "$rcommand\n";

my @out = SpawnProcess($rcommand);
for (my $m = 38; $m <= $#out; $m++) {

print "LT\toffset\t$number\trun $n\t$out[$m]";
}

}

sub SpawnProcess {

    my ($command)=@_;
   open(PROCESS, "$command 2>&1 |")
        || warn "spawn couldn't open \"$command\": $!\n"
            && return;

    my(@output)=<PROCESS>;

    close (PROCESS);
    my $status=($? >> 8);

    if ( $status != 0 ) {
        warn " spawn \"$command\" returned non-zero exit status: @output\n";
    }

    return (@output);

}



