#!/bin/bash
set -e
#
# cccjob template for a diagnostics only job string on PPP2
#
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
# config file
canesm_cfg_file=canesm.cfg
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

# Source the config file
. ${canesm_cfg_file}

# derive start_year and start_month
start_list=(${start_time//:/ })
start_year=${start_list[0]:-1}
start_month=${start_list[1]:-1}

# derive stop_year and stop_month
stop_list=(${stop_time//:/ })
stop_year=${stop_list[0]:-1}
stop_month=${stop_list[1]:-12}

# derive run_start_year and run_start_month
run_start_list=(${run_start_time//:/ })
run_start_year=${run_start_list[0]:-1}
run_start_month=${run_start_list[1]:-1}

# derive year_rtdiag_start and month_rtdiag_start
start_rtdiag_time=(${start_rtdiag//:/ })
year_rtdiag_start=${start_rtdiag_time[0]:-1}
month_rtdiag_start=${start_rtdiag_time[1]:-1}

# Change any or all of the following as required

# start and stop control the length of this job string
# They are both of the form year:month or just year, where year and month are positive integers
# With the year:month format, at least one of year or month must be defined.
#   -if month is missing then it will default to 1 for start and 12 for stop
#   -if year is missing then it will default to 1 for start and start_year for stop
# With the year only format, start month will be 1 and stop month will be 12
start=2003
stop=2003

#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#
#=#=# BEGIN preamble...do not modify
# Internal definitions
Runame=$(basename $0)
# Error exit with message (executed as a simple command)
bail(){
  echo $(date)" --- *EE* ${Runame}: $*"
  exit 1
}
# Issue a warning but do not exit
warn(){
  echo $(date)" --- *WW* ${Runame}: $*"
}
# Emit an informational message
info(){
  echo $(date)" --- *II* ${Runame}: $*"
}
# A pattern to match a string of the form INT:INT (INT a positive integer or zero)
patt1='^[0-9][0-9]*:[0-9][0-9]*$'
# A pattern to match a single positive integer or zero
patt2='^[0-9][0-9]*$'
# Process start or stop parameters (both will contain year:month values)
process_date_param(){
  local pnam pval pyear pmon dyear dmon
  local -a Aval
  # Process a date parameter (currently only start or stop are recognized)
  [ -z "$1" ] && bail "${FUNCNAME[0]} $*
 *EE* ${FUNCNAME[0]} requires a variable name on the command line whose value is of the form year:month, or just year"
  # Verify that the parameter name is valid and set a default year and month
  # for each name specified, to be used when the year or month info is missing.
  # Note that the default stop year depends on the start year and so the start
  # parameter should be processed before the stop parameter.
  case $1 in
    start) dyear=1; dmon=1  ;;             # Expected parameter name
     stop) dyear=${start_year:-1}; dmon=12 # Expected parameter name
           # If start_year is not defined then let the user know
           [ -z "$start_year" ] &&
           info "${FUNCNAME[0]}:
 *II* ${FUNCNAME[0]}: Normally stop is defined after start is defined.
 *II* ${FUNCNAME[0]}: You are currently defining stop before start is defined.
 *II* ${FUNCNAME[0]}: Setting default stop year to $dyear"
           ;;
    *) bail "${FUNCNAME[0]}: Invalid parameter name -->$1<--" ;;
  esac
  pnam=$1
  eval pval=\$$1
  [ -z "$pval" ] && bail "${FUNCNAME[0]}: $pnam must be defined and not null"
  local msg_comm="$pnam should be of the form year:month, or just year, where month and year are positive integers."

  if [[ $pval =~ ":" ]]; then
    # Split on colon
    Aval=(${pval//:/ })
    if [ ${#Aval[*]} == 0 ]; then
      # The array is empty (ie just a single colon in pval)
      bail "${FUNCNAME[0]}: Invalid value for ${pnam}=$pval missing year and month $msg_comm"
    elif [ ${#Aval[*]} == 1 ]; then
      # Only 1 element in Aval, meaning the single colon is either the first or last character
      if [[ ${pval:0:1} = ":" ]]; then
        # The colon is the first character (year is missing and month is present)
        # Assume the default, that is set above, for year
        pyear=$dyear
        pmon=${Aval[0]}
        warn "${FUNCNAME[0]}: $pnam is missing a value for year. $msg_comm Using $pnam year=$pyear $pnam month=$pmon"
      else
        # The colon is the last character (year is present but month is missing)
        # Assume the default, that is set above, for month
        pyear=${Aval[0]}
        pmon=$dmon
        warn "${FUNCNAME[0]}: $pnam is missing a value for month. $msg_comm Using $pnam year=$pyear $pnam month=$pmon"
      fi
    else
      # At least 2 elements in Aval
      pyear=${Aval[0]:-$dyear}
      pmon=${Aval[1]:-$dmon}
    fi
  elif [[ $pval =~ $patt2 ]]; then
    # The parameter value is a positive integer or zero
    # Assume it is the year and set month to the default value defined above
    pyear=$pval
    pmon=$dmon
    # warn "${FUNCNAME[0]}: ${pnam}=$pval is a single integer. Using $pnam year=$pyear $pnam month=$pmon"
  else
    bail "${FUNCNAME[0]}: Invalid value for ${pnam}=$pval  ...$msg_comm"
  fi
  # At this point the local variables pyear and pmon should be defined with
  # values consistent with the value of the user supplied parameter name.
  # Verify that pyear and pmon are integers with reasonable values
  [[ $pyear =~ $patt2 ]] ||
      bail "Invalid ${pnam}=$pval ...The year is not a positive integer or zero. $msg_comm"
  [[ $pyear < 0 ]] &&
      bail "Invalid ${pnam}=$pval ...The year is less that zero. $msg_comm"
  [[ $pmon  =~ $patt2 ]] ||
      bail "Invalid ${pnam}=$pval ...The month is not a positive integer. $msg_comm"
  [ $pmon -lt 1 -o $pmon -gt 12 ]  &&
    bail "Invalid ${pnam}=${pval} ...month=$pmon is out of range. $msg_comm"

  # Format local year and month values
  pyear=`echo $pyear | awk '{printf "%d",$1}'`
  pmon=`echo $pmon | awk '{printf "%02d",$1}'`

  # Define global variables ${pnam}_year, ${pnam}_mon and ${pnam}_time for use elsewhere
  eval ${pnam}_year=$pyear
  eval ${pnam}_mon=$pmon
  Aval[0]=$pyear
  Aval[1]=$pmon
  eval ${pnam}_time=\(${Aval[@]}\)
  eval echo \"${FUNCNAME[0]}: ${pnam}_year=\$pyear  ${pnam}_mon=\$pmon\"
}
#=#=# END preamble
#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#=#

# Create variables start_year, start_mon and start_time using info in start
# start should be processed before stop so that reasonable defaults can be used for stop
process_date_param start
echo start_year=$start_year start_mon=$start_mon

# Create variables stop_year, stop_mon and stop_time using info in stop
process_date_param stop
echo stop_year=$stop_year stop_mon=$stop_mon

# The chunk_size in months (must correspond to an integer number of years)
chunk_size=`echo $start_year $start_mon $stop_year $stop_mon | awk '{printf "%d",($3-$1)*12+($4-$2)+1}'`
if [ $chunk_size -gt 12 ] ; then
  chunk_size=12
fi
echo chunk_size=$chunk_size

# months for GCM and restart files
last_month=`expr $start_mon + 11` # last month in a year
end_month=`expr $start_mon + $months_run - 1` # last month in $months_run chunk
exe_month=`expr $start_mon + $months - 1` # last month in $months chunk
months_gs="+`seq $start_mon $months_run $last_month | awk '{print ($1-1)%12+1}'|tr '\n' ','`"
months_rs="+`seq $end_month $months_run $last_month | awk '{print ($1-1)%12+1}'|tr '\n' ','`"
months_ab="+`seq $exe_month $months     $last_month | awk '{print ($1-1)%12+1}'|tr '\n' ','`"

echo months_run=$months_run
echo months_gs=$months_gs
echo months_rs=$months_rs
echo months_ab=$months_ab

# Year of the restart files for the first year
if [ $start_mon -eq 1 ] ;then
  start_year_rs=`expr $start_year - 1`
  start_mon_rs=12
else
  start_year_rs=$start_year
  start_mon_rs=`echo $start_mon | awk '{printf "%02d",$1-1}'`
fi
echo start_year_rs=$start_year_rs start_mon_rs=$start_mon_rs

# Months for which to execute NEMO RTD
nemo_rtd_mons=`echo $months_gs | sed 's/+//' | tr ',' ' ' | xargs printf "%02d "`

# Months for which to execute Coupler RTD
coupler_rtd_mons=`echo $months_gs | sed 's/+//' | tr ',' ' ' | xargs printf "%02d "`

# frequency for GCMPAK
months_pack="-${months_run}m"

# months=1 would normally be used here ...but it can be reset if required for special cases
months=1
months_gcm=$months_run # keep months_run value as months_gcm (needed for gcmpak.dk)
months_run=1 # reset months_run to 1

#==========================================================================================
# Variables coming in from ${canesm_cfg_file}, modified here
#==========================================================================================

xc2ppp_suffix_list=`echo $xc2ppp_suffix_list | sed "s/+months_rs/${months_rs}/g;s/+months_gs/${months_gs}/g;s/+months_ab/${months_ab}/g"`
xc2ppp0_suffix_list=`echo $xc2ppp0_suffix_list | sed "s/+months_rs/+${start_mon_rs}/g;s/+months_gs/+${start_mon_rs}/g;s/+months_ab/+${start_mon_rs}/g"`

canesm_load_hist_suffix_list=`echo $canesm_load_hist_suffix_list | sed "s/+months_rs/${months_rs}/g;s/+months_gs/${months_gs}/g;s/+months_ab/${months_ab}/g"`
canesm_load_histRS0_suffix_list=`echo $canesm_load_histRS0_suffix_list | sed "s/+months_rs/+${start_mon_rs}/g;s/+months_gs/+${start_mon_rs}/g;s/+months_ab/+${start_mon_rs}/g"`
canesm_load_histRS_suffix_list=`echo $canesm_load_histRS_suffix_list | sed "s/+months_rs/${months_rs}/g;s/+months_gs/${months_gs}/g;s/+months_ab/${months_ab}/g"`

# The job created here uses the second character from uxxx to determine the type of
# pooling and/or the prefix for diagnostic and time series files
# Verify that uxxx contains a reasonable value
[ -z "$uxxx" ] && bail "uxxx must be defined"
ch2=$(echo $uxxx|awk '{print substr($1,2,1)}' -)
[ -z "$ch2" ] && bail "Invalid uxxx = $uxxx"
case $ch2 in
  a|m|c|r|d|f) ;; # These are valid
  *) bail "Invalid prefix found in uxxx = $uxxx" ;;
esac

stamp=`date "+%j%H%M%S"$$`
diagjob_sfx=diagjob_`echo ${CMCFEDEST} | cut -f2 -d'-'`_$stamp
jobdefs=jobdefs_diagjob_$stamp
cat >> $jobdefs << end_jobdefs
  uxxx=$uxxx
  runid=$runid
  months=$months
  months_run=$months_run
  months_gcm=$months_gcm
  chunk_size=$chunk_size
  rtd_xtrachem=$rtd_xtrachem
  rtd_ssvars=$rtd_ssvars
  keep_old_rtdiag=$keep_old_rtdiag
  noprint=$noprint
  debug=$debug
  crawork=${runid}_${diagjob_sfx}
  delt=$delt
  year_rtdiag_start=$year_rtdiag_start
  month_rtdiag_start=$month_rtdiag_start
  float1=$float1
  nemo_jpnij=$nemo_jpnij
  output_level=$output_level

  # Diagnostics options
  gssave=$gssave
  spsave=$spsave
  gpxsave=$gpxsave
  wxstats=$wxstats
  nocleanup=$nocleanup
  tdfiles=$tdfiles
  daily_cmip6_tiers=$daily_cmip6_tiers
  issp=$issp
  isgg=$isgg
  israd=$israd
  isbeg=$isbeg
  memory_agcm_diag=$memory_agcm_diag
  CCRNTMP_agcm_diag=$CCRNTMP_agcm_diag
  TMPFS_agcm_diag=$TMPFS_agcm_diag
  memory_agcm_rtd=$memory_agcm_rtd
  CCRNTMP_agcm_rtd=$CCRNTMP_agcm_rtd
  TMPFS_agcm_rtd=$TMPFS_agcm_rtd

  # NOTE: if GETHIST, defined below, is set to null then all xc2ppp_* variables are ignored

  # Define a year/month range that is specific to xc2ppp
  # Files to be transferred will fall within this year/month range (inclusive of end points)
  # These variables may differ from (start/stop)_(year/month) that are defined above but in this context
  # they should be the same
  xc2ppp_start_year=\$current_year
  xc2ppp_start_month=\$current_month
  xc2ppp_stop_year=\$next_year
  xc2ppp_stop_month=\$next_month

  xc2ppp0_start_year=$start_year_rs
  xc2ppp0_start_month=$start_mon_rs
  xc2ppp0_stop_year=$start_year_rs
  xc2ppp0_stop_month=$start_mon_rs

  # The prefix used during creation of the list of file names that are to be transferred
  xc2ppp_uxxx=${xc2ppp_uxxx:-$uxxx}

  # xc2ppp_suffix_list will contain a white space separated list of file name suffixes and is used
  # by xc2ppp during creation of the list of file names that are to be transferred
  # File names are of the form: ${pfx}_${runid}_${year}_m${month}_$sfx where
  # the prefix pfx is the value of xc2ppp_uxxx, if set. If not then pfx is the value of uxxx, if set.
  # If uxxx is also not set then pfx is the first 3 characters of the invoking users name.
  xc2ppp_suffix_list="${xc2ppp_suffix_list}"

  # xc2ppp_delete_files indicates whether to delete files from xc40 (lustre) after transfer (on) or not (off)
  xc2ppp_delete_files="${xc2ppp_delete_files}"

  # xc2ppp_keep_file_list indicates whether to keep (=on) or remove (=off) the list of files
  # to be transfered in ~/.queue directory. The default is =on.
  xc2ppp_keep_file_list="${xc2ppp_keep_file_list}"

  # list of files to transfer before the very 1st year of the run (initial restart files, etc.)
  xc2ppp0_suffix_list="${xc2ppp0_suffix_list}"

  # xc2ppp0_delete_files indicates whether to delete files from xc40 (lustre) after transfer (on) or not (off)
  xc2ppp0_delete_files="${xc2ppp0_delete_files}"

  # xc2ppp0_keep_file_list indicates whether to keep (=on) or remove (=off) the list of files
  # to be transfered in ~/.queue directory. The default is =on.
  xc2ppp0_keep_file_list="${xc2ppp0_keep_file_list}"

  # This is a list of files which will get loaded from tape to sitestore using hpcarchive.
  canesm_load_hist_suffix_list="${canesm_load_hist_suffix_list}"
  hpcarc_user="$hpcarc_user"

  # This is a list of history files for the very 1st year.
  canesm_load_histRS0_prefix="${canesm_load_histRS0_prefix}"
  canesm_load_histRS0_suffix_list="${canesm_load_histRS0_suffix_list}"

  # This is a list of restart files which will get loaded from tape to sitestore using hpcarchive.
  canesm_load_histRS_prefix="${canesm_load_histRS_prefix}"
  canesm_load_histRS_suffix_list="${canesm_load_histRS_suffix_list}"

  # Archive short term switch
  canesm_dump_hist_short_term=$canesm_dump_hist_short_term
  canesm_dump_histRS_short_term=$canesm_dump_histRS_short_term
  canesm_dump_histRS0_short_term=$canesm_dump_histRS_short_term
  canesm_dump_diag_short_term=$canesm_dump_diag_short_term
  canesm_dump_tser_short_term=$canesm_dump_tser_short_term

  # Archive checksum switch
  hpcarchive_checksum=$hpcarchive_checksum

  # List of time series variables to load
  tser_load_vars="${tser_load_vars}"

  # mdeleteBE_suffix_list indicates the model file suffixes to remove on backend after transfer is done
  mdeleteBE_suffix_list="${mdeleteBE_suffix_list}"
  mdeleteBE_bexfer="${mdeleteBE_bexfer}" # =off to delete files on frontend, =on to delete files on backend
  mdeleteBE_leave_last_mon="${mdeleteBE_leave_last_mon}" # =off to delete full year, =on to leave last month from previous year

  year_offset=0

  # NEMO rebuilding
  canesm_nemo_rbld_year=$start_year
  canesm_nemo_rbld_save_hist=1

  # In the first year, rebuild only the nemors
  canesm_nemo_rbld1st_save_hist=0

  nemo_rbld_hist_file_suffix_list="$nemo_rbld_hist_file_suffix_list"
  nemo_rbld_hist_file_freq_list="$nemo_rbld_hist_file_freq_list"

  # NEMO RTD executables
  nemo_physical_rtd_exe=$nemo_physical_rtd_exe
  nemo_ice_rtd_exe=$nemo_ice_rtd_exe
  nemo_carbon_rtd_exe=$nemo_carbon_rtd_exe
  nemo_rtd_mons="$nemo_rtd_mons"

  # Coupler RTD executables
  coupler_rtd_exe=$coupler_rtd_exe
  coupler_rtd_mons="$coupler_rtd_mons"
  # nemoval diag settings
  with_nemoval_diag=$with_nemoval_diag
  nemoval_repeat_period=$nemoval_repeat_period
  nemoval_avg_period=$nemoval_avg_period
  nemoval_res=$nemoval_res
  nemoval_root=$nemoval_root
  nemoval_pltyml=$nemoval_pltyml

  # Variables needed for offline diagnostics
  nemo_config=$nemo_config

  # netcdf conversion variables
  ncconv_cmmt=$ncconv_cmmt
  pycmor_env=$pycmor_env
  ncconv_exptab=$ncconv_exptab
  ncconv_exptab_repo=$ncconv_exptab_repo
  ncconv_tabs2conv=$ncconv_tabs2conv
  source_id=$source_id
  override_source_id=$override_source_id
  activity_id=$activity_id
  override_activity_id=$override_activity_id
  experiment_id=$experiment_id
  override_experiment_id=$override_experiment_id
  subexperiment_id=$subexperiment_id
  override_subexperiment_id=$override_subexperiment_id
  variant_label=$variant_label
  parent_runid=$parent_runid
  parent_branch_time=$parent_branch_time
  run_start_time=$run_start_time
  run_stop_time=$run_stop_time
  add_cccma_vars=$add_cccma_vars

  # Time series related variables
  nemo_timeseries=$nemo_timeseries
  diag_uxxx=d$ch2

  diag2ts_prefix_list=$diag2ts_prefix_list
  diag2ts_suffix_list=$diag2ts_suffix_list

  # These variables are used to determine if and where spltdiag will copy
  # time series files to a remote machine
  # spltdiag_trans = on|off ...on means transfer time series to the remote machine
  spltdiag_trans=off
  # spltdiag_remserver is the name of the remote host used when spltdiag_trans = on
  # spltdiag_remserver=''
  # spltdiag_remdir is the name of an existing directory on the remote host into which
  # the time series files will be copied when spltdiag_trans = on
  # spltdiag_remdir=''

  # Allow user to define a list of specific variables (ie superlabels) that will
  # limit the number of files that spltdiag creates
  # spltdiag_vars=''

  diag2ts_load_diag=off
  diag2ts_delete_diag=off
  diag2ts_transfer_time_series=off
  # diag2ts_transfer_all_dd=''
  # diag2ts_CCRNTMP=''
  # diag2ts_RUNPATH=''
  # diag2ts_RMTRUNPATH=''
  # diag2ts_remusr=''
  # diag2ts_remserver=''
  # diag2ts_rem_save=''
  diag2ts_with_gztsdiag=off
  # diag2ts_gztsdiag_deck1=''
  # diag2ts_gztsdiag_deck2=''
  diag2ts_with_gz=off
  diag2ts_with_cp=off
  diag2ts_with_dd=off
  diag2ts_with_dp=off
  diag2ts_with_ds=off
  diag2ts_with_dsd=off
  diag2ts_gssave=off
  diag2ts_with_cfmip=off
  diag2ts_with_dcosp=off
  diag2ts_with_mcosp=off
  # diag2ts_with_lsarc
  diag2ts_delete_time_series=off
  diag2ts_dump_time_series=off
  # diag2ts_one_job_per_suffix
end_jobdefs

# Define the name of the file to contain the output job string
date1=`echo ${start_time[0]:-1} ${start_time[1]:-1} | awk '{printf "%3.3dm%2.2d",$1,$2}'`
date2=`echo ${stop_time[0]:-1} ${stop_time[1]:-12} | awk '{printf "%3.3dm%2.2d",$1,$2}'`
if [[ ${#start_time[@]} -gt 2 ]]; then
  [ -n "${start_time[2]}" ] && printf -v d1 "d%2.2d" ${start_time[2]} && date1+="$d1"
fi
if [[ ${#stop_time[@]} -gt 2 ]]; then
  [ -n  "${stop_time[2]}" ] && printf -v d2 "d%2.2d" ${stop_time[2]}  && date2+="$d2"
fi

# Define job descriptions for components of the job string

# Copy history files from the back end to sitestore
# and save them on ppp1 or ppp2 (whichever machine runs this string)
if [ $with_gethist -eq 1 ]; then
  if [ $start_year -eq $run_start_year -a $start_mon -eq $run_start_month ] ; then
    # transfer additional restart files before the very 1st year
    # (controlled by xc2ppp0_* variables)
    GETHIST="xc2ppp0:n xc2ppp:${months_pack}"
  else
    GETHIST="xc2ppp:${months_pack}"
  fi
else
  GETHIST=''
fi

# Delete history files on xc40 after transfer
if [ $with_delhistBE -eq 1 ]; then
  DELHISTBE="mdeleteBE:${chunk_size}m"
else
  DELHISTBE=''
fi

# Repack AGCM history files.
if [ $with_gcmpak -eq 1 ]; then
  GCMPAK="canesm_gcmpak:${months_pack}"
else
  GCMPAK=''
fi

# Create run-time diagnostics files from history files
if [ $with_rtd -eq 1 ]; then
  RTDIAG="canesm_rtd_agcm:12m"
  echo "Doing AGCM RTD"
else
  RTDIAG=''
fi

if [ $with_rtd_nemo -eq 1 ]; then
  RTDIAG_NEMO="canesm_rtd_nemo:12m"
  echo "Doing NEMO RTD"
else
  RTDIAG_NEMO=''
fi

if [ $with_rbld_nemo -eq 1 ]; then
  if [ $start_year -eq $run_start_year -a $start_mon -eq $run_start_month ] ; then
    # Rebuild additional restart files before the very 1st year
    # (controlled by canesm_nemo_rbld1st_* variables)
    RBLD_NEMO="canesm_nemo_rbld1st:n canesm_nemo_rbld:${months_pack}"
  else
    RBLD_NEMO="canesm_nemo_rbld:${months_pack}"
  fi
else
  RBLD_NEMO=''
fi

if [ $with_nemo_bgc_diag -eq 1 ]; then
    NEMO_BGC_DIAG="canesm_nemo_bgc_diag:12m"
else
    NEMO_BGC_DIAG=''
fi

if [ $with_nemo_diag -eq 1 ]; then
  DIAG_NEMO="canesm_nemo_diag:12m"
 else
  DIAG_NEMO=''
fi

if [ $with_rtd_cpl -eq 1 ]; then
  RTDIAG_CPL="canesm_rtd_coupler:12m"
  echo "Doing Coupler RTD"
else
  RTDIAG_CPL=''
fi

# Create diagnostics files from history files
if [ $with_diag -eq 1 ]; then
  if [ $agcm_diag_parallel -eq 1 ] ; then
    CREATEDIAG="$diag_basefile:${chunk_size}m"
  else
    CREATEDIAG="$diag_basefile:m"
  fi
else
  CREATEDIAG=''
fi

# Create time series files from diagnostic files
if [ $with_time_series -eq 1 ]; then
  TIMESERIES=`echo "${ch2}diag2ts:${chunk_size}m"|sed 's/ //g'`
else
  TIMESERIES=''
fi

# Convert subset of output to netcdf files
if [ $with_netcdf_conv -eq 1 ]; then
  NETCDFCONV="canesm_netcdf_conv:12m"
else
  NETCDFCONV=""
fi

# Dump/delete files on ppp in a parallel job
if [ $with_dump_hist -eq 1 -o $with_dump_rs -eq 1 -o $with_delhistFE -eq 1 -o $with_dump_diag -eq 1 -o $with_deldiag -eq 1 -o $with_dump_tser -eq 1 -o $with_dump_nc -eq 1 ]; then
  DUMPPOST="canesm_dump_post:${chunk_size}m"
else
  DUMPPOST=''
fi

# Parallel diagnostic job
if [ $with_dpar -eq 1 ]; then
  DIAGPAR="canesm_dpar:${chunk_size}m"
else
  DIAGPAR="$CREATEDIAG $TIMESERIES $NETCDFCONV $DELHISTBE $DUMPPOST"
fi

# Load restart files from tape
if [ $with_load_rs -eq 1 ]; then
  if [ $start_year -eq $run_start_year -a $start_mon -eq $run_start_month ] ; then
    # load additional files before the very 1st year
    LOADRS="canesm_load_histRS0:n canesm_load_histRS:1m"
  else
    LOADRS="canesm_load_histRS:1m"
  fi
else
  LOADRS=''
fi

# Load history files from tape
if [ $with_load_hist -eq 1 ]; then
  LOADHIST="canesm_load_hist:1m"
else
  LOADHIST=''
fi

# Load diagnostic files to tape
if [ $with_load_diag -eq 1 ]; then
  LOADDIAG="canesm_load_diag:${chunk_size}m"
else
  LOADDIAG=''
fi

# Load time series files to tape
if [ $with_load_tser -eq 1 ]; then
  LOADTSER="canesm_load_tser:${chunk_size}m"
else
  LOADTSER=''
fi

# Run code checking and update logs
[ $production -eq 1 ] && flgs="" || flgs="-d"   # use 'development' mode if production is off
strict_check $flgs $runid create-diag-job-string-${date1}_${date2} canesm.cfg make_diag_job_${runid}
[ $? -ne 0 ] && exit 1

# Job description
JOBDESC="$LOADRS $LOADHIST $LOADDIAG $LOADTSER $GETHIST $GCMPAK $RTDIAG $RBLD_NEMO $RTDIAG_NEMO $RTDIAG_CPL $DIAG_NEMO $NEMO_BGC_DIAG $DIAGPAR"
echo JOBDESC=$JOBDESC

# Create the complete job string
range="${date1}_${date2}"
fout="${runid}_${range}_diag_job"
if [ ! -z "${JOBDESC// }" ] ; then
  cccjob --out=$fout --job="$JOBDESC" --start=$start --stop=$stop $jobdefs
fi
rm -f $jobdefs
