#!/usr/bin/ksh

# **************************** 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 ************************************


#set -a
set -x

#==================================================
#
# FUNCTIONS
#
#==================================================

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

function getDataForDate
{
set -x

typeset reqDate=$1
typeset reqTime=$2
typeset reqStep=$3

typeset f_etadot=${d_WORK}/etadot.grb
typeset f_etadot_tmp=${d_WORK}/etadot_tmp.grb
typeset f_uvt=${d_WORK}/uvt.grb
typeset f_spz=${d_WORK}/spz.grb


#if [ 1 -eq 0 ]; then

mars <<EOF
retrieve,
  type = fc,
  date = ${reqDate},
  time = ${reqTime},
  step = ${reqStep},
  param = etadot,
  levtype = ml,
  levelist = 1/to/91,
  grid = ${GRID},
  area = ${AREA},
  target = "${d_WORK}/etadot.grb"
EOF

mars <<EOF
retrieve,
  type = fc,
  date = ${reqDate},
  time = ${reqTime},
  step = ${reqStep},
  param = u/v/t,
  levtype = ml,
  levelist = 1/to/91,
  grid = ${GRID},
  area = ${AREA},
  target = "${d_WORK}/uvt.grb"
EOF

mars <<EOF
retrieve,
  type = fc,
  date = ${reqDate},
  time = ${reqTime},
  step = ${reqStep},  
  param = sp/z,
  levtype = sfc,
  grid = ${GRID},
  area = ${AREA},
  target = "${d_WORK}/spz.grb"
EOF

#fi

mv ${f_etadot} ${f_etadot_tmp}
metview4 -b ${macro_ETADOT} ${f_spz} ${f_etadot_tmp} ${f_etadot}

#cat ${f_etadot} ${f_spz} > ${f_etadot_tmp}
#rm -f ${f_etadot}
#${exe_ETADOT} ${f_etadot_tmp} ${f_etadot}
	
typeset valDate=`grib_get -p validityDate -w count=1 ${f_uvt} | cut -c 3-`
typeset valTime=`grib_get -p validityTime -w count=1 ${f_uvt} | awk '{printf("%04d", $1)}' | cut -c 1-2`

cat ${f_uvt} ${f_etadot} ${f_spz} > ${d_WORK}/EN${valDate}${valTime}
rm -f ${f_uvt} ${f_etadot} ${f_etadot_tmp} ${f_spz}

}

#------------------------------------
#
# Check if data is already in place
#
#------------------------------------

function checkInputIsInPlace
{
typeset inputIsInPlace=0
if [ -f $f_AVAILABLE -a -f $f_METVIEW_INFO ] 
then
   if [ "x`grep DATE $f_METVIEW_INFO | cut -d "=" -f 2`" = "x$DATE" -a \
        "x`grep TIME $f_METVIEW_INFO | cut -d "=" -f 2`" = "x$TIME" -a \
        "x`grep STEP $f_METVIEW_INFO | cut -d "=" -f 2`" = "x$STEP" -a \
        "x`grep AREA $f_METVIEW_INFO | cut -d "=" -f 2`" = "x$AREA" -a \
	"x`grep GRID $f_METVIEW_INFO | cut -d "=" -f 2`" = "x$GRID" ] 
   then
      inputIsInPlace=1  
      while read line
      do
        if [ `echo $line | grep -c EN` -eq 1 -a \
             ! -f ${d_OUTPUT}/`echo $line | awk '{print $3}'` ]	
        then 
	   inputIsInPlace=0
	   break
       fi
   done <  $f_AVAILABLE
   fi
fi

 return $inputIsInPlace
}

#==================================================
#
# MAIN PART
#
#==================================================

#---------------------------------------
# Get arguments
#---------------------------------------

f_PAR=
doCheckOnly=0
doCheck=1

set -- `getopt p:cf "$@"`
if [ $# -lt 1 ] ; then
   echo "Getopt failed to read arguments!"
   exit 1	
fi

while [ $# -gt 0 ]
do
    case "$1" in
        -p)  f_PAR="$2"; shift;;
        -c)  doCheckOnly=1;;
	-f)  doCheck=0;;
	--)  shift; break;;
	-*)
                echo >&2 \
		"Usage: $0 -p file [-c] [-f]"
		exit 1;;
	*)	break;;
    esac
    shift
