#!/bin/bash
## g.e. # WRF+LMDZ_launch.bash 19790101000000 19800101000000 28 /d4/lflmd/etudes/WRF_LMDZ/test_phylmd/AR40.0/control
## g.e. # WRF+LMDZ_launch.bash 19790101000000 19800101000000 month /d4/lflmd/etudes/WRF_LMDZ/test_phylmd/AR40.0/control
if test $1 = '-h'; then
  echo "*************************************"
  echo "*** Launching WRF+LMDZ simulation ***"
  echo "*************************************"
  echo "WRF+LMDZ_launch.bash [inidate] [enddate] [freq] [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 "  [odir]: folder for the outputs"
  echo "  [restart]: 'true' for a resume a simulation"
else

checking_date() {
# Function to check date (in [YYYY][MM][DD][HH][MI][SS] format)
   fname='checking_date'

   errfunc='ERROR -- error -- ERROR -- error'

  datev=$1

  Ldate=`expr length ${datev}`
  if test ${Ldate} -ne 14; then
    echo ${errfunc}
    echo "  "${fname}": date '"${datev}"' does not have the appropriated length: "   \
      ${Ldate}" should be: 14 !!!!"
    exit
  fi

  yr=${datev:0:4}
  mon=${datev:4:2}
  day=${datev:6:2}
  YMD1=${datev:0:8}
  hour=${datev:8:2}
  min=${datev:10:2}
  sec=${datev:12:2}

  datefmt=${yr}'/'${mon}'/'${day}' '${hour}':'${min}':'${sec}
# Checking individually
#
# yr
  chkyr=`date -d"${yr}0101"`
  if test $? -ne 0; then
    echo ${errfunc}
    echo "  "${fname}": "${datefmt}" wrong year '"${yr}"' !!!!"
    exit
  fi
# mon
  chkyr=`date -d"${yr}${mon}01"`
  if test $? -ne 0; then
    echo ${errfunc}
    echo "  "${fname}": "${datefmt}" wrong month '"${mon}"' !!!!"
    exit
  fi
# day
  chkyr=`date -d"${yr}${mon}${day}"`
  if test $? -ne 0; then
    echo ${errfunc}
    echo "  "${fname}": "${datefmt}" wrong day '"${day}"' !!!!"
    exit
  fi
# hour
  if test ${hour} -gt 23; then
    echo ${errfunc}
    echo "  "${fname}": "${datefmt}" wrong hour '"${hour}"' !!!!"
    exit
  fi
# minute
  if test ${min} -gt 59; then
    echo ${errfunc}
    echo "  "${fname}": "${datefmt}" wrong minute '"${min}"' !!!!"
    exit
  fi
# second
  if test ${sec} -gt 59; then
    echo ${errfunc}
    echo "  "${fname}": "${datefmt}" wrong second '"${sec}"' !!!!"
    exit
  fi
#  echo ${datefmt}
}

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_WRFnamelist() {
# Function to create namelist.input from a nameslit WRF template
#   nlistmplt: template of the namelist.input
#   id: initial date ([YYYYMMDDHHMISS] format)
#   ed: final date ([YYYYMMDDHHMISS] format)
#   fr: frquency (in days) of the restarts
#   it: number of sub-period within the simulation experiment

  nlisttmplt=$1
  id=$2
  ed=$3
  fr=$4
  it=$5

  frH=`expr ${fr} '*' 24`

  dThist=`cat ${nlisttmplt} | grep history_interval | awk '{print $3}' | tr ',' ' ' |\
     awk '{print $1*60}'`

  secsPeriod=`seconds_between_dates ${id} ${ed}`
  Nouts=`expr ${secsPeriod} / ${dThist}`

  cp ${nlisttmplt} namelist.input
  sed -e 's/@iyear@/'${id:0:4}'/g' namelist.input >& tmpA
  sed -e 's/@imonth@/'${id:4:2}'/g' tmpA >& tmpB
  sed -e 's/@iday@/'${id:6:2}'/g' tmpB >& tmpA
  sed -e 's/@ihour@/'${id:8:2}'/g' tmpA >& tmpB
  sed -e 's/@iminute@/'${id:10:2}'/g' tmpB >& tmpA
  sed -e 's/@isecond@/'${id:12:2}'/g' tmpA >& tmpB

  sed -e 's/@eyear@/'${ed:0:4}'/g' tmpB >& tmpA
  sed -e 's/@emonth@/'${ed:4:2}'/g' tmpA >& tmpB
  sed -e 's/@eday@/'${ed:6:2}'/g' tmpB >& tmpA
  sed -e 's/@ehour@/'${ed:8:2}'/g' tmpA >& tmpB
  sed -e 's/@eminute@/'${ed:10:2}'/g' tmpB >& tmpA
  sed -e 's/@esecond@/'${ed:12:2}'/g' tmpA >& tmpB
  sed -e 's/@Nouts@/'${Nouts}'/g' tmpB >& tmpA
  sed -e 's/@freqH@/'${frH}'/g' tmpA >& tmpB
  if test ${it} -gt 1; then
    sed -e 's/@restart@/.true./g' tmpB >& namelist.input
  else
    sed -e 's/@restart@/.false./g' tmpB >& namelist.input
  fi

  rm tmpA tmpB
}

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

