#!/bin/bash                                                                     
#
# E. Vanvyve / X. Fettweis - 08.10.2007
#                                                                               
# NAME                                                                          
#                                                                               
#   CODE - prepare and compile MAR                                              
#                                                                               
# SYNOPSIS                                                                      
#                                                                               
#   CODE name                                                                   
#                                                                               
# OPERANDS                                                                      
#                                                                               
#   name    the name of the MAR run                                             
#           = 1 letter (3rd one of the domain name) + 2 numbers (e.g. a+01=a01) 
#                                                                               
# DESCRIPTION                                                                   
#                                                                               
#   The CODE script prepares and compiles MAR for a new simulation inside a     
#   domain.                                                                     
#                                                                               

#INI.ctr                                 

tmp=`ls ${0%/*}/INI.ctr | wc -l`  #to avoid search in subdirectories
[ $tmp -ne 1 ] && echo '@&?%! '"fatal error: ${0%/*}/INI.ctr nonexistent" && exit

control=${0%/*}/INI.ctr
. $control

#FUNCTIONS

. FUNCTIONS


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

MAR_pp () {   # XF 2020 01 08

[ ! -f MAR_pp.inp ] && echo "MAR_pp.inp not found"

while IFS= read -r line ; do
 

 opt=`echo $line | awk '{print $1}'`

 if [ ${#opt} == 3 ] && [ "${opt:0:1}"=="#" ] ; then 

  echo ${line}

  for file in *.f ; do

   sed "s/c\ \#${opt:1:2}/\ \ \ \ \ /g" $file    > $file.new
   [ $? -eq 0 ]      && mv  $file.new  $file

  done

 fi

done < "MAR_pp.inp"

}

#-------------------------------------------------------------------------------
# HELP                                                                          
#-------------------------------------------------------------------------------

[ ${#1} -eq 0 ] && head -22 $0 && exit


#-------------------------------------------------------------------------------
#  SCRIPT INITIALISATION                                                        
#-------------------------------------------------------------------------------

#                                                                               
# User's parameters                                                             
#---------------------------------------                                       

#INI.ctr                                 

tmp=`ls ${0%/*}/INI.ctr | wc -l`  #to avoid search in subdirectories
[ $tmp -ne 1 ] && echo '@&?%! '"fatal error: ${0%/*}/INI.ctr non-existent" && exit

control=${0%/*}/INI.ctr
. $control

#$0.ctr                                 

tmp=`ls $0.ctr | wc -l`  #to avoid search in subdirectories
[ $tmp -eq 0 ] && echo '@&?%! '"fatal error: $0.ctr non-existent" && exit

control=$0.ctr
. $control

#                                                                               
# System initialisation                                                         
#---------------------------------------                                       

#main script parameters values          

case $cluster in (nic|linux|nasa|idris|foehn|froggy) echo ;;
                 (*) echo '@&?%! '"script not done for $cluster" && exit ;;
esac

#-------------------------------------------------------------------------------
#  TITLE                                                                        
#-------------------------------------------------------------------------------
TITLE0 "MAR PREPARATION AND COMPILATION "


#-------------------------------------------------------------------------------
#  1 - INITIALISATION                                                           
#-------------------------------------------------------------------------------
TITLE1 "INITIALISATION"

#                                                                               
# Your parameters (CODE.ctr)                                                    
#---------------------------------------                                       
TITLE2 "Your parameters (CODE.ctr)"

  # WLDreg   = world region (GR, AN, EU, BE, ...)             
  # domain   = domain of simulation (EUa, BEm, ...)       
  # run name = name of the run in domain/ (a01, m16, ...) 

#script argument                        

usage="\nusage: CODE name"

[ ${#1} -eq 0 ] && DAMNED "argument missing [run name]\n$usage"
arg1=$1 

#CODE.ctr arguments: user's dir. paths  

MARbin=${MARbin%/}
SIMdir=${SIMdir%/}
MARdir=${MARdir%/}
STKmar=${STKmar%/} ; [ ${#STKmar} -eq 0 ] && STKmar="."

#CODE.ctr arguments: y/n values         

fsplit=y

case $fsplit in ([!yn]) DAMNED "parameter error: fsplit [$fsplit]" ;; esac

#world region                           

case $WLDreg in
  (EU) tmp="Europe" ;;
  (WA) tmp="West Africa" ;;
  (AN) tmp="Antarctica" ;;
  (GR) tmp="Greenland" ;;
  (BE) tmp="Belgium" ;;
  (*)  tmp="extraterrestrial land..." ;;
esac

#user's parameters                      

echo "general world region  : $WLDreg ($tmp)"
echo
echo "SIMdir directory      : $SIMdir"
echo "MARdir directory      : $MARsrc"
echo "MAR directory on stock: $STKmar"
echo
[ $fsplit = "n" ] && tmp="no fsplitted" || tmp="fsplitted"
echo "compile MAR code      : $tmp"
echo
echo "cluster               : $cluster"
echo "stock address         : $stock"
echo

#                                                                               
# Check the run name                                                            
#---------------------------------------                                       
TITLE2 "Check the run name"

runnam=$arg1

#length                                 

[ ${#runnam} -ne 3 ] && DAMNED "format error: run name (a3) [$runnam]"

echo "run name: $runnam"
echo "associated domain: $WLDreg${runnam%??}"
echo "associated world region: $WLDreg"

#name denomination                    

  #domain
k=0
for i in `ls $SIMdir | awk '{ print($0) }'` ; do
  j=${i#$WLDreg}
  [ ${#j} -eq 1 -a ${runnam%??} = $j ] && k=$(($k+1))
done
[ $k -ne 1 ] && DAMNED "format error: run name [$runnam]. Associated domain $WLDreg${runnam%??} ($WLDreg+${runnam%??}) non-existent."

#                                                                               
# Set paths                                                                     
#---------------------------------------                                       
TITLE2 "Set paths"

domain=$WLDreg${runnam%??}  #e.g. EUa=EU+a
DOMdir=$SIMdir/$domain
CTRLdir="$DOMdir/ctrl/$runnam"
CODEdir="$DOMdir/code/$runnam"
RUNdir="$DOMdir/run/$runnam"

echo "simulation domain directory path: $DOMdir"
echo "simulation ctrl   directory path: $DOMdir/ctrl/$runnam"
echo "simulation code   directory path: $DOMdir/code/$runnam"
echo "simulation run    directory path: $DOMdir/run/$runnam"

#                                                                               
# Make directories                                                              
#---------------------------------------                                       
TITLE2 "Make directories"

#must have been created by the INI script!

[ -d $DOMdir ]        || DAMNED "$DOMdir/ non-existent"
[ -d $DOMdir/ctrl ]   || DAMNED "$DOMdir/ctrl/ non-existent"
[ -d $DOMdir/code ]   || DAMNED "$DOMdir/code/ non-existent"
[ -d $DOMdir/input ]  || DAMNED "$DOMdir/input/ non-existent"
[ -d $DOMdir/run ]    || DAMNED "$DOMdir/run/ non-existent"
[ -d $DOMdir/input/NESTOR ] || DAMNED "$DOMdir/input/NESTOR/ non-existent"

#check if any pre-existing run directory (ctrl/xxx, code/xxx, run/xxx)

if [ -d $CTRLdir ] ; then
  CHOICE "$CTRLdir existing. Erase it?"
  case $answer in
  (y) rm -rf $CTRLdir ;
      echo "mkdir: $CTRLdir" ; mkdir $CTRLdir ;;
  (n) echo "rm: $CTRLdir kept" ;;
  esac
else
  echo "mkdir: $CTRLdir" ; mkdir $CTRLdir
fi
if [ -d $CODEdir ] ; then
  CHOICE "$CODEdir existing. Erase it?"
  case $answer in
  (y) rm -rf $CODEdir ;
      echo "mkdir: $CODEdir" ; mkdir $CODEdir ;;
  (n) echo "rm: $CODEdir kept" ;;
  esac
else
  echo "mkdir: $CODEdir" ; mkdir $CODEdir
fi
if [ -d $RUNdir ] ; then
  CHOICE "$RUNdir existing. Erase it?"
  case $answer in
  (y) rm -rf $RUNdir ;
      echo "mkdir: $RUNdir" ; mkdir $RUNdir ;;
  (n) echo "rm: $RUNdir kept" ;;
  esac
else
  echo "mkdir: $RUNdir" ; mkdir $RUNdir
fi

#                                                                               
# Save your *.ctr file                                                          
#---------------------------------------                                       
TITLE2 "Save your *.ctr file"

echo "cp: $0.ctr -> $CTRLdir/CODE.ctr.$runnam"
cp -f  $0.ctr  $CTRLdir/CODE.ctr.$runnam


#------------------------------------------------------------------------------
#  2 - MAR PRE-PROCESSING OPTIONS
#-------------------------------------------------------------------------------
TITLE1 "MAR PRE-PROCESSING OPTIONS"

MAR_pp_inp=$CTRLdir/MAR_pp.inp.$runnam
INP () { echo $1 >> $MAR_pp_inp ; }

rm -f  $MAR_pp_inp
touch  $MAR_pp_inp

#
# Checking MAR options                                                         
#---------------------------------------
TITLE2 "Checking MAR options"

#OTHERS                                                                         

#vectorisation                         

LS="ERA40"        # LSC forcing                                    [ERA15/ERA40]
VE="F"            # vectorisation                                          [T/F]
VC="T"            # small vectorisation                                    [T/F]
MP="T"            # Open-MP                                                [T/F]
DP="F"            # Double precision                                       [T/F]
fsplit=y          # compile the fsplitted MAR code (idris=n)               [y/n]

case $VE in (T) echo "vectorisation" ;;
            (F) echo "no vectorisation" ;;
            (*) DAMNED "error value: vectorisation [VE=$VE]" ;;
esac
if [ $VE = "F" -a $cluster = "idris" ] ; then
  DAMNED "error value: vectorisation is compulsory on the IDRIS cluster"
fi
case $VC in (T) echo "small vectorisation" ;;
            (F) echo "no small vectorisation" ;;
            (*) DAMNED "error value: small vectorisation [VC=$VC]" ;;
esac



#dynamics

NH="F"      # basic non-hydrostatic option                            F   F   F 
NHs="F"     # slope non-hydrostatic option                            F   F   F 
NHh="F"     # heat  non-hydrostatic option                            F   F   F 

DD="F"      # divergence damper     option                            F   F   F 

case $NH in (T) echo "basic non-hydrostatic option" ;;
            (F) echo "hydrostatic option" ;;
            (*) DAMNED "error value: non-hydrostatic [NH=$NH]" ;;
esac

if [ $NH = "T" ] ; then
  case $NHs in (T) echo "slope non-hydrostatic option" ;;
               (F) echo "no slope non-hydrostatic option" ;;
               (*) DAMNED "error value: non-hydrostatic option [NHs=$NHs]";;
  esac
  case $NHh in (T) echo "heat non-hydrostatic option" ;;
               (F) echo "no heat non-hydrostatic option" ;;
               (*) DAMNED "error value: non-hydrostatic option [NHh=$NHh]";;
  esac
elif [ $NH = "F" ] ; then
  [ $NHs != "F" ] && DAMNED "error value: NHs must be set to F [NHs=$NHs]"
  [ $NHh != "F" ] && DAMNED "error value: NHh must be set to F [NHh=$NHh]"
fi

case $DD in (T) echo "divergence damper option" ;;
            (F) echo "no divergence damper option" ;;
            (*) DAMNED "error value: divergence damper option [DD=$DD]";;
esac

#advection scheme                                                              

AD="L"

case $AD in (L) echo "leap-frog back advection scheme" ;;
            (-) echo "cubic spline   advection scheme" ;;
esac

#convective adjustment scheme                                                  

CA="b"

case $CA in (-) echo "no convective adjustment" ;;
            (b) echo "convective adjustment MNH of Peter Bechtold" ;;
            (E) echo "convective adjustment of Kerry Emmanuel" ;;
            (*) DAMNED "value error: convective adjustement [CA=$CA]" ;;
esac

#radiative transfer scheme                                                     

RT="E"

case $RT in (M) echo "UCL/ASTR radiative transfer scheme" ;;
            (L) echo "LMDZ radiative transfer scheme" ;;
            (E) echo "ECMWF radiative transfer scheme" ;;
            (*) DAMNED "value error: radiative transfer scheme [RT=$RT]" ;;
esac

#turbulence transfer scheme                                                    

TU="e" 

case $TU in (L) echo "K-l Therry & Lacarrere turbulence closure" ;;
            (e) echo "K-e Duynkerke turbulence closure" ;;
            (*) DAMNED "value error: turbulence closure [TU=$TU]" ;;
esac

#water mass balance

WB="F"

case $WB in (T) echo "water mass balance" ;;
            (F) echo "no water mass balance" ;;
            (*) DAMNED "value error: water mass balance [WB=$WB]" ;;
esac

#surface-vegetation-atmosphere transfer scheme                                 

SV="T"

case $SV in (T) echo "SISVAT SVAT scheme" ;;
            (F) echo "Deardorff force restore" ;;
            (*) DAMNED "value error: surface model [SV=$SV]" ;;
esac

SN=T

case $SN in (T) echo "snow model" ;;
            (F) echo "no snow model" ;;
            (*) DAMNED "value error: snow model [SN=$SN]" ;;
esac

IB=T

case $IB in (T) echo "ice-sheet surface mass balance" ;;
            (F) echo "no ice-sheet surface mass balance" ;;
            (*) DAMNED "value error: ice-sheet surface mass balance [IB=$IB]" ;;
esac
case $BS in (T) echo "blowing snow model" ;;
            (F) echo "no blowing snow model" ;;
            (*) DAMNED "value error: blowing snow [BS=$BS]" ;;
esac
ES=F
case $ES in (T) echo "evolutive sastrugi model" ;;
            (F) echo "no evolutive sastrugi model" ;;
            (*) DAMNED "value error: evolutive sastrugi model [ES=$ES]" ;;
esac
AR=F
case $AR in (T) echo "Andreas * Roughness model" ;;
            (F) echo "no Andreas * Roughness model" ;;
            (*) DAMNED "value error: Andreas * Roughness model [AR=$AR]" ;;
esac

SR="F"      # scalar    roughness model                               F   T   F
PO="F"      # polynya - sea-ice model                                 F   F   F 

case $OR in (T) echo "orography roughness set-up" ;;
            (F) echo "no orography roughness set-up" ;;
            (*) DAMNED "value error: orography roughness set-up [OR=$OR]" ;;
esac
case $SR in (T) echo "scalar roughness model" ;;
            (F) echo "no scalar roughness model" ;;
            (*) DAMNED "value error: scalar roughness model [SR=$SR]" ;;
esac
case $PO in (T) echo "polynya - sea-ice model" ;;
            (F) echo "no polynya - sea-ice model" ;;
            (*) DAMNED "value error: polynya - sea-ice [PO=$PO]" ;;
esac

#
# Creation of MAR_pp.inp
#---------------------------------------
TITLE2 "Creation of MAR_pp.inp"

#
# DYNAMICS
#.......................................

# (non) hydrostatic

if [ $NH = "T" ] ; then

  echo "dynamics: non hydrostatic"

  INP "#NH  |   DYNAMICS: Non-Hydrost. Code  (adapted from Laprise, 1992)"

  if [ $NHs = "T" ] ; then
  INP "#nh  |   DYNAMICS: Non-Hydrost. Code  (Slope            Contribut)"
  fi
 
  if [ $NHh = "T" ] ; then
  INP "#DH  |   DYNAMICS: Non-Hydrost. Code  (Diabatic Heating Contribut)"
  fi

else

  echo "dynamics: hydrostatic"

fi

# other

  echo "dynamics: other"

  if [ $DD = "T" ] ; then
  INP "#DD  |   DYNAMICS: Mass Divergence Damper (Skamarock &Klemp, 1992)"
  fi


# advection scheme

  echo "dynamics: advection scheme = 4th centered leap-frog backward"


#
# EXPLICIT CLOUD MICROPHYSICS
#.......................................

  echo "physics: explicit cloud microphysics"

  if [ $WB = "T" ] ; then
  INP "#WB  |   Explicit Cloud MICROPHYSICS: Water Conservation Controled"
    if [ $cluster != "idris" ] ; then
  INP "#WW  |   Explicit Cloud MICROPHYSICS: Water Conservation Summary  "
    fi
  fi

#
# TURBULENCE
#.......................................

if [ $TU = "e" ] ; then

  echo "turbulence: K-e Duynkerke"

  
  if [ $WLDreg = "GR" ] ; then
  INP "#SB  |   Surface Boundary: modified externally (from Campain Data)"
  INP "#KC  |   TURBULENCE: T.K.E.(mz1):= T.K.E.(mz)                     "
  INP "#GL  |   SNOW Model: Greenland simulation                         "
  INP "#TZ  |   Z0 (Momentum) (typical value in polar models)            "
  INP "#II  |   Search new Ice/Snow Interface                            "
  INP "#GR  |   For Greenland                                            "
  INP "#up  |   For having more precip along the margin                  "
  INP "#SU  |   Slush Switch                                             "
  INP "#GP  |   Soil /Vegetation Model: LAI, GLF Variations NOT prescrib." 
# INP "#LN  |   Soil /Vegetation Model: LAI(x,y,t) prescribed(MARglf.DAT"
# INP "#EU  |   For Europe                                               "
  fi
  
  if [ $WLDreg = "AN" ] ; then
  INP "#SB  |   Surface Boundary: modified externally (from Campain Data)"
  INP "#KC  |   TURBULENCE: T.K.E.(mz1):= T.K.E.(mz)                     "
  INP "#TZ  |   Z0 (Momentum) (typical value in polar models)            "
  INP "#II  |   Search new Ice/Snow Interface                            "
  INP "#AC  |   For Cecile Agosta                                        "
  INP "#up  |   For having more precip along the margin                  "
  INP "#SU  |   Slush Switch                                             " 
  INP "#GP  |   Soil /Vegetation Model: LAI, GLF Variations NOT prescrib."
  fi
  
  if [ $WLDreg = "EU" ] ; then
  INP "#up  |   For having more precip along the margin                  "
  INP "#EU  |   For Europe                                               "
  INP "#LN  |   Soil /Vegetation Model: LAI(x,y,t) prescribed(MARglf.DAT)"
  fi

  if [ $WLDreg = "WA" ] ; then
  INP "#EU  |   For Europe/Africa                                        "
  INP "#ur  |   For having more precip along the margin                  "
  INP "#LN  |   Soil /Vegetation Model: LAI(x,y,t) prescribed(MARglf.DAT)"
  fi

fi


#
# CONVECTIVE ADJUSTMENT
#.......................................


  echo "convective adjustment: MNH (Peter Bechtold)"

#
# PHYSICS: RADIATIVE TRANSFER
#.......................................

if [ $RT = "E" ] ; then

  echo "physics: ECMWF radiative transfer scheme"

fi

 #INP "#AZ  |   PHYSICS: Solar : Direct Radiation:   Surface Slope Impact"
 #INP "#MM  |   PHYSICS: Solar : Direct Radiation:   Mountains Mask    ON"

#
# SURFACE-VEGETATION-ATMOSPHERE TRANSFER
#.......................................

if [ $SV = "T" ] ; then

  echo "surface processes: SISVAT"


  if [ $WLDreg = "WA" ] ; then
  INP "#SH  |   Soil /Vegetation Model: Hapex-Sahel   Vegetation     DATA"
 #INP "#MT  |   SISVAT: Monin-Obukhov Theory is linearized (Garrat schem)"
  fi

  if [ $SN = "T" ] ; then
  
  echo "surface processes: snow model"
  
  fi

fi

if [ $BS = "T" ] ; then

  echo "surface processes: blowing snow model"

  INP "#AE  |   TURBULENCE: Aerosols Erosion / Turbulent Diffusion Coeff."
                                         # #AE: for ice sheets and deserts
  INP "#BS  |   Explicit Cloud MICROPHYSICS: Blow. *(Snow)         Model "
 #INP "#cn  |   new cnos for precip "
  INP "#MA  |   SNOW Model: Increased polar B* Mobility (Mann et al.2000)"
  INP "#MB  |   SNOW Model: Erosion Efficiency (Marticorena & Berga.1995)"

  INP "#SS  |   Explicit Cloud MICROPHYSICS: Blow. *(Snow)  Linear Model "
  INP "#EM  |   Explicit Cloud MICROPHYSICS: de Montmollin Parameterizat."
  INP "#HS  |   SNOW Model: Hardened SNOW Pack Initialization            "

fi

if [ $ES = "T" ] ; then

  echo "surface processes: evolutive sastrugi model"

  INP "#SZ  |   SBL: Mom.: Roughn.Length= F(u*) Andreas &al.(2004)  Snow "
  if [ $VC = "T" ] ; then
  INP "#vR  |   PORTABILITY: Vectorization enhanced: Sastrugi Height     "
  fi

fi

if [ $AR = "T" ] ; then

  echo "surface processes: Andreas * roughness model"

 INP "#ZA  |   SBL: Mom.: Roughn.Length= F(u*) Andreas &al.(2004), Snow "
 INP "#ZN  |   SBL: Mom.: Roughn.Length= F(u*) Shao  & Lin (1999), Snow "

fi

if [ $OR = "T" ] ; then

  echo "surface processes: orography roughness model"

  INP "#OR  |   SBL: Orography Roughness included from SL_z0 in MARdom   "

fi

if [ $BS = "T" -o $OR = "T" -o $SR = "T" ] ; then

  INP "#RN  |   SBL: Heat: Roughn.Length= F(u*,z0)  Andreas (1987)  Snow "

fi

if [ ${#AO} -eq 1 ] && [ $AO = "T" ] ; then

  echo "coupling of MAR with NEMO"

 INP "#AO  |   coupling of MAR with NEMO"

fi

if [ $WLDreg = "AN_hubert" ] ; then
  echo "projection: polar stereographic"
  INP "#PP  |   PROJECTION: Polar Stereographic Projection               "
fi

#
# COMPUTATION
#.......................................

  echo "computation"

# INP "#T2  |   OUTPUT: 2, 3, 10-m  Temperature, Wind   (on NetCDF File )"


  if [ ${#DP} -gt 0 ] && [ $DP = "T" ] ; then
  INP "#DP  |   DOUBLE PRECISION            "
  fi

#
# OPTIONS (MAR_PP_DAT.F) NOT USED (?)
#.......................................

  echo 
  echo "MAR pre-processing options: $MAR_pp_inp"


#-------------------------------------------------------------------------------
#  3 - PREPARATION OF THE COMPILATION                                           
#-------------------------------------------------------------------------------
TITLE1 "PREPARATION OF THE COMPILATION"

#                                                                               
# MAR directory preparation                                                     
#---------------------------------------                                       
TITLE2 "MAR directory preparation"

cd $CODEdir        #$DOMdir/code/$runnam

rm -rf  $CODEdir/src
echo "mkdir: $CODEdir/src"
      mkdir  $CODEdir/src

if [ -f $MARsrc/forMAR/mar.f ] ; then

echo "cp: $MARsrc/forMAR/* -> $CODEdir/src/"
 cp -rf   $MARsrc/forMAR/*    $CODEdir/src/

else

echo "cp: $MARsrc/forMAR/forMAR/* -> $CODEdir/src/"
 cp -rf  $MARsrc/forMAR/forMAR/*    $CODEdir/src/

fi

echo "cp: $MARsrc/libMAR -> $CODEdir/src/"
  cp -rf  $MARsrc/libMAR    $CODEdir/src/

#                                                                               
# Pre-processing of MAR                                                         
#---------------------------------------                                       
TITLE2 "Pre-processing of MAR"

#stock initialisation                   
REMARK "stock initialisation"

case $cluster in
(foehn|froggy)
imkdir $STKmar/$domain
imkdir $STKmar/$domain/$runnam
imkdir $STKmar/$domain/$runnam/code
;;
(nic|linux|nasa)
if [ $sftp = "y" ] ; then
 $gateway $ssh $ustock@$stock mkdir -p $STKmar/$domain/$runnam/code
else
  mkdir -p $STKmar/$domain/$runnam/code
fi
[ $? -eq 0 ] && rm -f $CODEdir/ftpexe || DAMNED "directory creation on stock";;
esac
echo

#executing MAR_pp
REMARK "executing MAR_pp"

case $cluster in  #get the NESTOR declaration files: MARdcl_$domain*
(idris)       tmp=`ls $STKmar/$domain/input/NESTOR | head -1`
              tmp=${tmp%\/} ; dclyear=${tmp# }
              tmp=`ls $STKmar/$domain/input/NESTOR/$dclyear |                  \
                   grep "MARdcl_$domain" | head -1` 
              tmp=${tmp##*\/} ;;
(foehn|froggy)tmp=`ils $STKmar/$domain/input/NESTOR | head -2 | tail -1`
              tmp=${tmp%\/} ; dclyear=${tmp##*\/}
              tmp=`ils $STKmar/$domain/input/NESTOR/$dclyear |                  \
                   grep "MARdcl_$domain" | head -1`
              tmp=${tmp##*\/}  ; tmp=${tmp##*\ } ;;
(nic|linux|nasa) 
      if [ ${#ssh} -gt 0 ] ; then
       $ssh $ustock@$stock "cd $STKmar/$domain/input/NESTOR ; ls -1 " > $$
      else
       pwd=$PWD
       cd $STKmar/$domain/input/NESTOR ; ls -1  > $pwd/$$
       cd $pwd
      fi

      dclyear=`cat $$ | grep 1 | head -1` ; 
      dclyear2=`cat $$ | grep 2 | head -1` ; rm -f $$
      [ ${#dclyear2} -gt 0 ] && dclyear=$dclyear2

      if [ ${#ssh} -gt 0 ] ; then
       $ssh $ustock@$stock "cd $STKmar/$domain/input/NESTOR/$dclyear ; ls -1 *" > $$
      else
       cd $STKmar/$domain/input/NESTOR/$dclyear ; ls -1 * > $pwd/$$
       cd $pwd
      fi  
      tmp=`cat $$ | grep "MARdcl_$domain" | head -1 | awk '{i=NF ; print($i)}'`
      rm -f $$ ; tmp=${tmp##*\/} ; dclyear=${dclyear##*\/} 
      ;;
esac
Z=${tmp##*.inc} ; tmp=${tmp%$Z}

smget "$STKmar/$domain/input/NESTOR/$dclyear" "$tmp$Z" "$CODEdir/src"
[ $cluster != "idris" ] && ucX "$CODEdir/src" "$tmp" "$Z"

echo "cp: $CTRLdir/MAR_pp.inp.$runnam -> $CODEdir/src/MAR_pp.inp"  #MAR_pp.inp
   cp -f  $CTRLdir/MAR_pp.inp.$runnam    $CODEdir/src/MAR_pp.inp

if [ $VE = "F" ] ; then  #include *.inc_nv < NESTOR
  tmp=`ls $CODEdir/src/*.inc_nv | sed "s:$CODEdir/src/::g"`
  for inc in $tmp ; do
    echo "cp: $CODEdir/src/$inc -> $CODEdir/src/${inc%_nv}"
       cp -f  $CODEdir/src/$inc    $CODEdir/src/${inc%_nv}
  done
fi

cd $CODEdir/src/

echo

MAR_pp

echo "#!/bin/bash " > MAR_pp
head -n 61 $MARbin/CODE | tail -n 21 >> MAR_pp
chmod +x MAR_pp

echo

#                                                                               
# Code preparation                                                              
#---------------------------------------                                       
TITLE2 "Code preparation"

# MAR*.f

echo "cp: $CODEdir/src/*.*   ->    $CODEdir/"
      cp  $CODEdir/src/*.f90       $CODEdir/
      cp  $CODEdir/src/*.f         $CODEdir/
      cp  $CODEdir/src/*.90f       $CODEdir/
      cp  $CODEdir/src/MAR_pp.inp  $CODEdir/


# CVAmnh.f90

if [ $CA = "b" ] ; then
  echo "cp: $CODEdir/src/CVAmnh.f90 -> $CODEdir/cvamnh.f90"
    cp -f   $CODEdir/src/CVAmnh.f90    $CODEdir/cvamnh.f90 &>/dev/null
    cp -f   $CODEdir/src/cvamnh.f90    $CODEdir/cvamnh.f90 &>/dev/null
fi


# PHYrad_LMD.f / PHYrad_CEP.f

case $RT in
(E) echo "cp: $CODEdir/src/radCEP.d -> $CODEdir/"
      cp -rf  $CODEdir/src/radCEP.d    $CODEdir/
esac

# include files

  echo "mv: $CODEdir/src/*.inc -> $CODEdir/"
     mv -f  $CODEdir/src/*.inc    $CODEdir/

echo

# user files

if [ -d $CODEdir/../../usr ] ; then

  echo "cp: $CODEdir/../../usr/*.inc *.f -> $CODEdir"
  cp -f $CODEdir/../../usr/*.inc $CODEdir &>/dev/null
  cp -f $CODEdir/../../usr/*.f   $CODEdir &>/dev/null
fi

if [ -d $CODEdir/../../../../usr ] ; then

  echo "cp: $CODEdir/../../../usr/*.inc *.f -> $CODEdir"
  cp -f $CODEdir/../../../../usr/*.inc $CODEdir &>/dev/null
  cp -f $CODEdir/../../../../usr/*.f   $CODEdir &>/dev/null
fi

#if [ $BS = "T" ] ; then
# cd $CODEdir
# sed "s/klonv\=\  1/klonv\=256/g" MAR_SV.inc > MAR_SV.inc2
# mv MAR_SV.inc2 MAR_SV.inc
#fi  

if [ $WLDreg = "AN" ] || [ $WLDreg = "GR" ]  ; then
 cd $CODEdir

 sed "s/nsno\=\ \ 10/nsno\=\ \ 30/g" MAR_SV.inc > MAR_SV.inc2
 mv MAR_SV.inc2 MAR_SV.inc

 sed "s/nsno\=\ \ 25/nsno\=\ \ 30/g" MAR_SV.inc > MAR_SV.inc2
 mv MAR_SV.inc2 MAR_SV.inc
 sed "s/nsno\=\ \ 20/nsno\=\ \ 30/g" MAR_SV.inc > MAR_SV.inc2
 mv MAR_SV.inc2 MAR_SV.inc
fi

if [ $VE = "T" ] ; then
 cd $CODEdir
 sed "s/klon=\ \ \ \ \ \ 1/klon=mx2*my2/g" MARdim.inc > MARdim.inc2
 mv MARdim.inc2 MARdim.inc
fi 


if [ $AO = "T" ] ; then 
 cd $CODEdir
 mv mar_module.90f mar_module.f90
fi 


cd $CODEdir
sed "s/mzhyd\=mzabso+1/mzhyd\=mzabso/g" MARdim.inc > MARdim.inc2
mv MARdim.inc2 MARdim.inc

#sed "s/mzhyd\=mzabso/mzhyd\=mzabso-1/g" MARdim.inc > MARdim.inc2 
#mv MARdim.inc2 MARdim.inc

[ -f $CODEdir/SBCnew.f ] && mv $CODEdir/SBCnew.f $CODEdir/sbcnew.f

#-------------------------------------------------------------------------------
#  4 - COMPILATION AND LINKING                                                  
#-------------------------------------------------------------------------------
TITLE1 "COMPILATION AND LINKING"

#                                                                               
# Executing COMPILE                                                         
#---------------------------------------                                       
TITLE2 "Executing COMPILE"

cd $CODEdir
cp -f  $MARbin/COMPILE  $CODEdir/

  #general
sed "s|XXrunnam|$runnam|g"                       COMPILE77> COMPILE1
sed "s|XXdomain|$domain|g"                       COMPILE1 > COMPILE2
sed "s|XXCODEdir|$CODEdir|g"                     COMPILE2 > COMPILE1
sed "s|XXSTKcod|$STKmar/$domain/$runnam/code|g"  COMPILE1 > COMPILE2
sed "s|\$MARbin|$MARbin|g"                       COMPILE2 > COMPILE1
sed "s|\$stock|$stock|g"                         COMPILE1 > COMPILE2

  #compilation options
sed "s|XXfsplit|$fsplit|g"                       COMPILE2 > COMPILE1
sed "s|XXVE|$VE|g"                               COMPILE1 > COMPILE2
sed "s|XXRT|$RT|g"                               COMPILE2 > COMPILE1
sed "s|XXCA|$CA|g"                               COMPILE1 > COMPILE2
sed "s|XXMP|$MP|g"                               COMPILE2 > COMPILE1
sed "s|XXAO|$AO|g"                               COMPILE1 > COMPILE77


rm -f  COMPILE1 COMPILE2
chmod 777 COMPILE77

if [ $AO = "T" ] ; then 
echo "Stop before COMPILE"
echo "COMPILE manually on the cluester on which MAR is going to run "
echo "PS: troubles in coupling experiment start here"
exit

else 


 if [ $job_pbs = "y" ] ; then
 CHOICE "Compile in batch? (advised for idris cluster)"
 else
  answer="n"
 fi

 if [ $answer = "y" ] ; then

  case $cluster in
   (foehn)
     echo "#!/bin/bash"                               >  Compile.cmd
     echo "#OAR -n Compile"                           >> Compile.cmd
     echo "#OAR --stdout $WRKmsg/Compile.o"           >> Compile.cmd
     echo "#OAR --stderr $WRKmsg/Compile.e"           >> Compile.cmd
     echo "cd $CODEdir"                               >> Compile.cmd
     echo "./COMPILE MAR 3"                           >> Compile.cmd
     $QSUB Compile.cmd ;;
   (froggy)
     echo "#!/bin/bash"                               >  Compile.cmd
     echo "#OAR -n Compile"                           >> Compile.cmd
     echo "#OAR --stdout $WRKmsg/Compile.o"           >> Compile.cmd
     echo "#OAR --stderr $WRKmsg/Compile.e"           >> Compile.cmd
     echo "cd $CODEdir"                               >> Compile.cmd
     echo "./COMPILE MAR 3"                           >> Compile.cmd
     $QSUB --project regional-climate Compile.cmd ;;
   (linux)
     echo "#!/bin/bash"                               >  Compile.cmd
     echo "#PBS -N Compile"                           >> Compile.cmd
     echo "#PBS -o $WRKmsg/Compile.eo"                >> Compile.cmd
     echo "#PBS -j eo"                                >> Compile.cmd
     echo "#PBS -l nodes=1:ppn=4"                     >> Compile.cmd
     echo "cd $CODEdir"                               >> Compile.cmd
     echo "./COMPILE MAR"                             >> Compile.cmd
     qsub Compile.cmd ;;
   (nasa)
     echo "#!/bin/bash"                               >  Compile.cmd
     echo "#SBATCH -N 1"                              >> Compile.cmd
     echo "#SBATCH -n 4"                              >> Compile.cmd
     echo "#SBATCH -t 2:00:00"                        >> Compile.cmd
     echo "#SBATCH --output=$WRKmsg/Compile.eo"       >> Compile.cmd
     echo "cd $CODEdir"                               >> Compile.cmd
     echo "./COMPILE MAR"                             >> Compile.cmd
     sbatch Compile.cmd ;;
   (idris)
     #BATCH INSTRUCTIONS FOR IDRIS
     echo "#!/bin/ksh"                                >  Compile.cmd
     echo "#QSUB -ro"                                 >> Compile.cmd
     echo "#QSUB -eo"                                 >> Compile.cmd
     echo "#QSUB -o Compile.eo"                       >> Compile.cmd
     echo "#QSUB -lM 1000Mb"                          >> Compile.cmd
     echo "#QSUB -r Compile"                          >> Compile.cmd
     echo                                             >> Compile.cmd
     echo "ulimit -v unlimited"                       >> Compile.cmd
     echo                                             >> Compile.cmd
     echo "cd $CODEdir"                               >> Compile.cmd
     echo "#compile MAR for uqbar"                    >> Compile.cmd
     echo "./COMPILE MAR 2b"                        >> Compile.cmd
     echo                                             >> Compile.cmd
     qsub Compile.cmd ;;
   (nic)
     echo "#!/bin/bash"                               >  Compile.cmd
     echo "#job name"                                 >> Compile.cmd
     echo "#$ -N Compile"                             >> Compile.cmd
     echo "#environment"                              >> Compile.cmd
     echo "#$ -V"                                     >> Compile.cmd
     echo "#memory reqest"                            >> Compile.cmd
     echo "#$ -l h_vmem=2G"                           >> Compile.cmd
     echo "#standard error/output streams"            >> Compile.cmd
     echo "#$ -j y"                                   >> Compile.cmd
     echo "#$ -o Compile.eo"                          >> Compile.cmd
     echo "#$ -cwd"                                   >> Compile.cmd
     echo                                             >> Compile.cmd
     echo "cd $CODEdir"                               >> Compile.cmd
     echo "#compile MAR for lemaitre"                 >> Compile.cmd
     echo "./COMPILE MAR"                           >> Compile.cmd
     echo
     qsub Compile.cmd ;;
   esac

 else

   nice ./COMPILE MAR 

 fi
fi
#-------------------------------------------------------------------------------
#  4 - SUMMARIZE THE SIMULATION INFORMATIONS
#-------------------------------------------------------------------------------
TITLE1 "SUMMARIZE THE SIMULATION INFORMATIONS"

#
# options, version < CODE.ctr, MAR.f
#---------------------------------------

mNH=`grep "NH="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mN1=`grep "NHs=" $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mN2=`grep "NHh=" $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mDD=`grep "DD="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mAD=`grep "AD="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mCA=`grep "CA="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mRT=`grep "RT="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mTU=`grep "TU="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mWB=`grep "WB="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mSV=`grep "SV="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mSN=`grep "SN="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mIB=`grep "IB="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mBS=`grep "BS="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mES=`grep "ES="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mAR=`grep "AR="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mOR=`grep "OR="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mSR=`grep "SR="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mPO=`grep "PO="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mVE=`grep "VE="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`
mVC=`grep "VC="  $CTRLdir/CODE.ctr.$runnam | cut -d'"' -f2`

case $mNH in (T) mNH="basic non-hydrostatic option" ;;
             (F) mNH="hydrostatic" ;; esac
case $mN1 in (T) mN1="slope non-hydrostatic option" ;; (F) mN1="zut" ;; esac
case $mN2 in (T) mN2="heat  non-hydrostatic option" ;; (F) mN2="zut" ;; esac
case $mDD in (T) mDD="mass divergence damper option" ;; (F) mDD="zut" ;; esac
case $mAD in (L) mAD="leap-frog back" ;; (-) mAD="cubic spline" ;; esac
case $mCA in (b) mCA="MNH Peter Bechtold" ;; (E) mCA="Kerry Emmanuel" ;;
             (-) mCA="none" ;; esac
case $mRT in (M) mRT="UCL/ASTR" ;; (L) mRT="LMDZ" ;; (E) mRT="ECMWF" ;; esac
case $mTU in (e) mTU="K-e Duynkerke" ;; (L) mTU="K-l Therry & Lacarrere" ;; esac
case $mWB in (T) mWB="water mass balance" ;; (F) mWB="zut" ;; esac
case $mSV in (T) mSV="SISVAT" ;; (F) mSV="force restore" ;; esac
case $mSN in (T) mSN="snow model" ;; (F) mSN="no snow model" ;; esac
case $mIB in (T) mIB="ice-sheet surface mass balance" ;; (F) mIB="zut" ;; esac
case $mBS in (T) mBS="blowing snow model" ;; (F) mBS="zut" ;; esac
case $mES in (T) mES="evolutive sastrugi model" ;; (F) mES="zut" ;; esac
case $mAR in (T) mAR="Andreas * roughness model" ;; (F) mAR="zut" ;; esac
case $mOR in (T) mOR="orography roughness set-up" ;; (F) mOR="zut" ;; esac
case $mSR in (T) mSR="scalar roughness model" ;; (F) mSR="zut" ;; esac
case $mPO in (T) mPO="polynya - sea-ice model" ;; (F) mPO="zut" ;; esac 
case $mVE in (T) mVE="vectorisation" ;; (F) mVE="no vectorisation" ;; esac
case $mVC in (T) mVC="small vectorisation" ;; (F) mVC="no small vectorisation" ;; esac

mvers=`grep MARv3 mar.f | head -1 | awk '{print $4}'`

#
#forcing, domain, options, version < NST.ctr, MARgrd.ctr, NSTdim.inc, NESTOR.f
#---------------------------------------

tmp=`ls $DOMdir/input/NESTOR/ctrl/NST.ctr* 2> /dev/null`
if [ `echo $tmp | wc -w` -ne 0 ] ; then
  tmp=`echo $tmp | cut -d' ' -f1`
  nstk=`grep "STKlsc=" $tmp | cut -d'=' -f2 | cut -d' ' -f1`
  nlsc=`grep "NSTlsc=" $tmp | cut -d'=' -f2 | cut -d' ' -f1`
else
  nstk="NESTOR not processed on $cluster (`uname -n`)"
  nlsc="NESTOR not processed on $cluster (`uname -n`)"
fi

tmp1=$DOMdir/input/NESTOR/MARgrd.ctr
                  tmp=`grep "MAR domain center longitude" $tmp1 | cut -d'|' -f1`
nclon=`echo $tmp | cut -d' ' -f1`
                  tmp=`grep "MAR domain center latitude"  $tmp1 | cut -d'|' -f1`
nclat=`echo $tmp | cut -d' ' -f1`
                  tmp=`grep "MAR mesh size (km)"          $tmp1 | cut -d'|' -f1`
nmesh=`echo $tmp | cut -d' ' -f1`

tmp1=$DOMdir/input/NESTOR/src/NSTdim.inc
                                        tmp=`grep "mx    =" $tmp1 | cut -d= -f2`
   nmx=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "my    =" $tmp1 | cut -d= -f2`
   nmy=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "mz    =" $tmp1 | cut -d= -f2`
   nmz=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "ni ="    $tmp1 | cut -d= -f2`
   nni=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "nj ="    $tmp1 | cut -d= -f2`
   nnj=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "nk ="    $tmp1 | cut -d= -f2`
   nnk=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "nvx   =" $tmp1 | cut -d= -f2`
  nnvx=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "mw    =" $tmp1 | cut -d= -f2`
   nmw=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "nsl   =" $tmp1 | cut -d= -f2`
  nnsl=`echo $tmp | cut -d')' -f1` ;    tmp=`grep "nsno  =" $tmp1 | cut -d= -f2`
 nnsno=`echo $tmp | cut -d')' -f1`

tmp1=$DOMdir/input/NESTOR/src/NESTOR.f
nvers=`grep "C |  NESTOR" $tmp1 | awk '{print($4",",$7,$8,$9)}'`

#                                                                               
# informations on the simulation > descr
#---------------------------------------                                       

descr=$CTRLdir/descr.$runnam
touch $descr

BCH ()  { echo "$1" >> $descr ; }

#descr.$runnam: add those informations to the summary file of the simulation

[ -f $descr ] && rm -f $descr

#general

BCH "region  :  $WLDreg"
BCH "domain  :  ${runnam%??}${blank[9]}$nmx*$nmy*$nmz${blank[$((10-${#nmx}-${#nmy}-${#nmz}))]} $nmesh km${blank[$((7-${#nmesh}))]}${nclon}E ${nclat}N"
if [ ${#nlsc} -gt 0 ] && [ ${nlsc%% *} = "NESTOR" ] ; then
BCH "forcing :  $nlsc  $nni*$nnj*$nnk"
else
BCH "forcing :  $nlsc${blank[$((10-${#nlsc}))]}$nni*$nnj*$nnk"
fi
 
#MAR options                            
#directories and programs version       

BCH "${hyphen[80]}"
BCH "MAR    version         :  $mvers"
BCH "NESTOR version         :  $nvers"
BCH "simulation directories :  [home]$DOMdir"
BCH "                          [stock]$STKmar/$domain/$runnam"
BCH "forcing directory      :  [stock]$nstk"
BCH "MAR    control files in:  [home]$CTRLdir"
BCH "NESTOR control file  in:  [home]$DOMdir/input/NESTOR/ctrl"

echo
cat $descr

#-------------------------------------------------------------------------------
#  X - HAVE A NICE DAY :o)                                                      
#-------------------------------------------------------------------------------
TITLE1 "HAVE A NICE DAY :o)"
