#!/bin/sh

###########################################################
#  General script calculating meteo, bio emissions etc... #
#  and running CHIMERE for any period of time.            #
#  *** This version works only with ECMWF meteo data      #
#  Over Europe                                            #
#                                                         #
#  SOFTWARE REQUIRED: g77, gawk                           #
#                                                         #
#  LAST REVISION : NOVEMBER 2002                          #
#                                                         #
#  AUTHORS: H. SCHMIDT, C. DEROGNAT, J. ROUX, M. BEEKMANN #
#           N. BLOND, R. VAUTARD                          #
#         - INSTITUT PIERRE-SIMON LAPLACE -               #
#           L. MENUT, B. AUMONT                           #
#         - L.I.S.A -                                     #
#           C. HONORE                                     #
#         - INERIS -                                      #
########################################################### 

# *** WARNING : ALWAYS SET ABSOLUTE PATHS FOR DIRECTORIES BELOW

dom=CONT1                            # Name of Simulation domain
sim=IOP1                             # Simulation label: output files will be named
                                     # out.<sim>
year=2001                            # Year (4 digits)
month=06                             # Month of simulation start
day=10                            # Starting day
hour=00                              # Starting hour
nhours=144                          # Number of simulation hours

# CHANGE DIRECTORIES (ABSOLUTE PATHS)

# mount -t nfs 193.51.99.11:/part1 /home/menut/part1

METEODIR=/home/menut/part1/ECMWF/WEUROPE                        # ECMWF data base directory
simuldir=/d2/save/chimere/RUN_${dom}${sim}       # Directory for model outputs
emissdir=/d2/save/chimere/emi${dom}-200211        # Emissions directory
domnsdir=/d2/save/chimere/domains                 # Domain information files directory

nest=coarse                          # Nested run (nest) or not (coarse)
                                     # In the coarse case, only dom=CONT1 and
                                     # dom=CONT2 are defined, for western europe
                                     # and boundary conditions are taken from MOZART
                                     # climatologies. For nested runs (one-way nesting)
                                     # any domain can be defined within the corase domain
                                     # Boundary conditions are taken from a coarse run.
                                     # In that case, fill the lower part of the form
                                     # and take cdom=CONT1 or cdom=CONT2
ivs=1                                # Emission sublayer (2) or not (1). Not necessary
                                     # for large-scale (DX>20km) simulations
nlevemis=1                           # Number of emission levels

#  TEMPORARY DIRECTORY TO BE CHANGED (ABSOLUTE PATH)

TMP=${simuldir}                      # TMP is the temporary directory. Give a name where
clean=no                             # there is a lot of temporary disk space
                                     # The size of the directory is typically 100 mo but
                                     # can be much more in high-resolution simulations
                                     # CHIMERE is exectuted in this directory.
                                     # The entire directory is saved in the simuldir
                                     # directory with large files removed (clean=yes)
                                     # or not (clean=no). By setting a TMP directory name
                                     # that depends on process number ($$), it is possible
                                     # to perform several simulations in parallel without
                                     # interactions
clayers=6                            # Number of layers if coarse run
                                     # *** DO NOT CHNAGE IN THIS MODEL VERSION PLEASE
                                     # If this is a nest run, nlayers is the number of layers
                                     # of the coarse run. The hybrid level coefficients are in
                                     # the file data/VCOORD.coarse (*** DO NOT CHANGE THIS FILE)
phys=6                               # Frequency of physics calculation (number per hour)
step=1                               # Refined time step relative to physics calculation
                                     # 1/(phys*step) is the time step in hours
                                     # For 1/2 to 1/4 degree, with phys=6, step=1 is fine
                                     # For fine grids (5-10 kms), take at least step=4
                                     # For grids of 2-5 kms, try step=6 or more
ngs=2                                # Number of Gauss-Seidel iterations
                                     # Take 1 for debugging, 2 for higher accuracy.

#  NEST RUN (nest=nest above) : INFORMATIONS ABOUT THE COARSE RUN
#  THESE INFORMATIONS ARE NOT USED FOR NEST RUNS

cdom=CONT1                           # Cooarse domain name
csim=IOP6                            # Label of coarse run
lsubdiv="1 2 2 2 2 2"                # subdivisions of layers of the coarse run
csimuldir=/d2/save/chimere/SIMU_${dom}${sim} # Directory where to find results
                                                  # of the coarse run (ABSOLUTE PATH)

