#!/usr/bin/env perl

BEGIN {
	push @INC, "/home/serbin/BIORUN8";
}

use File::Copy;
use File::Path;
use Getopt::Long;
use MatrixFun;
use Cwd;


my $dbinstalllog =  "preexecrun.out";
print "Trying to open logfile... $dbinstalllog\n";
open(OLDOUT, ">&STDOUT");
open(OLDERR, ">&STDERR");
open(STDOUT, ">>$dbinstalllog") or die "Could not open $dbinstalllog: $!";
open(STDERR, ">&STDOUT");
select(STDERR);
 $| = 1;
select(STDOUT);
 $| = 1;

my $batchsz = $ARGV[0];
my $width = $ARGV[1];
my $here = getcwd();

print "Batchsz is <$batchsz>\n";
my $basecsv = "zPred_";
my $basemat = "runFile_";
my $jfolders = "crunch";
# How many data files are there?
my $zpreds = `ls $basecsv*`;
my @work = split /\s/, $zpreds;
my $worksz = @work;
# How many job folders?
my $crunches = `ls $jfolders*`;
my @jobs = split /\s/, $crunches;
my $jobsz = @jobs;

print "<$worksz> pieces of work to do\n";
print "<$jobsz> jobs for this level\n";

# get job data to job folder
my $counter = 1;
my $crunchcounter = 1;
my $transfers = "";
for (1 .. $worksz) {
	my $placefolder = "crunch" . "$crunchcounter";
	my $place = "$basecsv" . "$counter.csv";
	my $placealso = "$basemat" . "$counter.mat";
	system("cp $place $placefolder");
	system("cp $placealso $placefolder");
	$transfers = "$transfers" . "$place,$placealso,";
	print "Move $place and $placealso to $placefolder\n";
	if((($counter % $batchsz) == 0) or ($counter == $worksz)) {
		# Note: Dag built with marker for insert
		# at this time of correct files to transfer
		my $crunchfolder = "$jfolders$crunchcounter";
		chdir("$crunchfolder");
		RewriteSubmitTransfers("crunch.cmd","$transfers");
		chdir("$here");
		$crunchcounter += 1;
		$transfers = "";
	}
	$counter += 1;
}


# rewrite submit files

exit(0);

sub RewriteSubmitTransfers
{
	my $submitfile = shift;
	my $transfers = shift;

	my $line = "";
	open(IN,"<$submitfile") or die "Failed to open submit<$submitfile>:$!\n";
	open(OUT,">$submitfile.new") or die "Failed to open new submit<$submitfile.new>:$!\n";
	while(<IN>) {
		chomp();
		$line = $_;
		if($line =~ /^(.*?)XXXXXXXX(.*)$/) {
			print OUT "$1$transfers$2\n";
		} elsif($line =~ /^.*WantFlocking.*$/) {
			print OUT "+WantGlidein = true\n";
		} else {
			print OUT "$_\n";
		}
	}
	close(IN);
	close(OUT);
	system("mv $submitfile $submitfile.old");
	system("mv $submitfile.new $submitfile");
}
