#!/bin/bash 
set -eu
###
### Globals for this script
###

START=$(pwd) # The folder containing the script will be the root folder. This will avoid the script from breaking when called from a full path
OUTDIR="${START}/../output"

MODEL="gfs" #to be used in $FILENAME see Main
TVAL=00
EXTEN='.dump'
#wgrib PATH must be defined (/apps/GRADS/2.0.2/bin/wgrib)
FILENAME="Set_for_code_readability"
INPUT_FOLDER="Set_for_code_readability"
INITIME="Set_for_code_readability"
ENDTIME="Set_for_code_readability"
INT="Set_for_code_readability"


###
### Functions
###

#######################################
# Clean previous files (i.e.: another day)
#
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   None
#######################################
function clean_previous_output() {
  if [ -d "${START}" ]; then
    cd ${START}
    rm -f out_eraconv.log
  else
    echo "[ERROR] Degrib input folder ${START} doesn't exist in clean_previous_output"
    exit 1
  fi
}


#######################################
# Compile degrib2model_driver
#
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   None
#######################################
function compile_degrib2model() {
  cd ${START}
  gfortran -g -O era2modelWrh_rrtm.f -o era2modelWrh_rrtm.exe
  if [ ! -f era2modelWrh_rrtm.exe ]; then
    echo "[ERROR] Result of compilation for degrib2model not found at: ${START}"
    exit 1
  fi
}


