#!/bin/bash

# SEED, SOFTWARE, AND SEARCH PARAMETERS
n_min=1
n_max=4
w_min=3
w_max=16
l_min=1
l_max=64
r=1000

AWK='gawk'
SED='gsed'
CAT='cat'
GREP='grep'
SORT='sort'
UNIQ='uniq'

seed_enumeration="reopt"; # "full" / "random" / "reopt"

for ((t=0; t<1; t++))
do
    for ((n=${n_min}; n<=${n_max}; n++))
    do
        for ((w=${w_min}; w<=${w_max}; w++))
        do
            for ((l=${l_min}; l<=${l_max}; l++))
            do
                s=$((2*$w));

                # FIXME CHECK THIS CONTROL, AND UPDATE TO BETTER VALUE WHEN n=1 or n >= w-1 ...
                if [ ${s}  -gt  ${l} ];
                then
                    continue
                fi

                # run iedera in incremental (-r -k ) / full mode (no -r and no -k) / reoptimization mode (find seeds from other alignment lengths ... and reinject them)
                outfile="./experiments/_n${n}_w${w}_s${s}_l${l}";
                case ${seed_enumeration} in
                    full)
                        echo "full enumeration"
                        nice -n+19 ./iedera -spaced -BSymbols '01'         -n ${n} -w ${w},${w} -s ${w},${s} -l ${l}                              -o ${outfile}.ied
                        ;;
                    random)
                        echo "random enumeration"
                        p=`$AWK 'BEGIN {srand(); p=rand(); printf("%g,%g", p , 1-p); }'`; echo ${p};
                        nice -n+19 ./iedera -spaced -BSymbols '01' -f ${p} -n ${n} -w ${w},${w} -s ${w},${s} -l ${l} -r ${r} -k -e ${outfile}.ied -o ${outfile}.ied
                        ;;
                    reopt)
                        echo "reoptimize from other alignment lengths their current seeds on this alignment length"
                        w_1=$(($w - 1))
                        n_1=$(($n - 1))
                        ${CAT} ./experiments/_n${n}_w${w}_s${s}_*.ied | ${GREP} -E "^1(0*1){${w_1}}(,1(0*1){${w_1}}){${n_1}}\s" |  ${GREP} -vE "^$" | ${SED} 's/^\([10,]*\).*$/\1/' | ${SORT} | ${UNIQ} | (
                                while read line;
                                do
                                    p=`$AWK 'BEGIN {srand(); p=rand(); printf("%g,%g", p , 1-p); }'`;
                                    echo "reoptimize from seed \"${line}\" with probability \"${p}\""
                                    nice -n+19 ./iedera -spaced -BSymbols '01' -f ${p} -n ${n} -w ${w},${w} -s ${w},${s} -l ${l} -r ${r} -k -e ${outfile}.ied -o ${outfile}.ied -m ${line}
                                done
                            )
                        ;;
                    *)
                        echo "no enumeration ... next step"
                        ;;
                esac
            done
        done
    done
done
