#! /bin/csh -f
#==============================================================================
# Purpose:
#     (a) Build mct library
#==============================================================================

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

setenv MCT_DIR $CSMUTL/mct                   # mct directory
setenv MCT_LIB $EXEROOT/mct


if ($BLDTYPE == 'TRUE') then

  cd $MCT_LIB
  echo "Copying source to CCSM EXEROOT..."
  cp -r -p $MCT_DIR/* .

  set runconf = 0
  set runclean = 0

# It would be harmless to just run "configure" each time but it
# takes time so use file "mct_conf" to determine if configure must
# be run.  There are three possibilities:
# 1. brand new build -- run configure
# 2. already built but platform has changed (this can happen
#    when a filesystem is mounted on multiple platforms) -- run configure
# 3. already built, same platform -- don't run configure
#
  if(-e mct_conf) then
    echo "MCT already built. Checking machine type"
    cp -f mct_conf mct_conf.old
    echo ${OS} > mct_conf
    set diffwc = 1
    set diffwc = `diff mct_conf.old mct_conf | wc -m`
    if ($diffwc != 0) then
      echo "Different machine. Rerun configure"
      rm Makefile.conf.old
      rm -f $LIBROOT/libmct.a
      rm -f $LIBROOT/libmpeu.a

      set runconf = 1
      set runclean = 1
    else
      echo "Same machine."
      cp -p Makefile.conf.old Makefile.conf
    endif
  else
    echo "New build of MCT"
    echo ${OS} > mct_conf
    set runconf = 1
  endif

# run configure with correct arguments if necessary
  if ($runconf == 1) then
    echo "Running configure..."
    if ($OS == 'Linux-ia64') then
      ./configure FCFLAGS="-WB -tpp2 -ip -g -Zp16 -fno-alias -fno-fnalias -stack_temps"
    else if ($OS == 'UNICOS') then
      if (`uname` == 'Linux') then 
        # Cross compiler
        setenv ac_cv_c_bigendian yes
        ./configure --host=Linux FCFLAGS="-r m"
      else
        ./configure FCFLAGS="-r m"
      endif
    else
      ./configure
    endif
  endif

  if ($runclean == 1) then
    make clean
  endif

  cp -p Makefile.conf Makefile.conf.old

  make || exit 1

  cp mct/lib*.a $LIBROOT/
  cp mpeu/lib*.a $LIBROOT/
  cp mct/*.mod $LIBROOT/include/
  cp mpeu/*.mod $LIBROOT/include/
endif

exit 0

