#! /bin/tcsh -f
# Time-stamp: <2010-12-02 21:00:58 sander>

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

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

set basedir = `pwd`
if (! -d $basedir/output/montecarlo) mkdir $basedir/output/montecarlo
set outputdir = "$basedir/output/montecarlo/`date +'%Y-%m-%d-%H:%M:%S'`"
mkdir $outputdir
mkdir $outputdir/runs

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

# delete output from old runs:
rm caaba_*.nc

set logfile = "$outputdir/montecarlo.log"

# Define "maxline", the number of Monte-Carlo runs here. Seeds are taken
# from mcexp_seed.txt which can for example be created with the number
# generator messy/mbm/rnd/rnd.f90-mecca. Note that maxline must not be
# larger than the number of lines in mcexp_seed.txt.
set maxline=100
#set maxline=1000

echo;echo $hline
echo "START OF MONTE-CARLO MODEL SIMULATIONS"
echo $hline

set line=0
while ($line<$maxline)
  @ line++ 
  set mcexp_seed = `head -n$line montecarlo/mcexp_seed.txt | tail -n1`
  # define line number with 4 digits:
  set line4 = `printf "%4.4d" $line`
  mkdir $outputdir/runs/$line4
  # test if mecca.nml is suitable for Monte-Carlo runs:
  set test = `grep mcexp_seed mecca.nml`
  if ( "$test" == "" ) then
    echo "ERROR: mecca.nml does not contain mcexp_seed"
    exit
  endif
  # copy to a temporary file. In-place editing with "sed -i" is not
  # possible because it converts the link mecca.nml into a real file
  cp mecca.nml tmp_mecca.nml
  sed "s|.*mcexp_seed.*| mcexp_seed = $mcexp_seed|" tmp_mecca.nml > mecca.nml
  printf "Simulation $line4 with seed = %10d" $mcexp_seed | tee -a $logfile

  # 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

  cp -p caaba.log caaba.nml mecca.nml *.nc $outputdir/runs/$line4
  set MaxTime = (`ncks -M caaba_mecca.nc | awk '/name = time, size =/ {print $8}'`)
  printf " has finished (MaxTime=%d)\n" $MaxTime | tee -a $logfile
  # check if MaxTime is different from previous run:
  if ( "$line" != "1" ) then
    if ( "$MaxTime" != "$MaxTime0" ) set DifferentMaxTime
  endif
  set MaxTime0 = $MaxTime
end

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

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

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

# merge netcdf files, based on example from:
# http://nco.sourceforge.net/nco.html#Averaging-vs_002e-Concatenating

cd $outputdir
if (${?DifferentMaxTime}) then
  set fullfilenames = (caaba_mecca_c_end.nc caaba_mecca_k_end.nc)
else
  set fullfilenames = (runs/0001/*.nc)
endif
echo;echo "Merging the netcdf files:"

foreach fullfilename ($fullfilenames)
  set ncfile = `basename $fullfilename`
  echo "Working on $ncfile"
  echo -n "Monte-Carlo run"
  foreach mcrun (runs/*)
    set basemcrun = `basename $mcrun`
    echo -n " $basemcrun"
    # put Monte-Carlo run number into time:
    ncclamp $mcrun/$ncfile time 0 $basemcrun ge
  end
  echo " done"
  # concatenate files along time:
  ncrcat -O runs/*/$ncfile $ncfile
end

# ferret jnl files for scatter plots:
mv $basedir/_scatterplot1.jnl tmp_scatterplot1.jnl
mv $basedir/_scatterplot2.jnl .
mv $basedir/_histogram_k.jnl .
sort tmp_scatterplot1.jnl > _scatterplot1.jnl
ln -s $basedir/jnl/montecarlo.jnl     .
ln -s $basedir/jnl/scatterplot_mc.jnl .

rm tmp_*.nc tmp_*.jnl
cd -

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

echo;echo "The model output is now in:"
echo "output/montecarlo/`basename ${outputdir}`"
echo "start ferret in that directory and run montecarlo.jnl to plot the results"

# cleanup:
rm tmp_*

echo;echo $hline
echo "END OF MONTE-CARLO MODEL SIMULATIONS"
echo $hline

exit

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