#! /bin/tcsh -f

# multirun.tcsh calls CAABA/MECCA for each entry in inputfile $1
# original code: Hartwig Harder, 2009-...
# modified:      Rolf Sander,    2009-...

# Before starting this script, make sure that "ncks" from the netCDF
# Operators is available, e.g. with "nco_init".

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

if ( ! -f multirun/multirun.tcsh ) then
  echo "ERROR: multirun.tcsh must be started from caaba"
  echo "       directory, preferably via xcaaba"
  exit 1
endif

if ( $#argv == 0 ) then
  echo "multirun.tcsh = multiple runs of CAABA/MECCA"
  echo "usage: start this script vix xcaaba"
  exit
endif

set basedir = `pwd`
# set LC_ALL for printf:
setenv LC_ALL C

# define hline string:
set hline = "---------------------------------------"
set hline = "$hline$hline"

# add full path to input file name:
cd `dirname $1`
set ncfile1    = "$PWD/`basename $1`"
cd -

set ncfile2    = "tmp_`basename $1`"

echo $hline
echo "START OF MULTIRUN"
echo $hline

if ( ! -f $ncfile1 ) then
  echo "ERROR: inputfile $ncfile1 does not exist"
  exit 1
endif

if (! -d $basedir/output/multirun) mkdir $basedir/output/multirun
set outputdir = "$basedir/output/multirun/$ncfile1:t:r"
# if directory exists already, rename it:
if ( -d $outputdir ) then
  set backupdir = "$outputdir-`date -r $outputdir +'%Y-%m-%d-%H:%M:%S'`"
  mv $outputdir $backupdir
endif
mkdir $outputdir
set logfile = "$outputdir/multirun.log"
mkdir $outputdir/runs

echo
echo "inputdir  = `dirname $ncfile1`/" | tee -a $logfile
echo "inputfile = $ncfile1:t"          | tee -a $logfile
echo                                   | tee -a $logfile

# extract first line from $ncfile1 to $ncfile2:
set line = 1
set ret = (`ncks -F -O -d time,$line $ncfile1 $ncfile2`)

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

while (${#ret} == 0)
  set err = 0
  # define line number with 4 digits:
  set line4 = `printf "%4.4d" $line`
  # --------------------------------------------------------------------------
  # temperature:
  set temp = (`ncks -F -s "%10.10g" -H -C -d time,$line -v temp $ncfile1 |awk '{print $1+273.15}'`)
  set errstatus = (`echo $temp | awk '{if ($1<0) print "ERROR"}'`)
  if ( ${#errstatus} > 0) then
    set err = 1
  endif
  # --------------------------------------------------------------------------
  # pressure:
  set press = (`ncks -F -s "%10.10g" -H -C -d time,$line -v press $ncfile1`)
  set errstatus = (`echo $press | awk '{if ($1<0) print "ERROR"}'`)
  if ( ${#errstatus} > 0) then
    set err = 1
  endif
  # --------------------------------------------------------------------------
  printf "Simulation $line4 with T = %6.2f K, p = %6.0f Pa" $temp $press | tee -a $logfile

  # --------------------------------------------------------------------------

  if ( $err == 0 ) then

    # create nml file:
    set nmlfile = tmp_caaba.nml
    echo "! -*- f90 -*- (created by multirun.tcsh, do not edit\!)" > $nmlfile
    echo "&CAABA"                    >> $nmlfile
    echo "USE_MECCA = T"             >> $nmlfile
    echo "USE_READJ = T"             >> $nmlfile
    echo "temp = $temp"              >> $nmlfile
    echo "press = $press"            >> $nmlfile
    echo "photrat_channel = 'readj'" >> $nmlfile
    echo "init_spec = '$ncfile2'"    >> $nmlfile
    echo "init_j = '$ncfile2'"       >> $nmlfile
    echo "l_steady_state_stop = T"   >> $nmlfile
    echo "/"                         >> $nmlfile
    ln -fs $nmlfile caaba.nml
    # remove old *.nc files but ignore it if there are none:
    rm caaba_*.nc >& /dev/null
    # run the CAABA/MECCA box model:
    ./caaba.exe > caaba.log
    set exitstatus = `cat status.log`
    if ( "$exitstatus" != "0" ) then
      echo "ERROR: exit status from 'caaba.exe' is: $exitstatus"
      exit 1
    endif

    # MaxTime info:
    set MaxTime = (`ncks -M caaba_mecca.nc | awk '/name = time, size =/ {print $8}'`)
    @ MaxTime--
    printf ": finished (MaxTime=%d)\n" $MaxTime | tee -a $logfile
    # copy MaxTime info from caaba_mecca.nc to caaba_mecca_c_end.nc:
    # see also: http://nco.sourceforge.net/nco.html#Examples-ncap2
    ncap2 -A -s 'maxtime=($time.size-1)' caaba_mecca.nc caaba_mecca_c_end.nc
    # broadcast scalar maxtime to dimension (time, lev, lat, lon):
    ncdump caaba_mecca_c_end.nc | \
      sed 's|int maxtime|float maxtime(time, lev, lat, lon)|' | \
      ncgen -b

    # move/copy model output to another directory:
    mkdir $outputdir/runs/$line4
    mv $ncfile2 $outputdir/runs/$line4/input.nc
    cp -p caaba.log caaba.nml mecca.nml *.nc $outputdir/runs/$line4

  else

    printf ": ERROR\n" | tee -a $logfile

  endif

  @ line++
  # extract line number $line from $ncfile1 to $ncfile2:
  set ret = (`ncks -F -O -d time,$line $ncfile1 $ncfile2`)
end

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

echo "Creating zip file of caaba model code. Please wait..."
gmake zip >> $logfile
mv `basename $PWD`.zip $outputdir

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

# merge netcdf files, based on code in montecarlo.tcsh:
cd $outputdir
set fullfilenames = (caaba_mecca_c_end.nc caaba_mecca_k_end.nc input.nc)
echo;echo "Merging the netcdf files:"

foreach fullfilename ($fullfilenames)
  set ncfile = `basename $fullfilename`
  echo "Working on $ncfile"
  echo -n "Multirun"
  foreach murun (runs/*)
    set basemurun = `basename $murun`
    echo -n " $basemurun"
    if ( "$fullfilename" != "input.nc" ) then
      # put Multirun number into time:
      ncclamp $murun/$ncfile time 0 $basemurun gt
    endif
  end
  echo " done"
  # concatenate files along time:
  ncrcat -O runs/*/$ncfile $ncfile
end

cd -

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

echo;echo "The model output is now in:"
echo "output/multirun/`basename ${outputdir}`"
cd $outputdir
ls runs
ls -la *.*
cd -

# cleanup:
rm tmp_*
ln -fs nml/caaba_simple.nml caaba.nml

echo;echo $hline
echo "END OF MULTIRUN"
echo $hline

exit

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