#!/bin/ksh

#
# The original script "create_ECDYN.sh" written by Lionel GUEZ for ERAI
# is available here:
# https://lmdz.lmd.jussieu.fr/utilisateurs/utilisation-de-lmdz
#
# The actual script by Ionela MUSAT is merging the ERA* data
# extracted by the get_ERA.sh script into the 
# ECDYN_${year}${month}${day}_${hour}.nc file.
#
# This script has to be called following the execution of get_ERA.sh
#
# Author: Lionel GUEZ
#
# Changes: Ionela MUSAT, 1st April 2022
#
set -xe

host=$1
yr=$2
mth=$3
day=$4
hr=$5
fout=ECDYN_${yr}${mth}${day}_${hr}.nc

date=${yr}${mth}${day}${hr}
echo create ECDYN.nc for ${date} at ${hr} hour

for var in u v ta r geopt stl1 sp
do
    chmod 600 ${var}.nc
    ncpdq -U --dimension=time,0 --overwrite ${var}.nc \
	${var}_new.nc
done

#
# Get an old ECDYN called ECDYN_high_res.nc and extract the CDSW field from it
#
if [ ! -f ECDYN_high_res.nc ]; then
    echo Copy ECDYN_high_res.nc from https://www.lmd.jussieu.fr/~lmdz/pub/3DInputData/Init
    wget https://www.lmd.jussieu.fr/~lmdz/pub/3DInputData/Init/ECDYN_high_res.nc
else
    echo ECDYN_high_res.nc is here
fi
###
# Get the CDSW field from ECDYN_high_res.nc file
if [ ! -f CDSW_ECDYN_high_res.nc ]; then
    ncks -v CDSW ECDYN_high_res.nc CDSW_ECDYN_high_res.nc
fi
###
# Start from CDSW so that the time value is overwritten:
###
remap=remapcon,stl1_new.nc
cdo $remap CDSW_ECDYN_high_res.nc ${fout}

VARS="u v ta r geopt stl1 sp"
for var in ${VARS}; do
    ncks --append ${var}_new.nc ${fout}
done

ncrename --variable=u,U --variable=v,V --variable=ta,TEMP --variable=r,R \
    --variable=geopt,Z --variable=stl1,ST --variable=sp,SP ${fout}

# Clean up:
for var in ${VARS}; do
    echo $var
    echo \rm ${var}.nc
    echo \rm ${var}_new.nc
done

exit
