#!/usr/bin/env bash
# Wrapper script for @P@display-matplotlib-py

@MCCODE_BASH_STANDARD_PREAMBLE@

TOOL="@P@display"
UTILDIR="${MCCODE_TOOLDIR}/Python/@P@display/matplotlib"


#NB: miniconda should be installed next to the tool folder:
if [ -d "${MCCODE_TOOLDIR}/../miniconda3" ]; then
    source "${MCCODE_TOOLDIR}/../miniconda3/bin/activate" "${MCCODE_TOOLDIR}/../miniconda3"
    export PATH=${MCCODE_TOOLDIR}/../miniconda3/bin/:$PATH
fi

canrun() {
    if ! [ -x "${UTILDIR}/${TOOL}.py" ]; then
        exit 127;
    fi

    modules="matplotlib"
    cmd=""
    for name in ${modules}; do
        cmd="${cmd}import ${name}; "
    done
    python3 -c "${cmd}"
}

if ( canrun ); then
    arguments=""
    ncountmax="1e2"
    ncount=""
    trace=""
    next=0
    found_ncount=0
    for arg in "${@}"; do
	if [ "${next}" == "1" ];               # We found -n or --ncount in last pass, this is NUMBER
	then
	    ncount=${arg}
	    found_ncount=1
	    next=0
	elif [[ "${arg}" == "-n" ]];           # Case: -n NUMBER (NUMBER is next pass)
	then
	    next=1
	elif [[ "${arg}" == "--ncount" ]];     # Case: --ncount NUMBER (NUMBER is next pass)
	then
	    next=1
	elif
	    [[ ${arg} =~ ^-n ]];               # Case: -nNUMBER
	then
	    ncount=`echo $arg | cut -f2 -dn`
	elif [[ ${arg} =~ ^--ncount= ]];       # Case: --ncount=NUMBER
	then
	    ncount=`echo $arg | cut -f2 -d=`
	    found_ncount=1
	elif [[ ${arg} =~ ^--trace= ]];       # Case: --trace=NUMBER
	then
	    trace=`echo $arg | cut -f2 -d=`
	elif [[ ${arg} =~ ^--help ]];       # Case: --help
	then
	    script=`basename $0`
	    echo ""
	    echo "$script usage:"
	    echo ""
	    echo "$script [--trace=2] [--ncount=1e2] Instrument.instr par1=A par2=B ..."
	    echo "       --trace={1,2} - select classic / new visualisation mode, 2 is default"
	    echo "       --ncount=N    - set number of particles to trace, max/default N=1e2"
	    echo "             -n N "
	    echo "              -nN "
	    echo ""
	    exit
	else
	    arguments="$arguments $arg"
	fi
    done
    if [ "${trace}" == "" ];
    then
	trace="2"
    fi
    if [ "${found_ncount}" == "1" ];
    then
	ncountmax_bc=`echo $ncountmax | sed s/e/\*10^/g`
	ncount_bc=`echo $ncount | sed s/e/\*10^/g`
	if (( $(echo "${ncount_bc} > ${ncountmax_bc}" |bc -l) ));
	then
	    ncount=$ncountmax
	    echo "WARNING from $0: Reduced your ncount to $ncountmax"
	fi
    else
	ncount=$ncountmax
    fi
    @P@run  $* --trace=$trace --no-output-files -n $ncount | python3 ${UTILDIR}/${TOOL}.py
else
    @FLAVOR@_errmsg Failed to run Python ${TOOL} - permissions or missing dependencies\?
fi
