#!/bin/bash

# # 1) build hmm model
# hmmbuild --rna  --informat afa hmmmodel.hmm alignment.fasta
# # 2) build iedera automaton
# hmmread.pl
# # 3) compile and launch iedera
#g++ *.cc -O3 -march=native -msse4.2 -DUSE_TR1_TYPE_TRAITS=1 -DHAS_STD_TR1_TYPE_TRAITS=1 -DNOSLICER -o iedera-noslicer
#g++ *.cc -O3 -march=native -msse4.2 -DUSE_TR1_TYPE_TRAITS=1 -DHAS_STD_TR1_TYPE_TRAITS=1            -o iedera-slicer
# # 4) the full run ...

# Maximum number of single threads iedera commands
nb_processes=6; #6 processes on a 8 core

TIME_CMD='/usr/bin/time -f "%U"'

# Wait is the maximum number of childs is reached
function wait_max {
    bash_pid=$$
    children=`ps -eo ppid | grep -w $bash_pid`
    num_children=`echo $children | wc -w`
    while (( $num_children  > $nb_processes )) 
    do
	sleep 10;
	children=`ps -eo ppid | grep -w $bash_pid`
	num_children=`echo $children | wc -w`
    done
}


# Sub file function for non positioned seeds
function time_ll_r_n {
    local ll=$1
    local  r=$2
    local  n=$3
    exec >> _run_time_r${r}_ll${ll}_n${n}.csv 2>&1
    for w in 8 9 10 11 12
    do
	local s_w=$w;
	if (( $n > 1 ))
	then
	    s_w=$(($w+1))
	fi
	for (( s=$s_w; s<=2*$w; s++ ))
	do    
	    echo -n -e "$w\t$s\t"
	    eval "$TIME_CMD ./iedera-noslicer -n $n -A 3 -B 2 -M \"{{0,1,1},{0,0,1}}\" -BSymbols '-#' -r ${r} -fF autogen_from_hmm.txt -b 0.00,0.75,0.25 -w $w,$w -s $s,$s -l 1605 -ll ${ll} -n 2 -z 10000 2>&1 | grep -E \"^[0-9.e]*$\" | tr '\n' '\t' "
	    eval "$TIME_CMD ./iedera-slicer   -n $n -A 3 -B 2 -M \"{{0,1,1},{0,0,1}}\" -BSymbols '-#' -r ${r} -fF autogen_from_hmm.txt -b 0.00,0.75,0.25 -w $w,$w -s $s,$s -l 1605 -ll ${ll} -n 2 -z 10000 2>&1 | grep -E \"^[0-9.e]*$\" | tr '\n' '\t' "
	    echo ""
	done
    done
}


# Sub file function for positioned seeds
function timepos_ll_r_n {
    local ll=$1
    local  r=$2
    local  n=$3
    exec >> _run_time_pos_r${r}_ll${ll}_n${n}.csv 2>&1
    for w in 8 9 10 11 12
    do
	for q in 10 20 40 80 160 320 640 1280 
	do
	    local s_w=$w;
	    if (( $n > 1 ))
	    then
		s_w=$(($w+1))
	    fi
	    for (( s=$s_w; s<=2*$w; s++ ))
	    do    
		echo -n -e "$w\t$s\t$q\t"
		eval "$TIME_CMD ./iedera-noslicer -n $n -A 3 -B 2 -M \"{{0,1,1},{0,0,1}}\" -BSymbols '-#' -r ${r} -fF autogen_from_hmm.txt -b 0.00,0.75,0.25 -w $w,$w -s $s,$s -l 1605 -ll $ll -c 1605 -q $q -z 10000 2>&1 | grep -E \"^[0-9.e]*$\" | tr '\n' '\t' "
		eval "$TIME_CMD ./iedera-slicer   -n $n -A 3 -B 2 -M \"{{0,1,1},{0,0,1}}\" -BSymbols '-#' -r ${r} -fF autogen_from_hmm.txt -b 0.00,0.75,0.25 -w $w,$w -s $s,$s -l 1605 -ll $ll -c 1605 -q $q -z 10000 2>&1 | grep -E \"^[0-9.e]*$\" | tr '\n' '\t' "
		echo ""
	    done
	done
    done
}



# Main
for r_param in 100
do
    for n_param in 1 2
    do
	for ll_param in 100 200
	do
	    wait_max
	    timepos_ll_r_n $ll_param $r_param $n_param &
	    wait_max
	    time_ll_r_n $ll_param $r_param $n_param &
	done
    done
done
wait;
