#!/bin/sh
#
# Copyright (C) 2005-2009 ABINIT Group (Yann Pouillon)
# All rights reserved.
#
# This file is part of the ABINIT software package. For license information,
# please see the COPYING file in the top-level directory of the ABINIT source
# distribution.
#

#
# IMPORTANT NOTE
#
# Do not edit this file, as it is potentially harmful (i.e. it removes
# files). YOU HAVE BEEN WARNED !
#

# Utilities
SED="/bin/sed"

# C preprocessor
CPP="/lib/cpp"
CPPFLAGS="-P -std=c89   -DNDEBUG  "
DEFS=""
INCLUDES=""

# Fortran compiler
FC="/usr/local/openmpi-gcc43/bin/mpif90"
FCFLAGS=""
abi_fc_vendor="gnu"
fc_debug="symbols"
fc_cmdline=""
fc_modsearch=""
fc_onepass="no"

# Rewrite rules
absoft_modsearch="-p"
sun_modsearch="-M"

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

# Header
echo "ABINIT WRAPPER BEGIN"

# Rewrite command-line for buggy compilers
case "${abi_fc_vendor}" in

 # ABSOFT Pro Fortran compiler
 absoft|sun)
  # Isolate includes
  for fc_opt in `echo "${@}" | sed -e 's/ -I[ ]*/ -I/g'`; do
   fc_inc=`echo "${fc_opt}" | grep '^-I'`
   if test "${fc_inc}" != ""; then
    INCLUDES="${INCLUDES} ${fc_opt}"
   fi
  done
  # Transform includes
  fc_rewrite=`eval echo \\${${abi_fc_vendor}_modsearch}`
  fc_modsearch=`echo "${INCLUDES}" | sed -e "s/ -I/ ${fc_rewrite}/g"`
  # Actually run the compiler
  fc_cmdline="${fc_modsearch} ${@}"
  if test "${fc_debug}" = "no"; then
   fc_onepass="yes"
  fi
  ;;

 *)
  fc_cmdline="${@}"
  ;;

esac

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

# Isolate defs, includes and source file
for fc_opt in `echo "${fc_cmdline}" | sed -e 's/ -I[ ]*/ -I/g'`; do
 fc_def=`echo "${fc_opt}" | grep '^-D'`
 if test "${fc_def}" != ""; then
  DEFS="${DEFS} ${fc_opt}"
 fi
 fc_inc=`echo "${fc_opt}" | grep '^-I'`
 if test "${fc_inc}" != ""; then
  INCLUDES="${INCLUDES} ${fc_opt}"
 fi
 fc_src=`echo "${fc_opt}" | grep '\.[Ff]90$'`
 if test "${fc_src}" = ""; then
  fc_src=`echo "${fc_opt}" | grep '\.[Ff]$'`
 fi
 if test "${fc_def}" = "" -a "${fc_src}" = ""; then
  FCFLAGS="${FCFLAGS} ${fc_opt}"
 else
  fc_ext=`echo "${fc_src}" | sed -e 's/.*\.//'`
  fc_cpp=`echo "${fc_src}" | sed -e 's,.*/,,;s,\.F90$,_cpp.f90,;s,\.F$,_cpp.f,'`
  case "${fc_ext}" in
   F|F90)
    if test "${fc_onepass}" = "no"; then
     do_cpp="yes"
    else
     do_cpp="no"
    fi
    ;;
   f|f90)
    do_cpp="no"
    ;;
  esac
 fi
done

# Preprocess and compile separately, except specified
if test "${do_cpp}" = "yes"; then
 echo "${CPP} ${CPPFLAGS} ${DEFS} ${INCLUDES} ${fc_src} > ${fc_cpp}"
 ${SED} -e '/^!/d' ${fc_src} | \
  ${CPP} ${CPPFLAGS} ${DEFS} ${INCLUDES} | \
  ${SED} -e '/^#pragma/d' > ${fc_cpp}
 echo "${FC} ${FCFLAGS} ${fc_cpp}"
 ${FC} ${FCFLAGS} ${fc_cpp}
 fc_ret="${?}"
 if test "${fc_debug}" = "no" -a "${fc_ret}" = "0"; then
  rm ${fc_cpp}
 fi
else
 echo "${FC} ${fc_cmdline}"
 ${FC} ${fc_cmdline}
 fc_ret="${?}"
fi

# Footer
echo "ABINIT WRAPPER END"

exit "${fc_ret}"
