#!/bin/sh
#cd ${0%/*} || exit 1    # Run from this directory

# Source tutorial clean functions
#. $WM_PROJECT_DIR/bin/tools/CleanFunctions

#set -o xtrace

function usage {
    echo ""
    echo "usage: monitorVelocity QOI [-t startTime]"
    echo "  QOI                Quantity of interest for which to plot probes."
    echo "  -t | --time        simulation start time (default = 0)"
    exit 1
}

startTime=0

if (( $# >= 1 ));
then
    qoi=$1
    shift 1
else
    echo "ERROR: quantity of interest not provided"
    usage
fi

#parse optional arguments
while (( "$#" )); do
case "$1" in
    -t|--time)
        if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
            startTime=$2
            shift 2
        else
            echo "ERROR:  Argument for $1 is missing" >&2
            usage
        fi
    ;;
    * )
        echo "Invalid argument '$1'"
        usage
esac
done


[ -e vectorMonitors* ] && rm vectorMonitors*

#Write gnuplot file header info
cat <<EOF >> vectorMonitors
set terminal x11
set autoscale

set ylabel "${qoi}"
set xlabel "Time [s]"

while (1) {

EOF

#Determine the number of probes to plot and extract point info
file="${PWD}/postProcessing/probes/${startTime}/${qoi}"
re="^# Probe [0-9]+ \(."
nProbes=0
names=()
while IFS= read -r line;
do
    if [[ $line =~ $re ]];
    then
        nProbes=$((nProbes+1))
        names+=("$line")
    else
        break
    fi
done < $file

#for name in "${names[@]}"
#do
#    echo $name
#done
#exit 1

if (("$nProbes" <= 5));
then
    nrows=$nProbes
    ncols=1
else
    nrows=5
    ncols=$((nProbes/nrows))
    ncols=${ncols%.*} # convert float to int
fi

if (("$nProbes" == 0));
then
    echo "ERROR:  No probes were found in log file."
    exit 1
fi

echo 'set multiplot layout '${nrows}', '${ncols} >> vectorMonitors

for ((i=0;i<nProbes;i++));
do
        # Add the plot to the gnuplot script
        # read the ith line ans extract name
        echo ${names[$i]}
        echo 'set title "'${names[$i]}'"' >> vectorMonitors

        x=$((3*(i)+1))
        echo 'plot "< cat '${file}' | tr -d '\''()'\''" using 1:'$((x))' with lines title "x-component", \' >> vectorMonitors
        echo '     "< cat '${file}' | tr -d '\''()'\''" using 1:'$((x+1))' with lines title "y-component", \' >> vectorMonitors
        echo '     "< cat '${file}' | tr -d '\''()'\''" using 1:'$((x+2))' with lines title "z-component" ' >> vectorMonitors >> vectorMonitors
    
done

echo 'pause 1' >> vectorMonitors
echo '' >> vectorMonitors
echo 'unset multiplot' >> vectorMonitors
echo '' >> vectorMonitors
echo '}' >> vectorMonitors
    
gnuplot -p vectorMonitors &


#------------------------------------------------------------------------------
