#!/bin/bash 
## e.g. # LMDZ_launch.bash 19790101000000 19800101000000 28 32:32:39 /d4/lflmd/etudes/WRF_LMDZ/lmdz/AR40.0/control
## e.g. # LMDZ_launch.bash 19790101000000 19800101000000 month 32:32:39 /d4/lflmd/etudes/WRF_LMDZ/lmdz/AR40.0/control
if test $1 = '-h'; then
  echo "*********************************"
  echo "*** Launching LMDZ simulation ***"
  echo "*********************************"
  echo "LMDZ_launch.bash [inidate] [enddate] [freq] [dim] [odir]"
  echo "  [inidate]: initial date [YYYY][MM][DD][HH][MI][SS])" 
  echo "  [enddate]: final date [YYYY][MM][DD][HH][MI][SS])"
  echo "  [freq]: frequency restarts [DD] if it is 'month' real month frequency will be used)"
  echo "  [dim]: dimensions (dimx:dimy:dimz)"
  echo "  [odir]: folder for the outputs)"
else

seconds_between_dates() {
# Functino to provide the seconds between two dates
  date1=$1
  date2=$2

  # Date1
  ##
  YMD1=${date1:0:8}
  hours1=${date1:8:2}
  minutes1=${date1:10:2}
  seconds1=${date1:12:2}
  hours1=`(expr $hours1 '*' 3600)`
  minutes1=`(expr $minutes1 '*' 60)`
  seconds1=`(expr $hours1 + $minutes1 + $seconds1)`
  sec1=`(date +%s -u -d"$YMD1 $seconds1 seconds")`

  # Date2
  ##
  YMD2=${date2:0:8}
  hours2=${date2:8:2}
  minutes2=${date2:10:2}
  seconds2=${date2:12:2}
  hours2=`(expr $hours2 '*' 3600)`
  minutes2=`(expr $minutes2 '*' 60)`
  seconds2=`(expr $hours2 + $minutes2 + $seconds2)`
  sec2=`(date +%s -u -d"$YMD2 $seconds2 seconds")`
  seconds=`(expr $sec2 - $sec1)`

  echo $seconds
}

create_LMDZnamelist() {
# Function to create run.def from a LMDZ template
#   nlistmplt: template of the run.def
#   id: initial date (in [YYYY][MM][DD][HH][MI][SS] format)
#   fr: frquency (in days) of the restarts

  nlisttmplt=$1
  id=$2
  fr=$3

  day=`date -u "+%j" -d"${id:0:8}"`

  cp ${nlisttmplt} run.def
  sed -e 's/@freq@/'${fr}'/g' run.def >& tmpA
  sed -e 's/@iyear@/'${id:0:4}'/g' tmpA >& tmpB
  sed -e 's/@iday@/'${day}'/g' tmpB >& run.def

  cp config.def.template tmpA
  sed -e 's/@daysmonth@/'${fr}'/g' tmpA >& config.def

  rm tmpA tmpB
}

########    #######
## MAIN
    #######

  export LD_LIBRARY_PATH=/u/lflmd/bin/gcc_netcdf-4.3.0/lib:${LD_LIBRARY_PATH}

  rootsh=`pwd`
  errmsg='ERROR -- error -- ERROR -- error'

  inidate=$1
  enddate=$2
  freq=$3
  dim=$4
  odir=$5

  lmdztmplt='run.def.template'

