#!/bin/csh

set OP_SYS=`uname -s`
if( ! $?FC ) then
  if( $OP_SYS == "Linux" ) then
    setenv FC pgf90
  else
    setenv FC xlf90
  endif
endif

echo "============================================================================="
which ${FC} > /dev/null
if( $status ) then
  echo "Can't find fortran compiler ${FC}"
  echo "Please specify the fortran compiler by setting the FC environment variable"
  echo "============================================================================="
  exit -1
else
  echo "Using ${FC} fortran compiler"
  echo "============================================================================="
endif

if( ! $?NETCDF_DIR ) then
#------------------------------------------------------------
#  check for netcdf library
#------------------------------------------------------------
  set found_ncf_lib = 0
  foreach tst_dir (/usr/local /usr /opt)
    foreach tst_lib (lib64 lib netcdf)
      if( -e $tst_dir/$tst_lib/libnetcdf.a ) then
         set found_ncf_lib = 1
         break
      endif
    end
    if( $found_ncf_lib ) then
      break
    endif
  end
  if( $OP_SYS == "Linux" ) then
    if( $found_ncf_lib ) then
      setenv NETCDF_DIR $tst_dir
    else
      setenv NETCDF_DIR /usr
    endif
  else
    if( $found_ncf_lib ) then
      setenv NETCDF_DIR $tst_dir
    else
      setenv NETCDF_DIR /usr/local
    endif
  endif
  echo " "
  echo "Using $FC fortan90 compiler"
endif

echo "============================================================================="
if( ! -d ${NETCDF_DIR} ) then
  echo "Can't find netcdf top level directory ${NETCDF_DIR}"
  echo "Please specify the directory by setting the NETCDF_DIR environment variable"
  echo "============================================================================="
  exit -1
else
  echo "netcdf top level directory = ${NETCDF_DIR}"
  echo "============================================================================="
endif

set ar_libs = -lnetcdf
if( -e ${NETCDF_DIR}/lib/libnetcdff.a ) then
  set ar_libs = "${ar_libs} -lnetcdff"
endif

make clean >& /dev/null
make AR_LIBS="$ar_libs" || echo "Failed to build anthro_emis" && exit -1
echo " "

make cleanup >& /dev/null
echo "++++++++++++++++++++"
echo "anthro_emis build Ok"
echo "++++++++++++++++++++"

exit 0
