#!/bin/ksh

set -evx

export MARS_READANY_BUFFER_SIZE=3732480200
module load eclib

SDATE='19820901'
EDATE='20180831'

ROOTDIR=`pwd`
SAVEDIR=/scratch/dako/cci_bufr

mkdir -p ${SAVEDIR}

DATE=${SDATE}
while [ ${DATE} -le ${EDATE} ] ;do

  YYYY=`echo ${DATE} | cut -c1-4`
  MM=`echo ${DATE} | cut -c5-6`
  DD=`echo ${DATE} | cut -c7-8`

  if [ $DD -ge 15 ] ; then
    tmp=`dateincr -d ${DATE} +20`
    yyyymm1=${YYYY}${MM}
    yyyymm2=`echo ${tmp} | cut -c1-6`
  else
    tmp=`dateincr -d ${DATE} -20`
    yyyymm1=`echo ${tmp} | cut -c1-6`
    yyyymm2=${YYYY}${MM}
  fi
  diff1=$(datediff -d ${yyyymm2}15 ${yyyymm1}15)
  diff2=$(datediff -d ${YYYY}${MM}${DD} ${yyyymm1}15)
  mm1=`echo ${yyyymm1} | cut -c5-6`
  mm2=`echo ${yyyymm2} | cut -c5-6`

/usr/local/bin/mars << EOF
  read, source="imsclim_latlon.grib", param=141, date=2000${mm1}15, fieldset=scf1
  compute, fieldset=scf1_mask, formula="bitmap(scf1,-1)"
  read, source="imsclim_latlon.grib", param=141, date=2000${mm2}15, fieldset=scf2
  compute, fieldset=scf2_mask, formula="bitmap(scf2,-1)"
  compute, fieldset=scf_mask, formula='((${diff1}-${diff2})*scf1_mask+${diff2}*scf2_mask)/${diff1}'
  write, fieldset=scf_mask, target="imsclim_intp.grib"
EOF

  if [ ${DATE} -ge 19870901 ] ; then
    threshold=0.8
  else
    threshold=0.5
  fi

  rm -f *.idx
  python3 test.py ${YYYY} ${MM} ${DD} ${threshold}
  rm -f imsclim_intp.grib

  if [ ! -d ${SAVEDIR}/${YYYY} ] ; then
    mkdir -p ${SAVEDIR}/${YYYY}
  fi

  gzip CCI${YYYY}${MM}${DD}00.DAT
  mv CCI${YYYY}${MM}${DD}00.DAT.gz ${SAVEDIR}/${YYYY}

  DATE=`dateincr -d ${DATE} +1`

done

rm -f *.idx

