#!/bin/bash -x

if [ -z "$7" ]; then
    echo "Usage: arb_dnapars bootstrap searchdepth viewreport randomize transversion_pars threshold_pars interactive"
else
    BOOTSTRAP=$1
    SEARCH=$2
    REPORT=$3
    RANDOMIZE=$4
    TRANSVERSION_PARS=$5
    THRESHOLD_PARS=$6
    INTERACTIVE=$7

    FLAGS=

    if [ "$RANDOMIZE" = "1" ]; then
        RANDOMSEED=$(($RANDOM|1)) # a odd number
        FLAGS="$FLAGS j $RANDOMSEED 1"
    fi

    if [ "$TRANSVERSION_PARS" = "1" ]; then
        FLAGS="$FLAGS n"
    fi

    if [ \! "$THRESHOLD_PARS" = "0" ]; then
        FLAGS="$FLAGS t $THRESHOLD_PARS"
    fi

    case $SEARCH in
        0) FLAGS="$FLAGS" ;;
        1) FLAGS="$FLAGS s n" ;;
        2) FLAGS="$FLAGS s y" ;;
        *)  arb_message "Illegal value for 'searchdepth'"; exit 1 ;;
    esac

    if [ "$BOOTSTRAP" = "0" ]; then
        if [ "$INTERACTIVE" = "0" ]; then
            arb_echo $FLAGS y | dnapars
        else
            (arb_echo $FLAGS; cat -) | ( dnapars ; echo "Press RETURN to continue.." )
        fi
        echo '' >arb_read_tree_args
        arb_message "Please note: Branchlengths generated by DNAPARS have strange scaling (somehow relative to sequence length?)\n"
        WHAT=dnapars
    else
        arb_bootstrap $BOOTSTRAP dnapars $FLAGS
        WHAT=arb_bootstrap/dnapars/consense
    fi

    if [ -f outfile ]; then
        if [ -s outfile ]; then
            if [ "$REPORT" = "1" ]; then
                arb_textedit outfile &
            fi
        else
            arb_message "$WHAT: Error: generated 'outfile' is empty"
            false
        fi
    else
        arb_message "$WHAT: Error: 'outfile' has not been generated"
        false
    fi
fi
