#!/bin/sh

runname="myRun"
executable="./mbmdr-4.4.1.out"
options="--binary"
infile="myBigFile.txt"
nperm=999 # number of permutations
nproc=256 # number of parallel processes
starting_random_seq=1980 # random seed making analysis reproducible
qsuboptions="-q all.q -l h_vmem=2G -l mem_free=2G -cwd"
timeseq="96:00:00" # time needed in (sequential) steps 1 and 3

#############
# Execution #
#############

runName=$runname`date '+%s'`
npermperproc=$(($nperm/$nproc))
nproconemore=$(($nperm-$nproc*$npermperproc))
echo -e '#!/bin/sh\ntime '$executable' $@' > submit1.sh
for x in $(seq 1 $nproc); 
do qsub -N $runName.1 -l h_rt=$timeseq $qsuboptions submit1.sh $options --gammastep1 -i $x -N $nproc $infile
done
qsub -N $runName.2 -hold_jid $runName.1 -l h_rt=$timeseq $qsuboptions submit1.sh $options --gammastep2 -N $nproc $infile
echo -e '#!/bin/sh\ntime '$executable' '$options' -o permut$SGE_TASK_ID.txt -r $(('$starting_random_seq'+$SGE_TASK_ID-1)) $@' > submit2.sh
qsub -N $runName.3a -hold_jid $runName.2 -t 1-$nproconemore -l h_rt=$timeseq $qsuboptions submit2.sh --gammastep3 -p $(($npermperproc+1)) $infile
qsub -N $runName.3b -hold_jid $runName.2 -t $(($nproconemore+1))-$nproc -l h_rt=$timeseq $qsuboptions submit2.sh --gammastep3 -p $npermperproc $infile
echo -e '#!/bin/sh\ntime '$executable' '$options' -r 1980 $@' > submit3.sh
qsub -N $runName.4 -l h_rt=$timeseq -hold_jid $runName.3a,$runName.3b $qsuboptions submit3.sh --gammastep4 -p $nperm -q $nproc -c permut $infile
rm submit*.sh