######################################################
# Only experienceed users should change things below #
######################################################

# Environment variables

export TMP
export METEODIR
export FNCOO=${domnsdir}/COORD_${dom}
export FNLDU=${domnsdir}/LANDUSE_${dom}
export FNBIO=${domnsdir}/BIOFACS_${dom}
export FNLAP=${domnsdir}/LANDPAR_${dom}
export FNBOU=${domnsdir}/BOUNDS_${dom}
export FNVCO=$TMP/VCOORD

# Creating and temporary directory

#echo Temporary Directory : $TMP
#mkdir -p ${TMP}
#rm $TMP/*
#trap "rm -rf $TMP" 0

# Creating the output directory
mkdir -p ${simuldir}

#######################################
# Definition of simulation parameters #
#######################################

sd0=${year}${month}${day}${hour}
show=`gawk '$1=="'${dom}'" {print $11}' ${domnsdir}/DOMAINS`
nzo=`gawk '$1=="'${dom}'" {print $2}' ${domnsdir}/DOMAINS`
nme=`gawk '$1=="'${dom}'" {print $3}' ${domnsdir}/DOMAINS`
nspec=`wc  -l data/ACTIVE_SPECIES | gawk '{print $1}'`
nreac=`wc  -l data/CHEMISTRY      | gawk '{print $1}'`
nfam=`wc   -l data/FAMILIES       | gawk '{print $1}'`
nemisa=`wc -l data/ANTHROPIC      | gawk '{print $1}'`
nemisb=`wc -l data/BIOGENIC       | gawk '{print $1}'`

#####################################
# Vertical levels of the coarse run #
#####################################

if [ "$nest" = "nest" ] ; then
  util/vcoord_subdiv data/VCOORD.coarse ${lsubdiv} > data/VCOORD.nest
  nlayers=`wc -l data/VCOORD.nest | gawk '{print $1}'`
  cp data/VCOORD.nest $TMP/VCOORD
else
  nlayers=${clayers}
  cp data/VCOORD.coarse $TMP/VCOORD
fi

##################################
# Construction of chimere.h file #
##################################

cat << EOD > $TMP/chimere.h.sed-commands
s,_NVE_,${nlayers},
s,_IVS_,${ivs},
s,_NZO_,${nzo},
s,_NME_,${nme},
s,_SHO_,${show},
s,_NPH_,${phys},
s,_NST_,${step},
s,_NGS_,${ngs},
s,_NHR_,${nhours},
s,_NSP_,${nspec},
s,_NRE_,${nreac},
s,_NFA_,${nfam},
s,_NEA_,${nemisa},
s,_NEB_,${nemisb},
s,_NLE_,${nlevemis},
EOD
sed -f $TMP/chimere.h.sed-commands src/chimere.h.sed > $TMP/chimere.h

#############################################################
# Meteo diagnostic interface                                #
# It constructs 2 files in the temporary directory,         #
# a file named METEO containing all hourly meteo variables  #
# and a file named BEMISSIONS containing biogenic emissions #
#############################################################

util/prep-ecm $sd0 $nhours $show

##############################
# Hourly anthropic emissions #
##############################

echo "Preparing anthropic emissions..."
echo ${sd0} ${nhours}                            >  $TMP/prepemis.p
echo "'"${emissdir}/EMISSIONS-${dom}.${month}"'" >> $TMP/prepemis.p
echo "'"$TMP/AEMISSIONS"'"                       >> $TMP/prepemis.p
tcompile prepemis
$TMP/prepemis.e < $TMP/prepemis.p

############################
#  Boundary concentrations #
############################

