#!/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.'

## ensemble
dir=/cluster/shared/NS9039K/norcpm_ana_hindcast/archive/norcpm1_assim-i1_19800115
avgfile=ens_sst_avg.nc
anofile=ens_sst_ano.nc
trendfile=ens_sst_DJF_trend.nc
season="DJF"
var=sst
## if model data are save with time of next month
shiftday="-shifttime,-10day"
test -f ${avgfile} && test -f ${anofile} && test -f ${trendfile} && exit 0
## loop for every member
memdirs=$(ls -d ${dir}/*mem??)
i=0
for d in $memdirs; do
    ifiles=$(ls ${d}/ocn/hist/*.micom*.hm.{1982..2018}-??.nc)
    i=$(($i+1))
    ii=$(printf "%2.2d" $i)
    o1ts=sst_${ii}.nc
    test -f "$o1ts" && continue
    ncrcat -O -h -v ${var} ${ifiles} ${o1ts}
done
for i in sst_??.nc; do
    ## cal trend and avg
    avgf=$(echo $i | sed "s/sst/sst_avg_${season}/")
    trendf=$(echo $i | sed "s/sst/sst_trend_${season}/")
    if [ "$season" == 'ANN' ]; then
        cdo -b F64 -s -O -trend -yearmonmean $shiftday ${i} $avgf $trendf
    else
        ## warning messages when DJF
        cdo -b F64 -s -O -trend -seasmean -selseason,$season $shiftday ${i} $avgf $trendf
    fi
done
### these 2 need modify to seasonal
## monthly file
if [ ! -f "${anofile}" ] ;then
    cdo -b F64 -O -ensavg sst_??.nc ${avgfile}
    cdo -b F64 -O -ymonsub ${avgfile} -ymonmean ${avgfile} ${anofile}
fi

## seasonal trend
cdo -b F64 -O -ensavg sst_trend_${season}_??.nc ${trendfile}