#######################################
# Convert degribbed data to unformatted format for local area model use (run degrib2model)
#
# Globals:
#   $EXTEN
# Arguments:
#   $1 current $TVAL at dump_data_grib()
# Returns:
#   None
#######################################
function run_degrib2model() {
  # 
  echo " "
  echo " Start degrib to formatted data conversion process for timestep " $TVAL
  echo " "
 
  ${START}/era2modelWrh_rrtm.exe $TVAL >> out_eraconv.log || exit 1

  #this might be big, let's first list, then remove it
  ls -l ${OUTDIR}/*$EXTEN
  rm -f ${OUTDIR}/*$EXTEN

  ls -1 ${OUTDIR}/*.gfs > flist  #REVIEW, seems "flist" is an unused file!
}


#######################################
# Dump data: read files from hours $TVAL to $ENDTIME, process it
# (dump variables from gribfile) for the degribber
#
# For futher info about the records contained in the analysis, see the corresponding inventories:
# http://www.nco.ncep.noaa.gov/pmb/products/gfs/gfs_upgrade/gfs.t06z.pgrb2.0p50.f000.shtml
# http://www.nco.ncep.noaa.gov/pmb/products/gfs/gfs_upgrade/gfs.t06z.pgrb2.0p50.f006.shtml
#
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   None
#######################################
function dump_data_grib() {
  #declare -a LEVELS_1000TO10=('1000' '975' '950' '925' '900' '850' '800' '750' '700' '650' '600' '550' '500' '450' '400' '350' '300' '250' '200' '150' '100' '70' '50' '30' '20' '10');
  #declare -a LEVELS_1000TO100=('1000' '975' '950' '925' '900' '850' '800' '750' '700' '650' '600' '550' '500' '450' '400' '350' '300' '250' '200' '150' '100');
  cd ${START}
  echo "Read hours from ${TVAL} to ${ENDTIME}"

    filename1='ERAINT2D_'${iyear}'.grb'
    filename2='ERAINT3D_'${iyear}'.grb'
    GRIBFILE1=${INPUT_FOLDER}/${filename1}
    GRIBFILE2=${INPUT_FOLDER}/${filename2}
	echo "Initial date" ${iyear} ${imonth} "number of hours " ${ENDTIME}
	echo "Using files: " ${GRIBFILE1} ${GRIBFILE2}


  while [ ${TVAL} -le ${ENDTIME} ]
  do
    echo "Processing Hour ${TVAL}"
    if [ ${TVAL} -lt 10 -a ${TVAL} != 00 ]; then
      TVAL=0${TVAL}
    else
      TVAL=${TVAL}
    fi

    echo " ***************************************************"
    echo " **********  GRIB grid processor *******************"
    echo " ****** Dump data from ${GRIBFILE1} file *****"
    echo " ******         DEALING WITH 2D DATA           *****"
    echo " ***************************************************"

    if [ ! -e ${GRIBFILE1} ]; then
      echo "[ERROR] Missing input file ${GRIBFILE1}"
      exit 1
    fi

    # GETTING DATE
    date=`date -ud "$iyear$imonth$iday ${INITIME}00 + $TVAL hours" +%y%m%d%H`
    echo "Processing date $date"
    echo $date > date.txt
    # GETTING DATA
    inv_file=content2.txt.${iyear}
    vars="STL SWVL"
    levs=""0-7" "7-28" "28-100" "100-255""

	for var in ${vars}
	do  # Loop for 2D variables (at each soil depth in cm) 
		for lev in ${levs}
		do
		  if [ $var = STL -a $lev = "0-7" ]
		  then
		    name="SOILT1"
		  fi
		  if [ $var = STL -a $lev = "7-28" ]
		  then
		    name="SOILT2"
		  fi
		  if [ $var = STL -a $lev = "28-100" ]
		  then
		    name="SOILT3"
		  fi
		  if [ $var = STL -a $lev = "100-255" ]
		  then
		    name="SOILT4"
		  fi
		  if [ $var = SWVL -a $lev = "0-7" ]
		  then
		    name="SOILW1"
		  fi
		  if [ $var = SWVL -a $lev = "7-28" ]
		  then
		    name="SOILW2"
		  fi
		  if [ $var = SWVL -a $lev = "28-100" ]
		  then
		    name="SOILW3"
		  fi
		  if [ $var = SWVL -a $lev = "100-255" ]
		  then
		    name="SOILW4"
		  fi
		# echo "Degribbing " $name $var $lev
		    grep d=$date $inv_file | grep ":"$var | grep $lev | wgrib -i $GRIBFILE1 -o $OUTDIR/"$TVAL"_$name$EXTEN > /dev/null
		done
	done


    vars="SKT SD CI MSL"
    levs=""sfc""

	for var in ${vars}
	do  # Loop for 2D variables (at each soil depth in cm) 
		for lev in ${levs}
		do
		  if [ $var = SKT -a $lev = "sfc" ]
		  then
		    name="SST_TS"
		  fi
		  if [ $var = SD -a $lev = "sfc" ]
		  then
		    name="WEASD"
		  fi
		  if [ $var = CI -a $lev = "sfc" ]
		  then
		    name="ICEC"
		  fi
		  if [ $var = MSL -a $lev = "sfc" ]
		  then
		    name="PRMSL"
		  fi
		# echo "Degribbing " $name $var $lev
		    grep d=$date $inv_file | grep ":"$var":" | grep ":"$lev | wgrib -i $GRIBFILE1 -o $OUTDIR/"$TVAL"_$name$EXTEN > /dev/null
		done
	done

	echo " *******DEALING WITH 3D DATA*******************************"
    if [ ! -e ${GRIBFILE2} ]; then
      echo "[ERROR] Missing input file ${GRIBFILE2}"
      exit 1
    fi
	# GETTING DATE
	#        wgrib -s $GRIBFILE2 | head -1 | cut -d: -f3 | cut -d= -f2 > date2.txt
	# GETTING DATA

	inv_file=content.txt.${iyear}
	vars="T U V Z R CLWC"
	levs="1000 975 950 925 900 875 850 825 800 775 750 700 650 600 550 500 450 400 350 300 250 225 200 175 150 125 100 70 50 30 20 10 7 5 3 2 1"
	echo $levs

	for var in ${vars}
	do # Loop for 2D variables (at each soil depth in cm) 
		for lev in ${levs}
		do
		  if [ $var = T ]
		  then
		    name="TT"
		    units="mb"
		  fi
		  if [ $var = U ]
		  then
		    name="UU"
		    units="mb"
		  fi
		  if [ $var = V ]
		  then
		    name="VV"
		    units="mb"
		  fi
		  if [ $var = Z ]
		  then
		    name="HH"
		    units="mb"
		  fi
		  if [ $var = R ]
		  then
		    name="SH"
		    units="mb"
		  fi
		  if [ $var = CLWC ]
		  then
		    name="CW"
		    units="mb"
		  fi
		# echo "Degribbing " $name $var $lev $units
		    grep d=$date $inv_file | grep ":"$var":" | grep ":"$lev" "$units | wgrib -i $GRIBFILE2 -append -o $OUTDIR/"$TVAL"_$name$EXTEN > /dev/null
		done
	done

    # Convert degribbed data to unformatted format for local area model use:
    run_degrib2model ${TVAL}

    TVAL=$((${TVAL} + ${INT}))
  done
}


#######################################
# Clean temporary files generated by dump_data_grib and degrib
#
# Globals:
#   None
# Arguments:
#   None
# Returns:
#   None
#######################################
function clean_temp_files() {
  cd ${START}
  rm -f gfsconv.out
  rm -f date.txt
  rm -f gfs2model_rrtm.exe
}


###
### Main
###

#######################################
# Reads and checks the arguments, then calls rest of the script
# Globals:
#   None
# Arguments:
#   $1 Initial time of analysis (the 00 between t and z in the GFS/FNL filename: gfs.t00z.pgrbf00)
#   $2 Endtime (lenght of the forecast in hours)
#   $3 Frequency of boundary conditions update (hours)
#   $4 Type of analysis input file (pgrbf in the GFS/FNL filename: gfs.t00z.pgrbf00)
#   $5 Input folder where analysis files are (like gfs.tXXz.pgrbfYY)
# Returns:
#   None
#######################################
ME=`basename "$0"`
if (( "$#" != 8 )); then
  echo "[ERROR] Wrong call: $# arguments were passed, 8 arguments needed. Usage: ./$ME %HOUR% %NHOURS% BOCOS pgrbf ../output YEAR MONTH DAY"
  exit 1
else
  if [ $1 -eq $2 ]; then
    echo "[WARNING] (Disregard when running a GLOBAL job) Endtime (lenght of the forecast in hours) is the same as Initial time of analysis"
  fi
  # Set global variables:
  INITIME=${1}
  ENDTIME=${2}
  INT=${3}
  FILENAME=${MODEL}.t${INITIME}z.${4}  #ERA: NOT USED. Constructs gfs.t00z.pgrbf
  INPUT_FOLDER=${5}  #ERA: NOT USED. 

  folder=/gpfs/projects/bsc32/bsc32009/ERAINT/
  iyear=${6}
  imonth=${7}
  iday=${8}

  clean_previous_output
  compile_degrib2model
  dump_data_grib
fi
exit 0
