#!/bin/bash -e
set -o nounset
set -o errexit

#################################################################################
## Interpolate daily OSTIA (0.05x0.05deg) into monthly data (1x1deg)
##
## Ver1.0: Created by Mariko Koseki, 06/05/2025
#################################################################################

## User input ##
if [ $# -eq 2 ] #check number of arguments
then 
  start_year=$1
  start_month=$2
  end_year=$1
  end_month=$2
elif [ $# -eq 4 ]
then 
  start_year=$1
  start_month=$2
  end_year=$3
  end_month=$4
else
  echo "usage: $0 <year> <month> " 
  echo "       or "
  echo "       $0 <year1> <month1> <yearn> monthn> "
  exit 0
fi


## Grid file ##
GRIDDES=`pwd`/grid_360x180.txt


## Select dataset ##
# Dataset name: Global Ocean OSTIA Sea Surface Temperature and Sea Ice Reprocessed
#  Product ID: SST_GLO_SST_L4_REP_OBSERVATIONS_010_011
#  Dataset ID: METOFFICE-GLO-SST-L4-REP-OBS-SST
#  DOI: https://doi.org/10.48670/moi-00168
#  Spatial resolution: 0.05° × 0.05°
#  Period: 1 Oct 1981 to 31 May 2022

# Dataset name: Global Ocean OSTIA Sea Surface Temperature and Sea Ice Analysis
#  Product ID: SST_GLO_SST_L4_NRT_OBSERVATIONS_010_001
#  Dataset ID: METOFFICE-GLO-SST-L4-NRT-OBS-SST-V2
#  DOI: https://doi.org/10.48670/moi-00165
#  Spatial resolution: 0.05° × 0.05°
#  Period: 1 Jan 2007 to present


dataset='nrt'
#dataset='rep'


if [ ${dataset} = 'rep' ]
then
  datasetID='METOFFICE-GLO-SST-L4-REP-OBS-SST'
  data_path='SST_GLO_SST_L4_REP_OBSERVATIONS_010_011/METOFFICE-GLO-SST-L4-REP-OBS-SST_202003/'
  filename='120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc'

elif [ ${dataset} = 'nrt' ]
then
  datasetID='METOFFICE-GLO-SST-L4-NRT-OBS-SST-V2'
  data_path='SST_GLO_SST_L4_NRT_OBSERVATIONS_010_001/METOFFICE-GLO-SST-L4-NRT-OBS-SST-V2/'
  filename='120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB-v02.0-fv02.0.nc'

else
  echo "no such data"
fi
 
echo "ID:" ${datasetID}
echo ""




## Move into original data ##
TMPDIR='original/'${data_path}
cd $TMPDIR

ORGDIR=$(pwd)

## Read daily files ##
echo "Mapping files..."

cd $ORGDIR

for year in $(seq -f "%04g" $start_year $end_year)
do
  cd ${ORGDIR}/${year}

  PWDDIR=$(pwd)
  echo $PWDDIR

  for month in $(seq -f "%02g" $start_month $end_month)
  do
    cd ${ORGDIR}/${year}/${month}
    PWDDIR=$(pwd)
    echo $PWDDIR


    ndays=$(cal ${month} ${year} | awk 'NF {DAYS = $NF}; END {print DAYS}')
    echo $ndays
    echo ${ndays} |awk '{printf "%.3f\n", 1/sqrt($1)}'


    rm -f filelist
    for day in $(seq -f "%02g" 01 $ndays)
    do
      #echo "File name:"
      #echo ${year}${month}${day}${filename}      
      if [ -e ${year}${month}${day}${filename} ]
      then 
	echo ${year}${month}${day}${filename}>>filelist
      else
	echo "no files"
      fi 
    done
  #exit 0


    ### Define dim as record dimension in output file ###
    #'''
    #if first time post-processing
    #'''
    echo "step0"
    for fl in `cat filelist`; do
      ncks -O --mk_rec_dmn time $fl $fl
    done

    ### Calculate monthly mean ###
    echo "step1"
    ncra -O -o ostia.${year}${month}.nc `cat filelist`
    

    ### Remapping: 0.05 degree -> 1 degree ###
    echo "step2"
    cdo -remapcon,$GRIDDES ostia.${year}${month}.nc ${year}_${month}.nc

    ### Calculate standard error and save it as a separate output file (err.nc) ###
    echo "step3"
    #cdo -mulc,`echo "scale=3;1/sqrt(${ndays})" | bc` -selvar,analysis_error ${year}_${month}.nc err.nc  #bc: command not found
    cdo -mulc,`echo ${ndays} |awk '{printf "%.3f", 1/sqrt($1)}'` -selvar,analysis_error ${year}_${month}.nc err.nc  #use "awk" instead of "bc"

    ### Append standard error ###
    echo "step4"
    ncks -A -v analysis_error err.nc ${year}_${month}.nc

    ### Calculate weighted average ###
    #echo "step6"
    #ncwa -O -a zlev ${year}_${month}.nc ${year}_${month}.nc # no zlevel in files

    ### Rename variable ###
    echo "step5"
    ## sea_ice_fraction -> icec ###
    ncrename -v sea_ice_fraction,icec ${year}_${month}.nc

    ## analysis_error -> err ###
    ncrename -v analysis_error,err ${year}_${month}.nc

    ## analysed_sst -> sst ###
    ncrename -v analysed_sst,sst ${year}_${month}.nc


    ### change FillValue ###
    echo "step6"

    ncap2 -O -s 'where(err<-32760) err=-999.' ${year}_${month}.nc ${year}_${month}.nc

    ncatted -a _FillValue,,o,f,-999. -a missing_value,,o,f,-999. ${year}_${month}.nc


    ### Delete FillValue and missing value for icec ###
    ncatted -a _FillValue,icec,d,, -a missing_value,icec,d,, ${year}_${month}.nc

    ### Sea ice concentration ###
    ncap2 -O -s 'where(sst>-2. && icec==-999.) icec=0.; where(icec>0.) icec=icec*100.;' ${year}_${month}.nc ${year}_${month}.nc

    ### Add FillValue and missing value for icec ###
    ncatted -a _FillValue,icec,o,f,-999. -a missing_value,icec,o,f,-999. ${year}_${month}.nc

    ### Add add_offset and scale_factor for sst and icec ###
    ncatted -a add_offset,sst,o,f,0. -a scale_factor,sst,o,f,1. -a add_offset,icec,o,f,0. -a scale_factor,icec,o,f,1. ${year}_${month}.nc


    ### change unit "kelvin" -> "Celsius" ###
    echo "step7"
    cdo -setattribute,sst@units="Celsius" -subc,273.15 -selname,sst ${year}_${month}.nc temp_output.nc
    cdo -setattribute,err@units="Celsius" -selname,err ${year}_${month}.nc err_output.nc

    ### Append variables ###
    echo "step8"
    ncks -A -v sst temp_output.nc ${year}_${month}.nc
    ncks -A -v err err_output.nc ${year}_${month}.nc


    ### Delete eulaVlliF_ for sst and err ###
    ncatted -a eulaVlliF_,sst,d,, ${year}_${month}.nc
    ncatted -a eulaVlliF_,err,d,, ${year}_${month}.nc

    ncatted -O -a _FillValue,sst,o,f,-999. -a missing_value,sst,o,f,-999. ${year}_${month}.nc
    ncatted -O -a _FillValue,err,o,f,-999. -a missing_value,err,o,f,-999. ${year}_${month}.nc


    ### Move NetCDF file to monthly directory ###
    mv ${year}_${month}.nc ../../../../../monthly/1deg/${year}_${month}.nc
    echo "done"
    echo "file has been moved to monthly folder"
    echo " "

    ### Delete files ###
    rm -f ostia.${year}${month}.nc
    rm -f temp_output.nc
    rm -f err_output.nc
    rm -f err.nc

  done
done 

echo "Completed!!" 