echo "Preparing boundary concentrations..."
case ${nest} in
  coarse) echo ${nzo} ${nme} ${sd0}                          > $TMP/prepboun_mozart0.p;
          echo "'"${domnsdir}/BOUNDARIES_${dom}.${month}"'" >> $TMP/prepboun_mozart0.p;
          echo "'"$TMP/LAT_CONCS"'"                         >> $TMP/prepboun_mozart0.p;
          echo "'"$TMP/TOP_CONCS"'"                         >> $TMP/prepboun_mozart0.p;
          tcompile prepboun_mozart0;
          $TMP/prepboun_mozart0.e < $TMP/prepboun_mozart0.p ;
          iopbounlat=0;
          iopbountop=0;;
  nest)   nxc=`gawk '$1=="'${cdom}'" {print $2}' ${domnsdir}/DOMAINS`;
          nyc=`gawk '$1=="'${cdom}'" {print $3}' ${domnsdir}/DOMAINS`;
          dxc=`gawk '$1=="'${cdom}'" {print $4}' ${domnsdir}/DOMAINS`;
          dyc=`gawk '$1=="'${cdom}'" {print $5}' ${domnsdir}/DOMAINS`;
          xmc=`gawk '$1=="'${cdom}'" {print $7}' ${domnsdir}/DOMAINS`;
          ymc=`gawk '$1=="'${cdom}'" {print $9}' ${domnsdir}/DOMAINS`;
          nsboun=`wc -l data/LAT_SPEC.nest | gawk '{print $1}'`;
          pars="${sd0} ${nsboun} ${clayers} ${nxc} ${nyc} ${xmc} ${ymc} ${dxc} ${dyc} ${nzo} ${nme}";
          echo "${pars} '"$FNBOU"' '"${csimuldir}/out.${csim}"' '"$TMP/LAT_CONCS"'" > $TMP/preplat_chimere.p;
          echo ${lsubdiv} >> $TMP/preplat_chimere.p
          tcompile preplat_chimere;
          $TMP/preplat_chimere.e < $TMP/preplat_chimere.p;
          echo ${nzo} ${nme} ${sd0}                   > $TMP/preptop_mozart0.p;
          echo "'"${domnsdir}/TOP_${dom}.${month}"'" >> $TMP/preptop_mozart0.p;
          echo "'"$TMP/TOP_CONCS"'"                  >> $TMP/preptop_mozart0.p;
          tcompile preptop_mozart0;
          $TMP/preptop_mozart0.e < $TMP/preptop_mozart0.p ;
          iopbounlat=1;
          iopbountop=0;;
  *) echo "*** OPTION NEST NOT RECOGNIZED" ;;
esac

# Compiling of libraries and main program

echo "Compiling the chimere code..."
tcompile chimere

# Consruction of INFOS file

echo "Building the INFOS / chimere.h file..."
if [ ! -s ${simuldir}/ini.${sim} ] ; then
  echo "*** No initialisation used"
  init=0
else
  echo "*** Using concentrations for initializing"
  init=1
fi

cat << EOD > $TMP/INFOS.sed-commands
s,_SIM_,${sim},
s,_NHOURS_,${nhours},
s,_INITDATE_,${sd0},
s,_INIT_,${init},
s,_SIMULDIR_,${simuldir},
s,_TMPDIR_,$TMP,
s/_IOPBOUNLAT_/${iopbounlat}/
s/_IOPBOUNTOP_/${iopbountop}/
EOD
sed -f $TMP/INFOS.sed-commands data/INFOS.sed > $TMP/INFOS

# Copying data files to temporary directory

cp data/ACTIVE_SPECIES         $TMP
cp data/CHEMISTRY              $TMP
cp data/STOICHIOMETRY          $TMP
cp data/REACTION_RATES         $TMP
cp data/FAMILIES               $TMP
cp data/PPM_SPECIES            $TMP
cp data/ANTHROPIC              $TMP
cp data/BIOGENIC               $TMP
cp data/LAT_SPEC.${nest}       $TMP/LAT_SPEC
cp data/OUTPUT_SPECIES.${nest} $TMP/OUTPUT_SPECIES
cp data/TOP_SPEC               $TMP
cp data/DEPO_LAND              $TMP
cp data/DEPO_SPEC              $TMP
cp data/ACTIVE_REACTIONS       $TMP
cp data/PHOTORATES             $TMP
cp data/REACTIONS              $TMP
cp data/OUTPUT_PARAMETERS      $TMP

cp ${domnsdir}/LANDUSE_${dom}  $TMP/LANDUSE
cp ${domnsdir}/COORD_${dom}    $TMP/COORD

# Runing the model

echo "Model running..."
cd $TMP
#chimere.e

# Save temporary directory

if [ "$clean" = "yes" ] ; then
  rm $TMP/METEO
  rm $TMP/LAT_CONCS
  rm $TMP/TOP_CONCS
  rm $TMP/AEMISSIONS
  rm $TMP/BEMISSIONS
  rm $TMP/*-ecm
fi

#cp -rd $TMP ${simuldir}/save.${sim}
