#!/bin/tcsh
#
# Purpose
# -------
# Runs the CSIRO Mk3L climate system model for x years, in stand-alone
# atmosphere mode, coupled to CABLE. No need to resubmit on shine-cl.
#
# Usage
# -----
# compile_coal ! compile model and utilities used in this script
# setup_coal   ! copy necessary files into the working directory
# qsub run_coal
# should be submitted from working run directory created by setup
#
# Note
# ----
# *** Remember to check cable_mk3l.nml for output frequency ***
# *** modify input to the ensure it is setup to run for one year

# real year to use in determining fossil fuel emissions
set Realyr = 1810
# Duration of the run, in years (*** user must specify here ***)
set LASTYR = 00050

# Set the stack sizes
limit stacksize unlimited
setenv KMP_STACKSIZE 16M

# Set names of directories
set TMP_DIR = $cwd

# Change to the run directory
cd $TMP_DIR

# Set model year number - $year may have leading zeroes, whereas $yr will not
set year = `cat year`
set yr = `expr $year + 0`
set last = `expr $LASTYR + 0`
set loop = 1

# Loop through the required number of years
 while ($yr <= $LASTYR)

   # Run the model
   ./model < input | tee  output
   echo "Finished running $yr year."

   # Check that the run was OK
   set MESSAGE = `tail output | grep termination`
   if ("$MESSAGE" != '') then
     echo "Year $yr terminated normally."
   else
     echo "Abnormal termination of run."
     echo "Mk3L run stopped - abnormal termination."
     exit
   endif

   # sum emission first
   ./annual.sh -9 -9 1
   mv annual_991.nc annual.nc
   @ yy = {$year} + {$Realyr}
   echo {$yy}
  ./atmCO2conc -c $yy
  cat co2.txt >> co2_hist.txt
   set conc = `awk ' {print $1 } ' < co2.txt `
   set conc = 280
   ./radint -c $conc
   cp  co2_data  co2_data.{$year}ppm.18L
   mv  co2_data  co2_data.18l
   mv  cable_mk3l.nml  cable_mk3l_${year}.nml
   cp cable_mk3l_${year}.nml  cable_mk3l.nml

   # Archive results
   cp restart_out.nc restart_out_${year}.nc
   cp rest.end rest.end_${year}
   cp rest.end rest.start
   mv out_cable.nc out_cable_${year}.nc
   mv output output_${year}
   mv log_cable.txt log_cable_${year}.txt

./seasonal.sh -9 -9 1 
mv seasonal_991.nc seasonal_${year}.nc
mv annual.nc annual_${year}.nc
mv fort.40 ff.${year}

   # Start another year
   set yr1 = `expr $year + 1`
   set nextYr = $yr1
   if ($yr1 <= 9999) set nextYr = 0$yr1
   if ($yr1 <= 999) set nextYr = 00$yr1
   if ($yr1 <= 99) set nextYr = 000$yr1
   if ($yr1 <= 9) set nextYr = 0000$yr1
   /bin/rm year
   echo $nextYr > year
   set year = `cat year`
   set yr = `expr $year + 0`

 end