#  dd=`echo ${id:6:2} | awk '{print $1 + 0}'`
#  day=`printf %d ${dd}`

  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
    #######

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

  inidate=$1
  enddate=$2
  freq=$3
  odir=$4
  if test $# -eq 5; then
    restart=$5
  else
    restart='false'
  fi

  wrftmplt=${odir}'/namelist.input.template'
  lmdztmplt=${odir}'/run.def.template'

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

  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 ${wrftmplt}; then
    echo $errmsg
    echo "File '"${wrftmplt}"' does not exist!!!!"
    exit
  fi

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

  idate=${inidate}
  if test ${restart} = 'true'; then
    isubperiod=2
  else
    isubperiod=1
  fi

  checking_date ${idate}
  checking_date ${enddate}

  if test ${restart} = 'true'; then
    echo "Continuing the simulation from the last wrfrst"
  else
    rm -r ${odir}/wrfout
    rm -r ${odir}/lmdzout
    rm run_wrf_??????????????-??????????????.log
    mkdir -p ${odir}/wrfout
    mkdir -p ${odir}/lmdzout
  fi

  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}
# Checking for restart
##
    runperiod=true
    if test ${restart} = 'true' && test -f ${odir}/wrfout/wrfrst_d01_${nextdate:0:4}-${nextdate:4:2}-${nextdate:6:2}_${nextdate:8:2}:${nextdate:10:2}:${nextdate:12:2}; then
      runperiod=false
    else
      runperiod=true
      cp ${odir}/wrfout/wrfrst_d01_${idate:0:4}-${idate:4:2}-${idate:6:2}_${idate:8:2}:${idate:10:2}:${idate:12:2} ${odir}
      echo "  resuming the simulation from: "${idate:0:4}-${idate:4:2}-${idate:6:2}_${idate:8:2}:${idate:10:2}:${idate:12:2}
    fi

    if ${runperiod}; then
      echo "    "${isubperiod}" "${period}

      create_WRFnamelist ${wrftmplt} ${idate} ${nextdate} ${freqV} ${isubperiod}
      create_LMDZnamelist ${lmdztmplt} ${idate} ${freqV}

      ./wrf.exe >& ${odir}/run_wrf_${period}.log
      ewrf=$?

      if test ${ewrf} -ne 0; then
        echo ${errmsg}
        echo "  wrf.exe failed !!!"
        cat run_wrf_${period}.log
        exit
      fi
# Moving outputs
##
      mv namelist.input ${odir}/wrfout/namelist.input_${period}
      mv namelist.output ${odir}/wrfout/namelist.output_${period}
      mv wrfout_d* ${odir}/wrfout
      mv run_wrf_${period}.log ${odir}/wrfout
      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 wrfrst*${idate:0:4}-${idate:4:2}-${idate:6:2}* ${odir}/wrfout
      fi
    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_WRFnamelist ${wrftmplt} ${idate} ${nextdate} ${freqV} ${isubperiod}
    create_LMDZnamelist ${lmdztmplt} ${idate} ${freqV}

    ./wrf.exe >& ${odir}/run_wrf_${period}.log
    ewrf=$?
    if test ${ewrf} -ne 0; then
      echo ${errmsg}
      echo "  wrf.exe failed !!!"
      cat run_wrf_${period}.log
      exit
    fi
# Moving outputs
##
    mv namelist.input ${odir}/wrfout/namelist.input_${period}
    mv namelist.output ${odir}/wrfout/namelist.output_${period}
    mv wrfout_d* ${odir}/wrfout
    mv run_wrf_${period}.log ${odir}/wrfout
    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 wrfrst*${idate:0:4}-${idate:4:2}-${idate:6:2}* ${odir}/wrfout
    fi
  fi

# Post-process LMDZ hist files
##

  dimx=`cat ${odir}/wrfout/namelist.input_${period} | grep e_we | awk '{print $3}' | tr ',' ' ' | awk '{print $1 - 1}'`
  dimy=`cat ${odir}/wrfout/namelist.input_${period} | grep e_sn | awk '{print $3}' | tr ',' ' ' | awk '{print $1 - 1}'`
  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
