#!/bin/bash

## Just run code in recipes, use it carefully
## example: use cdo to make cache file. Since cdo is quicker than ncl.
#;DIAG_NORCPM; RUNTHESECODES: echo '    no codes run here.'

## ccipc2 env
module purge
module load cdo_gcc-7.5.0/1.9.8
#
outfile=era5_lsp_cor_ANN.nc
modfile=ens_PRECL_ano.nc
var=lsp
outDJF=${outfile%_ANN.*}_DJF.nc
outMAM=${outfile%_ANN.*}_MAM.nc
outJJA=${outfile%_ANN.*}_JJA.nc
outSON=${outfile%_ANN.*}_SON.nc
test -f ${outfile} && exit 0
## loop for every member
ifiles=$(ls ${d}//lfs/archive/Reanalysis/ERA5/SFC/mon/lsp/ERA5_SFC_lsp_{1982..2020}??_r1440x721_mon.nc)
cdo -O             \
    -select,name=${var} \
    ${ifiles} \
    ERA5_lsp_1982-2020.nc
    
## correlation, need regrid
cdo  -O  \
    -ymonsub ERA5_lsp_1982-2020.nc -ymonmean ERA5_lsp_1982-2020.nc  \
    ERA5_lsp_ano_1982-2020.nc
## Somehow remap is easily crash, should be run along
cdo  -O  \
    -remapbic,${modfile} \
    ERA5_lsp_ano_1982-2020.nc \
    tmp2.nc
cdo  -O -timcor    \
    -selvar,lsp tmp2.nc    \
    -select,name=PRECL ${modfile} \
    ${outfile}
cdo  -O -timcor    \
    -selseason,DJF -selvar,lsp tmp2.nc    \
    -selseason,DJF -select,name=PRECL ${modfile} \
    ${outDJF}
cdo  -O -timcor    \
    -selseason,MAM -selvar,lsp tmp2.nc    \
    -selseason,MAM -select,name=PRECL ${modfile} \
    ${outMAM}
cdo  -O -timcor    \
    -selseason,JJA -selvar,lsp tmp2.nc    \
    -selseason,JJA -select,name=PRECL ${modfile} \
    ${outJJA}
cdo  -O -timcor    \
    -selseason,SON -selvar,lsp tmp2.nc    \
    -selseason,SON -select,name=PRECL ${modfile} \
    ${outSON}
rm -f ERA5_lsp_ano_1982-2020.nc tmp2.nc