####### ###### #### ### ## # 

  dimx=`echo ${dim} | tr ':' ' ' | awk '{print $1 - 1}'`
  dimy=`echo ${dim} | tr ':' ' ' | awk '{print $2 - 1}'`
  dimz=`echo ${dim} | tr ':' ' ' | awk '{print $3}'`

  export PATH=/u/lflmd/bin/gcc_Python-2.7.5/bin:${PATH}
  export LD_LIBRARY_PATH=/u/lflmd/bin/gcc_netcdf-4.3.0/lib:/opt/intel/composer_xe_2011_sp1.9.293/compiler/lib/intel64:/opt/intel/composer_xe_2011_sp1.9.293/compiler/lib/intel64:/opt/intel/composer_xe_2011_sp1.9.293/mkl/lib/intel64:/opt/intel/composer_xe_2011_sp1.9.293/tbb/lib/intel64//cc4.1.0_libc2.4_kernel2.6.16.21:/usr/local/lib:/opt/intel/composer_xe_2011_sp1.9.293/debugger/lib/intel64:/opt/intel/composer_xe_2011_sp1.9.293/mpirt/lib/intel64

  if test ! -f ${lmdztmplt}; then
    echo $errmsg
    echo "File '"${lmdztmplt}"' does not exist!!!!"
    exit
  fi

  idate=${inidate}
  isubperiod=1

  rm -r ${odir}/lmdzout
  rm run_lmdz_??????????????-??????????????.log
  mkdir -p ${odir}/lmdzout

  while test ${idate} -le ${enddate}; do
    if test ${freq} = 'month'; then
      nextdate=`date +%Y%m%d%H%M%S -d"${idate:0:8} 1 month"`
      secmonths=`seconds_between_dates ${idate} ${nextdate}`
      freqV=`expr ${secmonths} / 24 / 3600`
    else
      nextdate=`date +%Y%m%d%H%M%S -d"${idate:0:8} ${freq} days"`
      freqV=${freq}
    fi
    if test ${nextdate} -gt ${enddate}; then break; fi
    period=${idate}'-'${nextdate}
    echo ${isubperiod}" "${period}

    create_LMDZnamelist ${lmdztmplt} ${idate} ${freqV}

    ./lmdz.exe >& ${odir}/run_lmdz_${period}.log
    elmdz=$?

    if test ${elmdz} -ne 0; then
      echo ${errmsg}
      echo "  lmdz.exe failed !!!"
      cat run_lmdz_${period}.log
      exit
    fi
# Moving outputs
##
    mv ${odir}/run_lmdz_${period}.log ${odir}/lmdzout/run_lmdz_${period}.log
    mv run.def ${odir}/lmdzout/run.def_${period}
    mv config.def ${odir}/lmdzout/config.def_${period}
    mv histmth.nc ${odir}/lmdzout/histmth_${period}.nc
    mv histday.nc ${odir}/lmdzout/histday_${period}.nc
    mv histins.nc ${odir}/lmdzout/histins_${period}.nc

    if test ${isubperiod} -gt 1; then
      mv restartphy.nc ${odir}/lmdzout/restartphy_${period}.nc
      mv restart.nc ${odir}/lmdzout/restart_${period}.nc
    fi
    
    lastdate=${idate}
    idate=${nextdate}
    isubperiod=`expr ${isubperiod} + 1`

# end of dates
  done

  isubperiod=`expr ${isubperiod} + 1`
  if test ${nextdate} -gt ${enddate} && test ${idate} -ne ${enddate}; then
    nextdate=${enddate}
    period=${idate}'-'${nextdate}
    echo "last: "${period}
    secmonths=`seconds_between_dates ${idate} ${nextdate}`
    freqV=`expr ${secmonths} / 24 / 3600`
    create_LMDZnamelist ${lmdztmplt} ${idate} ${freqV}

    ./lmdz.exe >& ${odir}/run_lmdz_${period}.log
    ewfr=$?
    if test ${ewrf} -ne 0; then
      echo ${errmsg}
      echo "  lmdz.exe failed !!!"
      cat run_lmdz_${period}.log
      exit
    fi
# Moving outputs
##
    mv ${odir}/run_lmdz_${period}.log ${odir}/lmdzout/run_lmdz_${period}.log
    mv run.def ${odir}/lmdzout/run.def_${period}
    mv histmth.nc ${odir}/lmdzout/histmth_${period}.nc
    mv histday.nc ${odir}/lmdzout/histday_${period}.nc
    mv histins.nc ${odir}/lmdzout/histins_${period}.nc

    if test ${isubperiod} -gt 1; then
      mv restartphy.nc ${odir}/lmdzout/restartphy_${period}.nc
    fi
  fi

# Post-process LMDZ hist files
##

  for file in ${odir}/lmdzout/hist*.nc; do
    filen=`basename ${file}`
    filenH=`echo ${filen} | tr '.' ' ' | awk '{print $1}'`
    python ${HOME}/PY/WRFLMDZ_regularout.py -f ${file} -d ${dimx},${dimy} -o ${odir}/lmdzout/${filenH}_reg.nc 
    rm ${file}
    d1=`echo ${filen} | tr '_' ' ' | awk '{print $2}' | tr '-' ' ' | awk '{print $1}'`
    totsecs=`seconds_between_dates 19491201000000 ${d1}`

    python ${HOME}/climatescripts/python/nc_var.py -f ${odir}/lmdzout/${filenH}_reg.nc -o valmod -S sumc,${totsecs} -v time
    python ${HOME}/climatescripts/python/nc_var.py -f ${odir}/lmdzout/${filenH}_reg.nc -o addvattrk -S 'units|seconds!since!1949-12-01!00:00:00|S' -v time
  done

fi
