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

# Source tutorial run functions
. $WM_PROJECT_USER_DIR/XylemFoam/tools/RunFunctions #Prints log to stdout AND the log.* file
. $WM_PROJECT_DIR/bin/tools/RunFunctions #Prints log to the log.* file only

#- Kill all subprocesses on exit
#jobs=()
#trap '(( #jobs == 0 )) || kill $jobs' EXIT HUP TERM INT
cleanup() {
    # kill all processes whose parent is this process
    #pkill -P $$
    pkill gnuplot
}

for sig in INT QUIT HUP TERM; do
  trap "
    cleanup
    trap - $sig EXIT
    kill -s $sig "'"$$"' "$sig"
done
trap cleanup EXIT

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

#set -o xtrace

startTime=0

#parse 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
            exit 1
        fi
        ;;
esac
done


rm ravdMonitors
rm swirlMonitors

cat <<EOT >> ravdMonitors
set terminal x11
set autoscale

set title "RAVD Monitors"
set ylabel "RAVD"
set xlabel "Time"

while (1) {
EOT

cat <<EOT >> swirlMonitors
set terminal x11
set autoscale

set title "Swirl Angle Monitors"
set ylabel "Swirl Angle"
set xlabel "Time"

while (1) {
EOT

ravdPlotStr='plot '
swirlPlotStr='plot '

firstRAVDLine=true
firstSwirlLine=true

for dir in postProcessing/*/
do
    name=${dir#"postProcessing/"}
    name=${name%"/"}
    re='RAVD_[0-9]+'
    if [[ $name =~ $re ]]; then
        n=${name#"RAVD_"}
        #echo $n
        file="$dir$startTime"/RAVD_RAVD_"$n"
        #- Get the latest log file
        if [ -f "$file"_1.dat ];
        then
            f=1
            while [ -f "$file"_"$((f+1))".dat ]
            do
                f=$((f+1))
            done
            file="$file"_"$f".dat
        else
            file="$file".dat
        fi

        if test -f $file; then
            if [[ $firstRAVDLine == true  ]]; then
                echo 'plot "'${file}'" using 1:3 with lines title "'${name}'", \' >> ravdMonitors
                firstRAVDLine=false
            else
                echo '     "'${file}'" using 1:3 with lines title "'${name}'", \' >> ravdMonitors
            fi
        fi
    fi
    re='SWIRLMETER_[0-9]+'
    if [[ $name =~ $re ]]; then
        n=${name#"SWIRLMETER_"}
        #echo $n
        file="$dir$startTime"/swirlAngle_SWIRLMETER_"$n".dat 
        #- Get the latest log file
        if [ -f "$file"_1.dat ];
        then
            f=1
            while [ -f "$file"_"$((f+1))".dat ]
            do
                f=$((f+1))
            done
            file="$file"_"$f".dat
        else
            file="$file".dat
        fi
        if test -f $file; then
            if [[ $firstSwirlLine == true  ]]; then
                echo 'plot "'${file}'" using 1:3 with lines title "'${name}'", \' >> swirlMonitors
                firstSwirlLine=false
            else
                echo '    "'${file}'" using 1:3 with lines title "'${name}'", \' >> swirlMonitors
            fi
        fi
    fi
    if [[ $name == probes ]]; then
        file="$dir$startTime"/p
        #- get the probe labels at the begining of the file
        mapfile -t -n 20 lines < ${file}
        #echo $lines
        labels=()
        for i in "${lines[@]}"; do
            if [[ $i[0] == /# ]]; then
                labels=( ${labels} ${i#?} )
            else
                break
            fi
        done
        echo $labels
    fi
done

#- Remove the '\' character on the last line
sed '$ s/, \\//' ravdMonitors >> ravdMonitors_
sed '$ s/, \\//' swirlMonitors >> swirlMonitors_

mv ravdMonitors_ ravdMonitors
mv swirlMonitors_ swirlMonitors

echo -e "pause 1\n}" >> ravdMonitors
echo -e "pause 1\n}" >> swirlMonitors

file=postProcessing/residuals/"$startTime"/residuals
#- Get the latest log file
if [ -f "$file"_1.dat ];
then
    f=1
    while [ -f "$file"_"$((f+1))".dat ]
    do
        f=$((f+1))
    done
    file="$file"_"$f".dat
else
    file="$file".dat
fi
foamMonitor -l "$file" &> /dev/null & \
# foamMonitor  postProcessing/probes/"$startTime"/U & \
# foamMonitor  postProcessing/probes/"$startTime"/p &
./monitorVector U &> /dev/null & 
set terminal x11 1
gnuplot -p ravdMonitors &> /dev/null &
# set terminal x11 2
# gnuplot -p swirlMonitors &

tail -f log.$(getApplication)

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