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

#################################################################################
## Compute monthly mean from daily OSTIA (0.05x0.05deg)
## Original data: Global Ocean OSTIA Sea Surface Temperature and Sea Ice Reprocessed
## DOI: https://doi.org/10.48670/moi-00168
## Period: 1 Oct 1981 to 31 May 2022
##
## Created by Mariko Koseki, xx/04/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


# Move into original data
TMPDIR='original/SST_GLO_SST_L4_REP_OBSERVATIONS_010_011/METOFFICE-GLO-SST-L4-REP-OBS-SST_202003/'

cd $TMPDIR

ORGDIR=$(pwd)

# Download 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 filelist2
    for day in $(seq -f "%02g" 01 $ndays)
    do
      #echo "File name:"
      #echo ${year}${month}${day}120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc
      if [ -e ${year}${month}${day}120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc ]
      then 
	echo ${year}${month}${day}120000-UKMO-L4_GHRSST-SSTfnd-OSTIA-GLOB_REP-v02.0-fv02.0.nc>>filelist2
      else
	echo "no files"
      fi 
    done
    #exit 0


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

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

    ### Calculate standard error and save it as a separate output file (err.nc) ###
    echo "step2"
    #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}_hires.nc err_hires.nc  #use "awk" instead of "bc"

    ### Append standard error ###
    echo "step3"
    ncks -A -v analysis_error err_hires.nc ${year}_${month}_hires.nc

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

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

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

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


    ### change FillValue ###
    echo "step5"
    
    ncap2 -O -s 'where(err<-32760) err=-999.' ${year}_${month}_hires.nc ${year}_${month}_hires.nc

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


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

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

    ### Add FillValue and missing value for icec ###
    ncatted -a _FillValue,icec,o,f,-999. -a missing_value,icec,o,f,-999. ${year}_${month}_hires.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}_hires.nc
    

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

    ### Append variables ###
    echo "step7"
    ncks -A -v sst temp_output_hires.nc ${year}_${month}_hires.nc
    ncks -A -v err err_output_hires.nc ${year}_${month}_hires.nc


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

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


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

echo "Completed!!" 
