#/bin/ksh
set -evx
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This script adds interpolated and rotated surface wind perturbations to the
# interpolated and rotated surface wind forcing fields.
#
# History : Virginie Guemas - Initial version                         - 2012 
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#                                Arguments
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
year0=2013                   # First year for which to add perturbations
yearf=2014                   # Last year for which to add perturbations
mid='_eraint_'               # '_eraint_' / '_DFS4.3_'
mode=2                       # 1/2 = Bound the perturbations/No bounding
bound=10.0                   # Bounding value for the perturbations
lstmbs=( 1 2 3 4 )           # List of members
lstvars=( 'u10' 'v10' )      # List of variables
pathpert='perturb1_era-dfs_mon'
             # Directory from where to take the perturbations
pathera='/cfu/scratch/vguemas/ERAint_ORCA1t'
pathdfs='/cfu/scratch/vguemas/dfs4.3'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

for ((year=${year0};year<=${yearf};year++)) ; do
  for memb in ${lstmbs[@]} ; do
    for var in ${lstvars[@]} ; do
      cp ${pathera}/${var}${mid}${year}.nc ${var}_${year}.nc
      fileout=${pathera}/${var}_fc${memb}${mid}${year}.nc
      if [[ $mid == '_eraint_' ]] ; then
        suf='_orca1t'
      else
        suf=''
      fi
      case $mode in 
        1) 
        cdo setrtomiss,$bound,100 ${pathpert}/${var}_fc${memb}${mid}${year}${suf}.nc toto1.nc
        cdo setmisstoc,$bound toto1.nc toto2.nc
        cdo setrtomiss,-100,-$bound toto2.nc toto1.nc
        cdo setmisstoc,-$bound toto1.nc toto2.nc
        mv toto2.nc ${var}_fc${memb}${mid}${year}${suf}.nc
        rm -f toto1.nc toto2.nc
        ;;
        2)
        cp ${pathpert}/${var}_fc${memb}${mid}${year}${suf}.nc .
        ;;
      esac
      cdo add -selvar,$var ${var}_${year}.nc -selvar,$var ${var}_fc${memb}${mid}${year}${suf}.nc $fileout 
      rm -f ${var}_${year}.nc ${var}_fc${memb}${mid}${year}${suf}.nc
      if [[ $mid == '_DFS4.3_' ]] ; then
        ncrename -d x,lon -d y,lat $fileout
        ncks -A -v lon,lat ${pathera}/${var}${mid}${year}.nc $fileout
      fi
    done
  done
done
