#!/bin/bash

#
# Burkhardt Rockel / Helmholtz-Zentrum Geesthacht
# Initial Version: 2009/09/02
# Latest Version:  2016/12/16 (Version 2.3)
#

if [[ ${0%/*} == "."  || ${0%/*} == $PWD ]]
then :
else
  echo  === ERROR === subchain must be called from within its directory
  echo "               " it was called from: ${0%/*}
  exit 1
fi


if [ $# -lt 1 ]
then
  echo wrong number of arguments
  echo usage : subchain \<action\>
  echo   where \<action\> is one of the following options
  echo   "  "\(please read the documentation for details on how to use them\):
  echo   start : starts the chain
  echo   prep \<YYYYMM\> : restarts the chain with a a pre-processing job
  echo   int2lm \<YYYYMM\> : restarts the chain with a int2lm job 
  echo   cclm : restarts the chain with a cclm job
  echo   arch [\<YYYYMM\>] : restarts the chain with an archiving job
  echo   post [\<YYYYMM\>] : restarts a post-processing job
  echo   clean : deletes all files and directories created
  echo   create : creates the directory structure \(only needed
  echo   "           "if the directory structure was corrupted\)
  exit
fi

ACTION=$1

#################################################
# START global settings
#... change this due to your needs
#################################################

source job_settings

#################################################
# END global settings
#... no more changes needed beyond this line
#...   except specific settings for the used computer system
#################################################

#... safety check
if [ $PWD != $PFDIR/${EXPID} ]
then
  echo === ERROR === scripts directory is not the same as EXPID directory
  echo "basename" = $PWD
  echo "EXPID   " = ${PFDIR}/${EXPID} 
  exit
fi

#################################################
# delete all created files
#################################################
  # turn on extended pattern matching in case of bash shell
[ -n "$BASH_VERSION" ] && shopt -s extglob
if [ ${ACTION} == 'clean' ]
then
  #... safety request
  while true; do
    echo "Do you wish to delete all created files and directories of your experiment?(y/n)"
    read yn
    case $yn in
        [Yy]* ) break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
  done
  #... remove files and directories
  rm -rf !(subchain|job_settings|jobs|templates)
  rm -rf jobs/*
  rm -rf ${ARCHIVE_OUTDIR}/${EXPID}
  rm -rf ${WORKDIR}/${EXPID}
  rm -rf ${SCRATCHDIR}/${EXPID}
  exit
fi

#################################################
# create the job directory structure
#################################################
### either
###   at the start of the model chain
### or
###   if the command option "create" is used

if [[ -f ${PFDIR}/${EXPID}/date.log && ${ACTION} != 'create' ]]
then :
else
  echo -------------------------------------------
  echo creating directory structure for ${EXPID}
  echo -------------------------------------------
  mkdir -p ${WORKDIR}/${EXPID}
  mkdir -p ${SCRATCHDIR}/${EXPID}
  mkdir ${SCRATCHDIR}/${EXPID}/output
  mkdir ${SCRATCHDIR}/${EXPID}/output/prep
  mkdir ${SCRATCHDIR}/${EXPID}/output/int2lm
  mkdir ${SCRATCHDIR}/${EXPID}/output/cclm
  mkdir ${SCRATCHDIR}/${EXPID}/output/arch
  mkdir ${SCRATCHDIR}/${EXPID}/output/post
  mkdir ${SCRATCHDIR}/${EXPID}/input
  mkdir ${SCRATCHDIR}/${EXPID}/input/prep
  ln -fs ${SCRATCHDIR}/${EXPID}/output/prep ${SCRATCHDIR}/${EXPID}/input/int2lm
  ln -fs ${SCRATCHDIR}/${EXPID}/output/int2lm ${SCRATCHDIR}/${EXPID}/input/cclm
  ln -fs ${SCRATCHDIR}/${EXPID}/output/cclm ${SCRATCHDIR}/${EXPID}/input/arch
  ln -fs ${SCRATCHDIR}/${EXPID}/output/cclm ${SCRATCHDIR}/${EXPID}/input/post
  mkdir ${SCRATCHDIR}/${EXPID}/tmp
  mkdir ${WORKDIR}/${EXPID}/joboutputs
  mkdir ${WORKDIR}/${EXPID}/joboutputs/prep
  mkdir ${WORKDIR}/${EXPID}/joboutputs/int2lm
  mkdir ${WORKDIR}/${EXPID}/joboutputs/cclm
  mkdir ${WORKDIR}/${EXPID}/joboutputs/arch
  mkdir ${WORKDIR}/${EXPID}/joboutputs/post
  mkdir ${WORKDIR}/${EXPID}/joblogs
  mkdir ${WORKDIR}/${EXPID}/joblogs/prep
  mkdir ${WORKDIR}/${EXPID}/joblogs/int2lm
  mkdir ${WORKDIR}/${EXPID}/joblogs/cclm
  mkdir ${WORKDIR}/${EXPID}/joblogs/arch
  mkdir ${WORKDIR}/${EXPID}/joblogs/post
  mkdir ${WORKDIR}/${EXPID}/restarts
  mkdir ${WORKDIR}/${EXPID}/post
  mkdir -p ${ARCHIVE_OUTDIR}/${EXPID}
fi

if [ ! -f ${PFDIR}/${EXPID}/date.log ]
then
  echo ${YDATE_START} > ${PFDIR}/${EXPID}/date.log 
fi

### get the current date
cd ${PFDIR}/${EXPID}
CURRENT_DATE=$(cat ${PFDIR}/${EXPID}/date.log | cut -c1-14)

### at the end of the model run just exit
 if [[ ${CURRENT_DATE} -ge ${YDATE_STOP} && $# -lt 2 ]]
 then
   echo --- JOB FINISHED --
   exit
 fi

case "${ACTION}" in

create)
#################################################
# just create the directory structure
#################################################
# in case directories has been deleted,
# but are still needed

  exit;;

start)
#################################################
# starts the program
#################################################
# this equivalent to "subchain prep"

  ${PFDIR}/${EXPID}/subchain prep

  exit;;

prep)
#################################################
# Preprocessing settings and submission
#################################################

  if [ $# -gt 2 ]
  then
      echo wrong number of arguments, must be 0 or 1
      echo usage: subchain prep [\<current_date\>]
      exit
  fi
  #... if a second argument is given, that will be used for the CURRENT_DATE instead of the value in date.log
  if [ $# -eq 2 ]
  then
      CURRENT_DATE=${2:0:6}01${YDATE_START:8:4}
  fi

  if [ ${ITYPE_INT2LM} -eq 1 ]
  then
  OUTDIR=${SCRATCHDIR}/${EXPID}/output/prep
  else
    OUTDIR=${SCRATCHDIR}/${EXPID}/output/int2lm
  fi
  YYYY=$(echo ${CURRENT_DATE} | cut -c1-4)
  MM=$(echo ${CURRENT_DATE} | cut -c5-6)
  YYYY_MM=${YYYY}_${MM}
  if [ ${#CURRENT_DATE} -eq 10 ]
  then
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-10)
  else
  NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-14)
  fi
  YYYY_NEXT=$(echo ${NEXT_DATE} | cut -c1-4)
  MM_NEXT=$(echo ${NEXT_DATE} | cut -c5-6)
  JOBLOGFILE=${WORKDIR}/${EXPID}/joblogs/prep/prep_${EXPID}_${YYYY_MM}.o

  if [ ! -d ${OUTDIR}/${YYYY_MM} ]
  then
    mkdir ${OUTDIR}/${YYYY_MM}
  fi

  sed \
      -e s%@{ARCHIVE_INPDIR}%${ARCHIVE_INPDIR}%g \
      -e s%@{CURRENT_DATE}%${CURRENT_DATE}%g \
      -e s%@{EMAIL_ADDRESS}%${EMAIL_ADDRESS}%g \
      -e s%@{EXPID}%${EXPID}%g \
      -e s%@{HINCBOUND}%${HINCBOUND}%g \
      -e s%@{ITYPE_CALENDAR}%${ITYPE_CALENDAR}%g \
      -e s%@{ITYPE_INT2LM}%${ITYPE_INT2LM}%g \
      -e s%@{JOBLOGFILE}%${JOBLOGFILE}%g \
      -e s%@{MM_NEXT}%${MM_NEXT}%g \
      -e s%@{MM}%${MM}%g \
      -e s%@{NC_BINDIR}%${NC_BINDIR}%g \
      -e s%@{NCO_BINDIR}%${NCO_BINDIR}%g \
      -e s%@{NEXT_DATE}%${NEXT_DATE}%g \
      -e s%@{OUTDIR}%${OUTDIR}%g \
      -e s%@{PFDIR}%${PFDIR}%g \
      -e s%@{PROJECT_ACCOUNT}%${PROJECT_ACCOUNT}%g \
      -e s%@{SCRATCHDIR}%${SCRATCHDIR}%g \
      -e s%@{UTILS_BINDIR}%${UTILS_BINDIR}%g \
      -e s%@{WORKDIR}%${WORKDIR}%g \
      -e s%@{YDATE_START}%${YDATE_START}%g \
      -e s%@{YDATE_STOP}%${YDATE_STOP}%g \
      -e s%@{YYYY_MM}%${YYYY_MM}%g \
      -e s%@{YYYY_NEXT}%${YYYY_NEXT}%g \
      -e s%@{YYYY}%${YYYY}%g \
      <templates/prep.job.tmpl>jobs/prep${EXPID}.job

  echo "***********************"
  echo \* submitting PREP job \*
  echo "***********************"
  ##${KSH_CMD} ${PFDIR}/${EXPID}/jobs/prep${EXPID}.job

 chmod u+x  ${PFDIR}/${EXPID}/jobs/prep${EXPID}.job
 qsub ${PFDIR}/${EXPID}/jobs/prep${EXPID}.job

exit;;

int2lm)
#################################################
# INT2LM settings and submission
#################################################

  if [ $# -gt 2 ]
  then
      echo wrong number of arguments, must be 0 or 1
      echo usage: subchain int2lm [\<current_date\>]
      exit
  fi
  #... if a second argument is given, that will be used for the CURRENT_DATE instead of the value in date.log
  if [ $# -eq 2 ]
  then
      CURRENT_DATE=${2:0:6}01${YDATE_START:8:4}
  fi

  #... adjust the following to your computer system
  PPN=12           # processors per node

  NP=$(python -c "print ${NPX_INT2LM}*${NPY_INT2LM}")

  # check whether whole nodes will be used
  #...   this can be removed in case it does not matter on your computer system
  MOD_NP=$(python -c "print ${NP}%${PPN}")
  if [ ${MOD_NP} -ne 0 ]
  then
    echo Error in INT2LM  > ${PFDIR}/${EXPID}/error_message
    echo ERROR: number of processors mismatch  >> ${PFDIR}/${EXPID}/error_message
    echo please use whole nodes. modulo\(NP, PPN\) should be 0, but is ${MOD_NP}  >> ${PFDIR}/${EXPID}/error_message
    if [ -n "${EMAIL_ADDRESS}" ]
    then
      mailx -s "SUBCHAIN ${EXPID} abort due to errors" ${EMAIL_ADDRESS} < ${PFDIR}/${EXPID}/error_message
    fi
    exit 1
  fi

  NODES=$(python -c "print ${NP}/${PPN}")          # number of nodes
  NPX=${NPX_INT2LM}            # number of processors in x - direction
  NPY=${NPY_INT2LM}            # number of processors in y - direction
  NPIO=0           # number of processors for I/O, is presently always 0 for netCDF I/O in INT2LM


  INPDIR=${SCRATCHDIR}/${EXPID}/input/int2lm
  OUTDIR=${SCRATCHDIR}/${EXPID}/output/int2lm

  # the following parameters change during job chaining
  if [ ${#CURRENT_DATE} -eq 10 ]
  then
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-10)
  else
  NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-14)
  fi
  YYYY=$(echo ${CURRENT_DATE} | cut -c1-4)
  MM=$(echo ${CURRENT_DATE} | cut -c5-6)
  YYYY_MM=${YYYY}_${MM}
  JOBLOGFILE=${WORKDIR}/${EXPID}/joblogs/int2lm/int2lm_${EXPID}_${YYYY_MM}.o
   if [ ! -d ${WORKDIR}/${EXPID}/joboutputs/int2lm/${YYYY_MM} ]
  then
    mkdir ${WORKDIR}/${EXPID}/joboutputs/int2lm/${YYYY_MM}
  fi
   if [ ! -d ${OUTDIR}/${YYYY_MM} ]
  then
    mkdir ${OUTDIR}/${YYYY_MM}
  fi

  sed \
      -e s%@{CURRENT_DATE}%${CURRENT_DATE}%g \
      -e s%@{CZML_SOIL}%${CZML_SOIL}%g \
      -e s%@{DLAT}%${DLAT}%g \
      -e s%@{DLON}%${DLON}%g \
      -e s%@{EMAIL_ADDRESS}%${EMAIL_ADDRESS}%g \
      -e s%@{EXPID}%${EXPID}%g \
      -e s%@{HINCBOUND}%${HINCBOUND}%g \
      -e s%@{IE_TOT}%${IE_TOT}%g \
      -e s%@{INPDIR}%${INPDIR}%g \
      -e s%@{INT2LM_EXE}%${INT2LM_EXE}%g \
      -e s%@{ITYPE_AEROSOL}%${ITYPE_AEROSOL}%g \
      -e s%@{ITYPE_ALBEDO}%${ITYPE_ALBEDO}%g \
      -e s%@{ITYPE_CALENDAR}%${ITYPE_CALENDAR}%g \
      -e s%@{JE_TOT}%${JE_TOT}%g \
      -e s%@{JOBLOGFILE}%${JOBLOGFILE}%g \
      -e s%@{KE_SOIL}%${KE_SOIL}%g \
      -e s%@{KE_TOT}%${KE_TOT}%g \
      -e s%@{LFOREST}%${LFOREST}%g \
      -e s%@{LLAKE}%${LLAKE}%g \
      -e s%@{LSSO}%${LSSO}%g \
      -e s%@{MM}%${MM}%g \
      -e s%@{NEXT_DATE}%${NEXT_DATE}%g \
      -e s%@{NODES}%${NODES}%g \
      -e s%@{NP}%${NP}%g \
      -e s%@{NPX}%${NPX}%g \
      -e s%@{NPY}%${NPY}%g \
      -e s%@{OUTDIR}%${OUTDIR}%g \
      -e s%@{PFDIR}%${PFDIR}%g \
      -e s%@{POLGAM}%${POLGAM}%g \
      -e s%@{POLLAT}%${POLLAT}%g \
      -e s%@{POLLON}%${POLLON}%g \
      -e s%@{PPN}%${PPN}%g \
      -e s%@{PROJECT_ACCOUNT}%${PROJECT_ACCOUNT}%g \
      -e s%@{STARTLAT_TOT}%${STARTLAT_TOT}%g \
      -e s%@{STARTLON_TOT}%${STARTLON_TOT}%g \
      -e s%@{TASK_AFFINITY}%${TASK_AFFINITY}%g \
      -e s%@{UTILS_BINDIR}%${UTILS_BINDIR}%g \
      -e s%@{WORKDIR}%${WORKDIR}%g \
      -e s%@{YDATE_START}%${YDATE_START}%g \
      -e s%@{YYYY}%${YYYY}%g \
      -e s%@{YYYY_MM}%${YYYY_MM}%g \
      <templates/int2lm.job.tmpl>jobs/int2lm${EXPID}.job

  echo "*************************"
  echo \* submitting INT2LM job \*
  echo "*************************"
chmod u+x ${PFDIR}/${EXPID}/jobs/int2lm${EXPID}.job
qsub ${PFDIR}/${EXPID}/jobs/int2lm${EXPID}.job

exit;;

cclm)
#################################################
# CCLM settings and submission
#################################################

  # the following parameters are constant during job chaining
  INPDIR=${SCRATCHDIR}/${EXPID}/input/cclm
  OUTDIR=${SCRATCHDIR}/${EXPID}/output/cclm
  RESDIR=${WORKDIR}/${EXPID}/restarts

  #... adjust the following to your computer system
  PPN=12           # processors per node

  NP=$(python -c "print ${NPX_CCLM}*${NPY_CCLM}+${NPIO_CCLM}")

  # check whether whole nodes will be used
  #...   this can be removed in case it does not matter on your computer system
  MOD_NP=$(python -c "print ${NP}%${PPN}")
  if [ ${MOD_NP} -ne 0 ]
  then
    echo Error in CCLM  > ${PFDIR}/${EXPID}/error_message
    echo ERROR: number of processors mismatch  >> ${PFDIR}/${EXPID}/error_message
    echo please use whole nodes. modulo\(NP, PPN\) should be 0, but is ${MOD_NP}  >> ${PFDIR}/${EXPID}/error_message
    if [ -n "${EMAIL_ADDRESS}" ]
    then
      mailx -s "SUBCHAIN ${EXPID} abort due to errors" ${EMAIL_ADDRESS} < ${PFDIR}/${EXPID}/error_message
    fi
    exit 1
  fi

  NODES=$(python -c "print ${NP}/${PPN}")          # number of nodes
  NPX=${NPX_CCLM}            # number of processors in x - direction
  NPY=${NPY_CCLM}            # number of processors in y - direction
  NPIO=${NPIO_CCLM}           # number of processors for I/O, is presently always 0 for netCDF I/O in INT2LM

  # the following parameters change during job chaining
  if [ ${#CURRENT_DATE} -eq 10 ]
  then
    NEXT_MONTH=$(${UTILS_BINDIR}/cfu get_next_dates $(echo ${CURRENT_DATE} | cut -c1-6)0100 01:00:00 ${ITYPE_CALENDAR} | cut -c1-10)
  else
    NEXT_MONTH=$(${UTILS_BINDIR}/cfu get_next_dates $(echo ${CURRENT_DATE} | cut -c1-6)01000000 01:00:00 ${ITYPE_CALENDAR} | cut -c1-14)
  fi

  if [ "$2" != "noprep" ]  # if input data for CCLM already exist for the next month run "subchain cclm noprep"
  then
  if [ $(echo ${CURRENT_DATE} | cut -c7-10) -eq 0100 ]
  then
    ### submit a preprocessing job for the following month in parallel
  if [ ${#CURRENT_DATE} -eq 10 ]
  then
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-10)
  else
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-14)
  fi
   if [ ${NEXT_DATE} -lt ${YDATE_STOP} ]
    then
      ${PFDIR}/${EXPID}/subchain prep ${NEXT_DATE}
    fi
  fi
  fi

  if [ ${#CURRENT_DATE} -eq 10 ]
  then
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} ${INC_DATE} ${ITYPE_CALENDAR} | cut -c1-10)
  else
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} ${INC_DATE} ${ITYPE_CALENDAR} | cut -c1-14)
  fi
  if [ ${NEXT_DATE} -ge ${NEXT_MONTH} ]
  then
    NEXT_DATE=${NEXT_MONTH}
  fi
  
  MM=$(echo ${CURRENT_DATE} | cut -c5-6)
  YYYY=$(echo ${CURRENT_DATE} | cut -c1-4)
  YYYY_MM=${YYYY}_${MM}
  HSTART=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${CURRENT_DATE} ${ITYPE_CALENDAR})
  HNEXT=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${NEXT_DATE} ${ITYPE_CALENDAR})
  let "HINC = HNEXT - HSTART"
  JOBLOGFILE=${WORKDIR}/${EXPID}/joblogs/cclm/cclm_${EXPID}_${YYYY_MM}.o

  # write the data file *c.nc just for the first month
  # in case of restart, the initial data are read from restart files
  # instead of int2lm output
  if [ ${CURRENT_DATE} -eq ${YDATE_START} ]
  then
    LWRITE_CONST=.TRUE.
    YDIRINI=${INPDIR}/${YYYY_MM}
  else
    LWRITE_CONST=.FALSE.
    YDIRINI=${RESDIR}
  fi

# check if all boundary data are provided by INT2LM
  if [ $(${UTILS_BINDIR}/cfu check_files ${CURRENT_DATE} ${NEXT_DATE} ${HINCBOUND}:00:00 laf lbfd .nc ${INPDIR}/${YYYY_MM} T ${ITYPE_CALENDAR}) -eq 1 ]
  then
    echo Error in CCLM  > ${PFDIR}/${EXPID}/error_message
    echo Date ${YYYY} / ${MM} >> ${PFDIR}/${EXPID}/error_message
    echo Error during CCLM >> ${PFDIR}/${EXPID}/error_message
    echo Not all CCLM input files found >> ${PFDIR}/${EXPID}/error_message
    echo Maybe the CCLM job was faster than the in parallel running INT2LM job >> ${PFDIR}/${EXPID}/error_message
    echo If the latter is the case the INT2LM will rerun the CCLM automatically >> ${PFDIR}/${EXPID}/error_message
    cat check_files.log >> ${PFDIR}/${EXPID}/error_message
    if [ -n "${EMAIL_ADDRESS}" ]
    then
      mailx -s "SUBCHAIN ${EXPID} abort due to errors" ${EMAIL_ADDRESS} < ${PFDIR}/${EXPID}/error_message
    fi
    rm check_files.log
    exit
  fi

  # create output file directories for the current month
  if [ ! -d ${WORKDIR}/${EXPID}/joboutputs/cclm/${YYYY_MM} ]
  then
    mkdir ${WORKDIR}/${EXPID}/joboutputs/cclm/${YYYY_MM}
  else
    # delete Y* etc. files
    if [ $(echo ${CURRENT_DATE} | cut -c7-10) -eq 0100 ]
    then
      rm -rf ${WORKDIR}/${EXPID}/joboutputs/cclm/${YYYY_MM}/*
    else
      # in case of sub-monthly chunks delete only files
      find ${WORKDIR}/${EXPID}/joboutputs/cclm/${YYYY_MM}  -maxdepth 1 -type f -exec rm -f {} \;
    fi
  fi

  if [ ! -d ${SCRATCHDIR}/${EXPID}/output/cclm/${YYYY_MM} ]
  then
    mkdir ${SCRATCHDIR}/${EXPID}/output/cclm/${YYYY_MM}
    NOUTDIR=1
    while [ ${NOUTDIR} -le ${HOUT_INC[0]} ]
    do
      NOUTDIR2=$(printf %02d ${NOUTDIR})
      mkdir ${SCRATCHDIR}/${EXPID}/output/cclm/${YYYY_MM}/out${NOUTDIR2}
      ((NOUTDIR++))
    done
  fi

  # build the cclm${EXPID}.job file
  sed \
      -e s%@{CCLM_EXE}%${CCLM_EXE}%g \
      -e s%@{CURRENT_DATE}%${CURRENT_DATE}%g \
      -e s%@{CZML_SOIL}%${CZML_SOIL}%g \
      -e s%@{DLAT}%${DLAT}%g \
      -e s%@{DLON}%${DLON}%g \
      -e s%@{EMAIL_ADDRESS}%${EMAIL_ADDRESS}%g \
      -e s%@{EXPID}%${EXPID}%g \
      -e s%@{HINC}%${HINC}%g \
      -e s%@{HINCBOUND}%${HINCBOUND}%g \
      -e s%@{HINCMXT}%${HINCMXT}%g \
      -e s%@{HINCMXU}%${HINCMXU}%g \
      -e s%@{HNEXT}%${HNEXT}%g \
      -e s%@{HOUT_INC}%"${HOUT_INC[*]}"%g \
      -e s%@{HSTART}%${HSTART}%g \
      -e s%@{IE_TOT}%${IE_TOT}%g \
      -e s%@{INC_DATE}%${INC_DATE}%g \
      -e s%@{INPDIR}%${INPDIR}%g \
      -e s%@{ITYPE_AEROSOL}%${ITYPE_AEROSOL}%g \
      -e s%@{ITYPE_ALBEDO}%${ITYPE_ALBEDO}%g \
      -e s%@{ITYPE_CALENDAR}%${ITYPE_CALENDAR}%g \
      -e s%@{JE_TOT}%${JE_TOT}%g \
      -e s%@{JOBLOGFILE}%${JOBLOGFILE}%g \
      -e s%@{KE_SOIL}%${KE_SOIL}%g \
      -e s%@{KE_TOT}%${KE_TOT}%g \
      -e s%@{LFOREST}%${LFOREST}%g \
      -e s%@{LLAKE}%${LLAKE}%g \
      -e s%@{LSSO}%${LSSO}%g \
      -e s%@{LWRITE_CONST}%${LWRITE_CONST}%g \
      -e s%@{MM}%${MM}%g \
      -e s%@{NEXT_DATE}%${NEXT_DATE}%g \
      -e s%@{NODES}%${NODES}%g \
      -e s%@{NP}%${NP}%g \
      -e s%@{NPIO}%${NPIO}%g \
      -e s%@{NPX}%${NPX}%g \
      -e s%@{NPY}%${NPY}%g \
      -e s%@{OUTDIR}%${OUTDIR}%g \
      -e s%@{PFDIR}%${PFDIR}%g \
      -e s%@{POLGAM}%${POLGAM}%g \
      -e s%@{POLLAT}%${POLLAT}%g \
      -e s%@{POLLON}%${POLLON}%g \
      -e s%@{PPN}%${PPN}%g \
      -e s%@{PROJECT_ACCOUNT}%${PROJECT_ACCOUNT}%g \
      -e s%@{RESDIR}%${RESDIR}%g \
      -e s%@{SHARED}%${SHARED}%g \
      -e s%@{STARTLAT_TOT}%${STARTLAT_TOT}%g \
      -e s%@{STARTLON_TOT}%${STARTLON_TOT}%g \
      -e s%@{TASK_AFFINITY}%${TASK_AFFINITY}%g \
      -e s%@{WORKDIR}%${WORKDIR}%g \
      -e s%@{YDATE_START}%${YDATE_START}%g \
      -e s%@{YDATE_STOP}%${YDATE_STOP}%g \
      -e s%@{YDIRINI}%${YDIRINI}%g \
      -e s%@{YYYY}%${YYYY}%g \
      -e s%@{YYYY_MM}%${YYYY_MM}%g \
      <templates/cclm.job.tmpl>jobs/cclm${EXPID}.job

  echo "***********************"
  echo \* submitting CCLM job \*
  echo "***********************"
  chmod u+x ${PFDIR}/${EXPID}/jobs/cclm${EXPID}.job
 qsub ${PFDIR}/${EXPID}/jobs/cclm${EXPID}.job


exit;;


arch)
#################################################
# Archiving settings and submission
#################################################

  if [ $# -eq 2 ]
  then
        CURRENT_DATE=${2:0:6}01${YDATE_START:8:4}  # just in case of an arch re-run for a specific month
  fi
  INPDIR=${SCRATCHDIR}/${EXPID}/input/arch
  if [ ${#CURRENT_DATE} -eq 10 ]
  then
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-10)
  else
  NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-14)
  fi
  YYYY=$(echo ${CURRENT_DATE} | cut -c1-4)
  MM=$(echo ${CURRENT_DATE} | cut -c5-6)
  YYYY_MM=${YYYY}_${MM}
  HSTART=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${CURRENT_DATE} ${ITYPE_CALENDAR})
  HNEXT=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${NEXT_DATE} ${ITYPE_CALENDAR})
  HSTOP=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${YDATE_STOP} ${ITYPE_CALENDAR})
  JOBLOGFILE=${WORKDIR}/${EXPID}/joblogs/arch/arch_${EXPID}_${YYYY_MM}.o
  YDATE_NEXT=${NEXT_DATE}
  YYYY_NEXT=$(echo ${NEXT_DATE} | cut -c1-4)
  MM_NEXT=$(echo ${NEXT_DATE} | cut -c5-6)

  # LASTOUTPUT is set for check_files, since the last month contains one additional 
  #            output file
  LASTOUTPUT=T
  if [ ${NEXT_DATE} -lt ${YDATE_STOP} ]
  then
     LASTOUTPUT=F
  fi

  # build the arch${EXPID}.job file
  sed \
      -e s%@{CDO}%${CDO}%g \
      -e s%@{ARCHIVE_OUTDIR}%${ARCHIVE_OUTDIR}%g \
      -e s%@{CURRENT_DATE}%${CURRENT_DATE}%g \
      -e s%@{EMAIL_ADDRESS}%${EMAIL_ADDRESS}%g \
      -e s%@{EXPID}%${EXPID}%g \
      -e s%@{HOUT_INC}%"${HOUT_INC[*]}"%g \
      -e s%@{INC_DATE}%${INC_DATE}%g \
      -e s%@{INPDIR}%${INPDIR}%g \
      -e s%@{ITYPE_CALENDAR}%${ITYPE_CALENDAR}%g \
      -e s%@{ITYPE_COMPRESS_ARCH}%${ITYPE_COMPRESS_ARCH}%g \
      -e s%@{ITYPE_SAMOA}%${ITYPE_SAMOA}%g \
      -e s%@{JOBLOGFILE}%${JOBLOGFILE}%g \
      -e s%@{LASTOUTPUT}%${LASTOUTPUT}%g \
      -e s%@{MM}%${MM}%g \
      -e s%@{NBOUNDCUT}%${NBOUNDCUT}%g \
      -e s%@{NC_BINDIR}%${NC_BINDIR}%g \
      -e s%@{NEXT_DATE}%${NEXT_DATE}%g \
      -e s%@{PFDIR}%${PFDIR}%g \
      -e s%@{PROJECT_ACCOUNT}%${PROJECT_ACCOUNT}%g \
      -e s%@{SCRATCHDIR}%${SCRATCHDIR}%g \
      -e s%@{UTILS_BINDIR}%${UTILS_BINDIR}%g \
      -e s%@{WORKDIR}%${WORKDIR}%g \
      -e s%@{YDATE_NEXT}%${YDATE_NEXT}%g \
      -e s%@{YYYY_MM}%${YYYY_MM}%g \
      -e s%@{YYYY}%${YYYY}%g \
      <templates/arch.job.tmpl>jobs/arch${EXPID}.job

  ###  submit the archiving job
  echo "***********************"
  echo \* submitting ARCH job \*
  echo "***********************"
  chmod u+x  ${PFDIR}/${EXPID}/jobs/arch${EXPID}.job
 qsub ${PFDIR}/${EXPID}/jobs/arch${EXPID}.job

exit;;

post)
#################################################
# Post-processing settings and submission
#################################################

  if [ $# -eq 2 ]
  then
    CURRENT_DATE=${2:0:6}01${YDATE_START:8:4}  # just in case of a postprocessing re-run for a specific month
  fi

  INPDIR=${SCRATCHDIR}/${EXPID}/input/post
  OUTDIR=${WORKDIR}/${EXPID}/post
  if [ ${#CURRENT_DATE} -eq 10 ]
  then
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-10)
  else
    NEXT_DATE=$(${UTILS_BINDIR}/cfu get_next_dates ${CURRENT_DATE} 01:00:00 ${ITYPE_CALENDAR} | cut -c1-14)
  fi
  YYYY=$(echo ${CURRENT_DATE} | cut -c1-4)
  MM=$(echo ${CURRENT_DATE} | cut -c5-6)
  YYYY_MM=${YYYY}_${MM}
  HSTART=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${CURRENT_DATE} ${ITYPE_CALENDAR})
  HNEXT=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${NEXT_DATE} ${ITYPE_CALENDAR})
  HSTOP=$(${UTILS_BINDIR}/cfu get_hours ${YDATE_START} ${YDATE_STOP} ${ITYPE_CALENDAR})
  JOBLOGFILE=${WORKDIR}/${EXPID}/joblogs/post/post_${EXPID}_${YYYY_MM}.o
  YDATE_NEXT=${NEXT_DATE}
  YYYY_NEXT=$(echo ${NEXT_DATE} | cut -c1-4)
  MM_NEXT=$(echo ${NEXT_DATE} | cut -c5-6)

  if [ ! -d ${OUTDIR}/${YYYY_MM} ]
  then
    mkdir ${OUTDIR}/${YYYY_MM}
  fi

  # build the post${EXPID}.job file
  sed \
      -e s%@{CDO}%${CDO}%g \
      -e s%@{CURRENT_DATE}%${CURRENT_DATE}%g \
      -e s%@{EMAIL_ADDRESS}%${EMAIL_ADDRESS}%g \
      -e s%@{EXPID}%${EXPID}%g \
      -e s%@{IE_TOT}%${IE_TOT}%g \
      -e s%@{INPDIR}%${INPDIR}%g \
      -e s%@{ITYPE_COMPRESS_ARCH}%${ITYPE_COMPRESS_ARCH}%g \
      -e s%@{ITYPE_COMPRESS_POST}%${ITYPE_COMPRESS_POST}%g \
      -e s%@{JE_TOT}%${JE_TOT}%g \
      -e s%@{JOBLOGFILE}%${JOBLOGFILE}%g \
      -e s%@{MM}%${MM}%g \
      -e s%@{NBOUNDCUT}%${NBOUNDCUT}%g \
      -e s%@{NC_BINDIR}%${NC_BINDIR}%g \
      -e s%@{NCO_BINDIR}%${NCO_BINDIR}%g \
      -e s%@{NEXT_DATE}%${NEXT_DATE}%g \
      -e s%@{OUTDIR}%${OUTDIR}%g \
      -e s%@{PFDIR}%${PFDIR}%g \
      -e s%@{PROJECT_ACCOUNT}%${PROJECT_ACCOUNT}%g \
      -e s%@{SCRATCHDIR}%${SCRATCHDIR}%g \
      -e s%@{WORKDIR}%${WORKDIR}%g \
      -e s%@{YDATE_START}%${YDATE_START}%g \
      -e s%@{YDATE_STOP}%${YDATE_STOP}%g \
      -e s%@{YYYY_MM}%${YYYY_MM}%g \
      -e s%@{YYYY}%${YYYY}%g \
      <templates/post.job.tmpl>jobs/post${EXPID}.job

  ###  submit the post processing job
  echo "***********************"
  echo \* submitting POST job \*
  echo "***********************"
  chmod u+x ${PFDIR}/${EXPID}/jobs/post${EXPID}.job
  qsub ${PFDIR}/${EXPID}/jobs/post${EXPID}.job

exit;;

#################################################
# invalid parameter
#################################################
*)
    echo "Error in SUBCHAIN"  > ${PFDIR}/${EXPID}/error_message
    echo "ERROR: invalid program: " ${ACTION}  >> ${PFDIR}/${EXPID}/error_message
    echo NP=${NP}  NPSCA=${NPSCA}  >> ${PFDIR}/${EXPID}/error_message
    if [ -n "${EMAIL_ADDRESS}" ]
    then
      mailx -s "SUBCHAIN ${EXPID} abort due to errors" ${EMAIL_ADDRESS} < ${PFDIR}/${EXPID}/error_message
    fi
exit 1;;

esac

