#! /bin/csh -f 

source $CASEROOT/env_conf || exit -1
source $CASEROOT/env_run  || exit -1
source $CASEROOT/env_mach.$MACH  || exit -1
source $CASEROOT/env_pes.$MACH  || exit -1

set exedir = $EXEROOT/lnd
set objdir = $OBJROOT/lnd/obj

cd $objdir

# Filepath: List of source code directories (in order of importance).
# (update only if new or changed)
#--------------------------------------------------------------------
\cat >! .tmp << EOF; cmp -s .tmp Filepath || mv -f .tmp Filepath 
$CASEROOT/SourceMods/src.share
$CASEROOT/SourceMods/src.clm
$CODEROOT/lnd/clm2/src/main
$CODEROOT/lnd/clm2/src/biogeophys
$CODEROOT/lnd/clm2/src/riverroute
$CODEROOT/lnd/clm2/src/biogeochem
$CODEROOT/csm_share/cpl
$CODEROOT/csm_share/shr
$CODEROOT/utils/timing
$CODEROOT/utils/esmf_wrf_timemgr
EOF

# build preproc.h: land model specific cpp variables
# (update only if new or changed)
#----------------------------------------------------------
\cat >! .tmp << EOF; cmp -s .tmp preproc.h || mv -f .tmp preproc.h 
#ifndef PREPROC_SET
#define PREPROC_SET
#define COUP_CSM
#define LSMLON 128
#define LSMLAT 64
#define CN
#define SOM4
#define EXIT_SPINUP
#define MAXPATCH_PFT numpft+1
#define RTM    
#endif
EOF

#--------------------------------------------------------------------
# check basic task and thread settings
#--------------------------------------------------------------------

if !($NTASKS_LND > 0) then
  echo "NTASKS_LND must be > 0, please correct in env_pes and reconfigure"
  exit -1
endif
if !($NTHRDS_LND > 0) then
  echo "NTHRDS_LND must be > 0, please correct in env_pes and reconfigure"
  exit -1
endif

# build misc.h; generic cpp variables (e.g. if spmd is defined)
# (update only if new or changed)
#------------------------------------------------
set spmd = "#undef  SPMD"
if ($NTASKS_LND > 1) set spmd = "#define SPMD"   

\cat >! .tmp << EOF; cmp -s .tmp misc.h || mv -f .tmp misc.h ; set rebuild = TRUE
#ifndef MISC_SET  
#define MISC_SET  
$spmd
#endif       
EOF

# Create the executable
#----------------------

if ($BLDTYPE == 'TRUE') then
if ($OS == 'UNICOS') then
  if (`uname` == 'Linux') then
    # cross compiler needs to run dependency program locally
    module purge
    gcc -o makdep $BLDROOT/makdep.c || exit 2
    source $CASEROOT/env_mach.$MACH  || exit -1
  else
    # makes the build run faster on the Cray X1E
    cc -h command -o makdep $BLDROOT/makdep.c || exit 2
  endif
else
  cc -o makdep $BLDROOT/makdep.c || exit 2
endif
  set THREAD = FALSE ;  if ($NTHRDS_LND > 1) set THREAD = TRUE
  gmake VPFILE=Filepath MODEL=clm EXEC=$exedir/clm \
      THREAD=$THREAD -f  $BLDROOT/Makefile MACFILE=$CASEROOT/Macros.$MACH deps   || exit 2
  gmake -j $GMAKE_J VPFILE=Filepath MODEL=clm EXEC=$exedir/clm \
      THREAD=$THREAD -f  $BLDROOT/Makefile MACFILE=$CASEROOT/Macros.$MACH    || exit 2
endif

wait

if !(-f $exedir/clm) then
  echo "ERROR: clm executable not available, check SETBLD"
  exit -1
endif