done

#---------------------------------------------------------------
# Include the control parameters set via the Metview interface
# d_WORK, d_OUTPUT, f_AVAILABLE,  DATE, TIME, STEP, AREA, GRID
#---------------------------------------------------------------

if [[ "x$f_PAR" != x && -f $f_PAR ]] ; then
   . $f_PAR
else
   echo "No parameter file found: " $f_PAR	
   exit 1
fi

#---------------------------------------
# Init control parameters
#---------------------------------------

#d_WORK=
#d_OUTPUT=
#DATE=20111114
#TIME=0000
#STEP=0/3/6/9/12/15/21/24/27/30/33/36
#AREA=31.17/-28.56/70.77/31.53
#GRID=1/1

#---------------------------------------
# Paths
#---------------------------------------

#f_AVAILABLE=${d_OUTPUT}/AVAILABLE
f_METVIEW_INFO=${d_OUTPUT}/mv_info.txt
#exe_ETADOT=${MV_FLEXTRA_ETADOT_EXE}

#-------------------------------------
# Check if data is already in place
#-------------------------------------

if [ $doCheckOnly -eq 1 ] ; then
  
   checkInputIsInPlace
   if [ $? -eq 1 ] ; then 
	echo "All the needed files are already in place!"
	exit 0
   else
        exit 1
   fi
	 		
elif [ $doCheck -eq 0  ] ; then
   
   checkInputIsInPlace
   if [ $? -eq 1 ] ; then 
        echo "All the needed files are already in place!"
	exit 0
   fi
fi


#-----------------------------
# Further checks
#-----------------------------

#if [ "x${exe_ETADOT}" = x -o  ! -f $exe_ETADOT ] ; then   
#   echo "No etadot executable found: " $exe_ETADOT	
#   exit 1
#fi
#
#if [ ! -x $exe_ETADOT ] ; then   
#   echo "Etadot executable cannot be run! Permission is missing. " $exe_ETADOT
#   exit 1
#fi

#---------------------------------------
# Check directories
#---------------------------------------

[[ ! -d $d_WORK ]] && mkdir -p $d_WORK
[[ ! -d $d_OUTPUT ]] && mkdir -p $d_OUTPUT

#---------------------------------------
# Create Metview macro to modify etadot
#---------------------------------------

macro_ETADOT=${d_WORK}/mv_modify_etadot.mv

cat > ${macro_ETADOT} <<EOF
#Metview Macro

 print("hello")

 x=arg()
 if count(arg) <> 3 then
   fail("")
 end if
 
 sp=read(x[1])
 etadot=read(x[2])
 outFile=x[3]

 res=mvl_flextra_etadot(sp,etadot)
 write(outFile,res)

EOF

#-----------------------------
# Loop for the steps
#-----------------------------

#Split steps
SAVEIFS=$IFS
IFS="/"
set -A steps $STEP
IFS=$SAVEIFS

#Loop for each step
for ts in ${steps[*]} ; do

	#echo "getDataForDate  $DATE $TIME $ts"
	getDataForDate  $DATE $TIME $ts 
done


#--------------------------------------
# Generate the AVIALABLE file and
# move the results to the output dir
#--------------------------------------

cd ${d_WORK}

SAVEIFS=$IFS
IFS=$'\n'

cat > ${f_AVAILABLE} <<EOF
DATE      TIME     FILNAME     SPECIFICATIONS
YYYYMMDD  HHMISS
_____________________________________________
EOF

#for f in  $(find . -mindepth 1  -name "EN*" -type f)  ; do

for f in  `ls EN*` ; do

  echo "file: " $f

  f_name=`basename $f`	
  f_date=`grib_get -p validityDate -w count=1 $f`
  f_time=`grib_get -p validityTime -w count=1 $f`
  f_time=`echo $f_time | awk '{printf(" %04d", $1)}'`00

  cat >> ${f_AVAILABLE} << EOF
${f_date} ${f_time}    ${f_name}      ON DISC
EOF

  mv -f $f ${d_OUTPUT}

done
IFS=$SAVEIFS

#--------------------------------------
# Generate the metview info file
#--------------------------------------

cat > ${f_METVIEW_INFO} <<EOF
DATE=$DATE
TIME=$TIME
STEP=$STEP
AREA=$AREA
GRID=$GRID
EOF

exit 0
