#!/bin/bash

# **************************** LICENSE START ***********************************
#
# Copyright 2012 ECMWF and INPE. This software is distributed under the terms
# of the Apache License version 2.0. In applying this license, ECMWF does not
# waive the privileges and immunities granted to it by virtue of its status as
# an Intergovernmental Organization or submit itself to any jurisdiction.
#
# ***************************** LICENSE END ************************************

# ---------------------------------------------------------
# Script to post process FLEXPART output
# ---------------------------------------------------------

set -x

# ---------------------------------------------------------
# Functions
# ---------------------------------------------------------

check_outCode()
{
    outCode=$1
    if [ $outCode -ne 0 ] ; then
        exit $outCode
    fi
}


print_err()
{
    echo ${text_ERR}  $* >> "${f_LOG}"
}

check_exe()
{
    exe=$1
    exeDesc=$2
    
    if [ x"$exe" = "x" ] ; then
        
        print_err "No $exeDesc is defined."
        exit 1
    fi

    if [ ! -f "$exe" ] ; then
        print_err "No $exeDesc executable found: " $exe
        exit 1
    fi

    if [ ! -x "$exe" ] ; then
        print_err "$exeDesc executable cannot be run! Permission is missing. " $exe
        exit 1
    fi
}

convert_grid()
{
    gridId=$1

    fPattern="grid_${gridId}_*_"
    fTmpPattern="tmp_${gridId}_"

    rm -f ${fTmpPattern}*.grib

    sp=1

    #loop for the species
    while [ $sp -lt 1000 ]   ; do

        spStr=$(printf "%03d" $sp)

        echo "Find output grids for species: " $spStr

        lst=$(ls ${fPattern}${spStr} 2> /dev/null)
        if [ "$lst" == "" ] ; then
            echo "   --> No output found"
            return
        fi

        hasOutput=1

        fRes="${gridId}_s${spStr}.grib"
        if [ -f $fRes ] ; then
            rm -f $fRes
        fi

        echo "Convert output grids to grib"
        for f in $lst ; do

            fTmp=${fTmpPattern}*.grib

            ${f_grid_EXE} header ${gridId} $f ${fTmpPattern} ${forwardSim} $sp
            check_outCode $?

            cat ${fTmp} >> ${fRes}
            rm -f ${fTmp}

        done

        mv ${fRes} ${d_OUT}

        echo "-------------------------------"

        sp=$((sp + 1))

    done
}

convert_flux()
{
    fPattern="grid_flux_??????????????"
    fTmpPattern="tmp_flux_"

    rm -f ${fTmpPattern}*.grib

    lst=$(ls ${fPattern} 2> /dev/null)
    if [ "$lst" == "" ] ; then
        echo "   --> No output found"
        return
    fi

    hasOutput=1

    fResPattern=flux*.grib
    if [ -f $fRes ] ; then
        rm -f $fRes
    fi

    echo "Convert output grids to grib"
    for f in $lst ; do

        fTmp=${fTmpPattern}*.grib

        ${f_grid_EXE} header flux $f ${fTmpPattern} ${forwardSim} $sp
        check_outCode $?

        for t in $(ls $fTmp) ; do
            sp=$(echo $t | cut -d "_" -f 7)
            spStr=$(printf "%03d" $sp)
            fRes="flux_s${spStr}.grib"
            cat ${t} >> $fRes
        done

        rm -f ${fTmp}

    done

    mv ${fResPattern} ${d_OUT}

    echo "-------------------------------"
}

convert_trajectory()
{
    fTr="trajectories.txt"

    if [ ! -f ${fTr} ] ; then
        echo "   --> No output found"
        return
    fi

    hasOutput=1

    echo "Convert output trajectories"

    fResPrefix=tr_r
    fResPattern=${fResPrefix}*.csv

    ${f_tr_EXE}  ${fTr} ${fResPrefix}
    check_outCode $?

    mv ${fResPattern} ${d_OUT}


    echo "-------------------------------"
}

convert_receptor()
{
    recId=$1

    #Flexpart generates receptor_conc or receptor_pptv files.

    fRec="receptor_${recId}"
    fTmpPattern="tmp_receptor_${recId}_"

    rm -f ${fTmpPattern}*.csv

    if [ ! -f ${fRec} ] ; then
        echo "   --> No output found"
        return
    fi

    hasOutput=1

    fResPattern="receptor_${recId}_s"
    rm -f ${fResPattern}*.csv

    ${f_rec_EXE} header dates ${recId} ${fRec} ${fTmpPattern} ${receptorNum}
    check_outCode $?

    #The ouput file names are: ${fTmpPattern}specId_.csv"

    for t in $(ls ${fTmpPattern}*.csv) ; do
        sp=$(echo $t | cut -d "_" -f 4)
        spStr=$(printf "%03d" $sp)
        fRes=${fResPattern}${spStr}.csv
        mv $t ${fRes}
        mv ${fRes} ${d_OUT}
    done

    echo "-------------------------------"
}

#---------------------------------------------------------
# Main part
# ---------------------------------------------------------

text_ERR="Script `basename $0` FAILED> "

#Get args

if [ $# -ne 6 ] ; then
    echo "Invalid number of arguments specified! (" $# " instead of 6)"
    exit 1
fi

d_WORK=$1
f_SIMLOG=$2
f_LOG=$3
d_OUT=$4
forwardSim=$5
receptorNum=$6

f_grid_EXE=${METVIEW_BIN}/flexpartField
f_tr_EXE=${METVIEW_BIN}/flexpartTrajectory
f_rec_EXE=${METVIEW_BIN}/flexpartReceptor

#-------------------------------
# Go to working directory
#-------------------------------

if [ ! -d "$d_WORK" ] ; then
   print_err "No working directory found: " $d_WORK
   exit 1
fi

cd $d_WORK

#--------------------------------
# Clean up
#--------------------------------
rm -f ${f_LOG}

#-------------------------------
# Check/create output dir
#-------------------------------

if [ x"$d_OUT" = "x" ] ; then
   print_err "No output directory is defined!"
   exit 1
fi

if [ ! -d "$d_OUT" ] ; then
   mkdir -p "$d_OUT"
fi

if [ ! -r "$d_OUT" -o ! -x $"$d_OUT" ] ; then
   print_err "The specified output directory is not accessible: " $d_OUT
   exit 1
fi

#-------------------------------
# Check exe
#-------------------------------

check_exe ${f_grid_EXE} "flexpart grid converter"
check_exe ${f_tr_EXE} "flexpart trajectory converter"
check_exe ${f_rec_EXE} "flexpart receptor converter"

#-----------------------------------
# Clean up
#-----------------------------------

rm -f *.grib


#-----------------------------------
# Copy simulation log to output dir
#-----------------------------------

cp -f ${f_SIMLOG} ${d_OUT}

#-----------------------------------
# Convert to grib
#-----------------------------------

hasOutput=0

convert_grid conc
convert_grid pptv
convert_grid time
convert_flux

echo $(pwd)

convert_receptor conc
convert_receptor pptv
convert_trajectory

if [ ${hasOutput} -eq 0 ] ; then
    print_err "No FLEXPART ouput was found!"
    exit 1
fi

echo $(pwd)

exit 0
