#! /bin/sh
#
# Copyright Intel Corporation.
# 
# This software and the related documents are Intel copyrighted materials, and
# your use of them is governed by the express license under which they were
# provided to you (License). Unless the License provides otherwise, you may
# not use, modify, copy, publish, distribute, disclose or transmit this
# software or the related documents without Intel's prior written permission.
# 
# This software and the related documents are provided as is, with no express
# or implied warranties, other than those that are expressly stated in the
# License.
##
## Copyright (C) by Argonne National Laboratory
# 
# 				  COPYRIGHT
# 
# The following is a notice of limited availability of the code, and disclaimer
# which must be included in the prologue of the code and in all source listings
# of the code.
# 
# Copyright Notice
# 1998--2020, Argonne National Laboratory
# 
# Permission is hereby granted to use, reproduce, prepare derivative works, and
# to redistribute to others.  This software was authored by:
# 
# Mathematics and Computer Science Division
# Argonne National Laboratory, Argonne IL 60439
# 
# (and)
# 
# Department of Computer Science
# University of Illinois at Urbana-Champaign
# 
# 
# 			      GOVERNMENT LICENSE
# 
# Portions of this material resulted from work developed under a U.S.
# Government Contract and are subject to the following license: the Government
# is granted for itself and others acting on its behalf a paid-up, nonexclusive,
# irrevocable worldwide license in this computer software to reproduce, prepare
# derivative works, and perform publicly and display publicly.
# 
# 				  DISCLAIMER
# 
# This computer code material was prepared, in part, as an account of work
# sponsored by an agency of the United States Government.  Neither the United
# States, nor the University of Chicago, nor any of their employees, makes any
# warranty express or implied, or assumes any legal liability or responsibility
# for the accuracy, completeness, or usefulness of any information, apparatus,
# product, or process disclosed, or represents that its use would not infringe
# privately owned rights.
# 
# 			   EXTERNAL CONTRIBUTIONS
# 
# Portions of this code have been contributed under the above license by:
# 
#  * Intel Corporation
#  * Cray
#  * IBM Corporation
#  * Microsoft Corporation
#  * Mellanox Technologies Ltd.
#  * DataDirect Networks.
#  * Oak Ridge National Laboratory
#  * Sun Microsystems, Lustre group
#  * Dolphin Interconnect Solutions Inc.
#  * Institut Polytechnique de Bordeaux
#
##     
##

# Simple script to compile and/or link MPI programs.
# This script knows the default flags and libraries, and can handle
# alternative C compilers and the associated flags and libraries.
# The important terms are:
#    includedir, libdir - Directories containing an *installed* mpich
#    prefix, execprefix - Often used to define includedir and libdir
#    FC                 - Fortran 90 compiler
#    WRAPPER_FCFLAGS    - Any special flags needed to compile
#    WRAPPER_LDFLAGS    - Any special flags needed to link
#    WRAPPER_LIBS       - Any special libraries needed in order to link
#    FC_OTHER_LIBS      - Yet more libraries, needed just with FC
#
# We assume that (a) the C compiler can both compile and link programs
#
# Handling of command-line options:
#   This is a little tricky because some options may contain blanks.
#
# Special issues with shared libraries - todo
#
# --------------------------------------------------------------------------
# Set the default values of all variables.
#
# Directory locations: Fixed for any MPI implementation.
# Set from the directory arguments to configure (e.g., --prefix=/usr/local)
prefix=I_MPI_SUBSTITUTE_INSTALLDIR
# The environment variable I_MPI_ROOT may be used to override installation folder path  
if [ -n "${I_MPI_ROOT}" ] ; then
    prefix="${I_MPI_ROOT}";
fi

exec_prefix=__EXEC_PREFIX_TO_BE_FILLED_AT_INSTALL_TIME__
sysconfdir=${prefix}/etc
includedir=${prefix}/include
libdir=${prefix}/lib

if [ -n "$I_MPI_COMPILER_CONFIG_DIR" ] ; then
    sysconfdir=$I_MPI_COMPILER_CONFIG_DIR;
fi
modincdir=${prefix}/include

if [ ! -f "${prefix}/lib/mpi/debug/libmpi.so" ]; then
    release_lib_dir="/release"
    debug_lib_dir="/debug"
else
    sysconfdir=${prefix}/opt/mpi/etc
    release_lib_dir=""
    debug_lib_dir="/mpi/debug"
    modincdir=${prefix}/include/mpi
fi
MPILIBDIR=${release_lib_dir}
# Default settings for compiler, flags, and libraries
# Determined by a combination of environment variables and tests within
# configure (e.g., determining whehter -lsocket is needed)
FC="gfortran"
FCCPP=""
#
# Fortran 90 Compiler characteristics
FCINC="-I"
# f90modinc specifies how to add a directory to the search path for modules.
# Some compilers (Intel ifc version 5) do not support this concept, and
# instead need
# a specific list of files that contain module names and directories.
# The FCMODINCSPEC is a more general approach that uses <dir> and <file>
# for the directory and file respectively.
FCMODINC="-I"
FCMODINCSPEC=""
FCEXT="f90"
MPICH_VERSION="3.4a2"
FCFLAGS=""
MPIVERSION="2021.14"
MPILIBNAME="mpi"
enable_wrapper_rpath="@enable_wrapper_rpath@"


# How to pass a linker flag through the compiler.
wl=""

# Static library suffix (normally "a").
libext="a"

# Shared library suffix (normally "so").
shlibext="so"

# Format of library name prefix.
libname_spec="lib\$name"

# Library names that the linker finds when passed -lNAME.
library_names_spec="\$libname\$shrext"

# Flag to hardcode $libdir into a binary during linking.
# This must work even if $libdir does not exist.
hardcode_libdir_flag_spec="\${wl}-rpath \${wl}\$libdir"

# Flag to add dtags to allow using runpath instead of rpath
enable_dtags_flag=""
disable_dtags_flag=""

# Whether we need a single -rpath flag with a separated argument.
hardcode_libdir_separator=""

# Set to yes if using DIR/libNAME.so during linking hardcodes DIR into the
# resulting binary.
hardcode_direct="no"

# Set to yes if using the -LDIR flag during linking hardcodes DIR into the
# resulting binary.
hardcode_minus_L="no"


# Attempt to construct dynamic loading info, based on the user
# preference of rpath, runpath or none and on the detected libdir
# flags.
with_wrapper_dl_type=no
if test "X${with_wrapper_dl_type}" = "Xrunpath" ; then
    eval wrapper_dl_type_flags=\"${hardcode_libdir_flag_spec} ${enable_dtags_flag}\"
elif test "X${with_wrapper_dl_type}" = "Xrpath" ; then
    eval wrapper_dl_type_flags=\"${hardcode_libdir_flag_spec} ${disable_dtags_flag}\"
else
    wrapper_dl_type_flags=""
fi

# Internal variables
# Show is set to echo to cause the compilation command to be echoed instead
# of executed.
Show=eval
strip_debug_info=
handle_executable=
executable=a.out
static_log=yes
ilp64=no
no_ilp64=
trace_opt=no
no_rpath=no
#
# End of initialization of variables
#---------------------------------------------------------------------
# Environment Variables.
# The environment variables MPICH_FC may be used to override the
# default choices.
# In addition, if there is a file $sysconfdir/mpifort-$FCname.conf,
# where FCname is the name of the compiler with all spaces replaced by hyphens
# (e.g., "fc -64" becomes "fc--64", that file is sources, allowing other
# changes to the compilation environment.  See the variables used by the
# script (defined above)
# Added MPICH_FC_OLD, MPICH_FC can be used to prefix FC with external utility,
# e.g. setenv MPICH_FC 'eval linkcache $MPICH_FC_OLD'
if [ -n "$I_MPI_FCFLAGS" ] ; then
    FCFLAGS=" "$I_MPI_FCFLAGS
fi
if [ -n "$I_MPI_LDFLAGS" ] ; then
    LDFLAGS=" -ldl "$I_MPI_LDFLAGS 
fi
if [ -n "$I_MPI_F90" ] ; then
    FC="$I_MPI_F90"
    FCname=`echo $FC | sed 's/ /-/g'`
    if [ -s $sysconfdir/mpif90-$(basename $FCname).conf ] ; then
        . $sysconfdir/mpif90-$(basename $FCname).conf
    fi
else
    if [ -n "$MPICH_FC" ] ; then
        MPICH_FC_OLD="$FC"
        FC="$MPICH_FC"
        FCname=`echo $FC | sed 's/ /-/g'`
        if [ -s $sysconfdir/mpifort-$FCname.conf ] ; then
            . $sysconfdir/mpifort-$FCname.conf    
        fi
    fi
fi
if [ -n "$I_MPI_CHECK_COMPILER" ] ; then
    for comp_val in "1" "on" "yes" "enable"
    do
        if [ "$I_MPI_CHECK_COMPILER" = "$comp_val" ] ; then
            Docompchk=yes
            break
        fi
    done
fi
if [ -n "$I_MPI_DEBUG_INFO_STRIP" ] ; then
    for comp_val in "0" "off" "no" "disable"
    do
        if [ "$I_MPI_DEBUG_INFO_STRIP" = "$comp_val" ] ; then
            strip_debug_info=no
            break
        fi
    done
fi
# Allow a profiling option to be selected through an environment variable
if [ -n "$MPIF90_PROFILE" ] ; then
    profConf=$MPIF90_PROFILE
fi
if [ -n "$I_MPI_F90_PROFILE" ] ; then
    profConf=$I_MPI_F90_PROFILE
fi
if [ -n "$MPIFC_PROFILE" ] ; then
    profConf=$MPIFC_PROFILE
fi
if [ -n "$I_MPI_FC_PROFILE" ] ; then
    profConf=$I_MPI_FC_PROFILE
fi

# Override default mpi library
if [ -n "$I_MPI_LINK" ] ; then
    mpilib_override=$I_MPI_LINK
fi
#
# ------------------------------------------------------------------------
# Argument processing.
# This is somewhat awkward because of the handling of arguments within
# the shell.  We want to handle arguments that include spaces without
# loosing the spacing (an alternative would be to use a more powerful
# scripting language that would allow us to retain the array of values,
# which the basic (rather than enhanced) Bourne shell does not.
#
# Look through the arguments for arguments that indicate compile only.
# If these are *not* found, add the library options
#
linking=yes
allargs=""
interlib_deps=yes
argno=0
cppflags=""
static_mpi=no
for arg in "$@" ; do
    # Set addarg to no if this arg should be ignored by the C compiler
    addarg=yes
    qarg=$arg
    if [ "x$handle_executable" = "xyes" ] ; then
    executable=$arg
    handle_executable=
    fi
    case "$arg" in 
    # ----------------------------------------------------------------
    # Compiler options that affect whether we are linking or no
    -c|-S|-E|-M|-MM)
    # The compiler links by default
    linking=no
    ;;
    # ----------------------------------------------------------------
    # Options that control how we use mpifort (e.g., -show,
    # -fc=* -config=*
    -static)
    interlib_deps=no
    static_log=yes
    static_mpi=yes
    FCFLAGS="$FCFLAGS -Xlinker --export-dynamic"
    addarg=yes
    ;;
    -o )
    handle_executable=yes
    addarg=yes
    ;;
    -static-mpi)
    interlib_deps=no
    static_mpi=yes
    addarg=no
    FCFLAGS="$FCFLAGS -Xlinker --export-dynamic"
    ;;
    -echo)
    addarg=no
    set -x
    ;;
    -f90=*)
    FC=`echo A$arg | sed -e 's/A-f90=//g'`
    if [ "$#" -eq "1" ] ; then
            echo "Error: extra arguments required"
            echo "usage: mpifort -f90=<name> -v"
            exit 1
    fi
    addarg=no
    ;;
    -fc=*)
    FC=`echo A$arg | sed -e 's/A-fc=//g'`
    if [ "$#" -eq "1" ] ; then
            echo "Error: extra arguments required"
            echo "usage: mpifort -fc=<name> -v"
            exit 1
    fi
    addarg=no
    ;;
    -show)
    addarg=no
    Show=echo
    ;;
    -config=*)
    addarg=no
    FCname=`echo A$arg | sed -e 's/A-config=//g'`
    if [ -s "$sysconfdir/mpifort-$FCname.conf" ] ; then
        . "$sysconfdir/mpifort-$FCname.conf"
    else
    echo "Configuration file mpifort-$FCname.conf not found"
    fi
    ;;
    -compile-info|-compile_info)
    # -compile_info included for backward compatibility
    Show=echo
    addarg=no
    ;;
    -link-info|-link_info)
    # -link_info included for backward compatibility
    Show=echo
    addarg=no
    ;;
    -v)
    # Pass this argument to the compiler as well.
    echo "$(basename $0) for the Intel(R) MPI Library $MPIVERSION for Linux*"
    echo "Copyright Intel Corporation."
    linking=no
    ;;
    -profile=*)
    # Pass the name of a profiling configuration.  As
    # a special case, lib<name>.so or lib<name>.la may be used
    # if the library is in $libdir
    profConf=`echo A$arg | sed -e 's/A-profile=//g'`
    addarg=no
    # Loading the profConf file is handled below
    ;;
    -help)
    # Print mini-help if started without parameters
    echo "Simple script to compile and/or link MPI programs."
    echo "Usage: `basename $0` [options] <files>"
    echo "----------------------------------------------------------------------------" 
    echo "The following options are supported:"
    echo "   -fc=<name> | -f90=<name>"
    echo "                   specify a FORTRAN compiler name: i.e. -fc=gfortran"
    echo "   -echo           print the scripts during their execution"
    echo "   -show           show command lines without real calling"
    echo "   -config=<name>  specify a configuration file: i.e. -config=gfortran for mpif90-gfortran.conf file" 
    echo "   -v              print version info of $(basename $0) and its native compiler"
    echo "   -profile=<name> specify a profile configuration file (an MPI profiling"
    echo "                   library): i.e. -profile=myprofile for the myprofile.cfg file."
    echo "                   As a special case, lib<name>.so or lib<name>.a may be used"
    echo "                   if the library is found"
    echo "   -check_mpi      link against the Intel(R) Trace Collector (-profile=vtmc)."
    echo "   -static_mpi     link the Intel(R) MPI Library statically"
    echo "   -mt_mpi         link the thread safe version of the Intel(R) MPI Library"
    echo "   -ilp64          link the ILP64 support of the Intel(R) MPI Library"
    echo "   -no_ilp64       disable ILP64 support explicitly"
    echo "   -t or -trace"
    echo "                   link against the Intel(R) Trace Collector"
    echo "   -trace-imbalance"
    echo "                   link against the Intel(R) Trace Collector imbalance library"
    echo "                   (-profile=vtim)"
    echo "   -dynamic_log    link against the Intel(R) Trace Collector dynamically"
    echo "   -static         use static linkage method"
    echo "   -nostrip        turn off the debug information stripping during static linking"
    echo "   -O              enable optimization"
    echo "   -link_mpi=<name>"
    echo "                   link against the specified version of the Intel(R) MPI Library"
    echo "                   i.e -link_mpi=opt|opt_mt|dbg|dbg_mt"
    echo "   -norpath        disable rpath for compiler wrapper of the Intel(R) MPI Library"
    echo "All other options will be passed to the compiler without changing."
    echo "----------------------------------------------------------------------------" 
    echo "The following environment variables are used:"
    echo "   I_MPI_ROOT      the Intel(R) MPI Library installation directory path" 
    echo "   I_MPI_F90 or MPICH_F90"  
    echo "                   the path/name of the underlying compiler to be used"
    echo "   I_MPI_FC_PROFILE or I_MPI_F90_PROFILE or MPIF90_PROFILE" 
    echo "                   the name of profile file (without extension)" 
    echo "   I_MPI_COMPILER_CONFIG_DIR" 
    echo "                   the folder which contains configuration files *.conf"
    echo "   I_MPI_TRACE_PROFILE"
    echo "                   specify a default profile for the -trace option"
    echo "   I_MPI_CHECK_PROFILE"
    echo "                   specify a default profile for the -check_mpi option"
    echo "   I_MPI_LINK      specify the version of the Intel(R) MPI Library"
    echo "   I_MPI_DEBUG_INFO_STRIP"
    echo "                   turn on/off the debug information stripping during static linking"
    echo "   I_MPI_FCFLAGS"
    echo "                   special flags needed for compilation"
    echo "   I_MPI_LDFLAGS "
    echo "                   special flags needed for linking" 
    echo "----------------------------------------------------------------------------" 
    exit 0
    ;;
    -nolinkage)
    # This internal option is used by wrapper driver scripts mpicc, mpicxx, mpifc when -v option is used.
    linking=no
    addarg=no
    ;;
    -g)
    MPILIBDIR=${release_lib_dir}
    ;;
    -static_log)
    static_log=yes
    addarg=no
    ;;
    -dynamic_log)
    static_log=no
    addarg=no
    ;;
    -mt_mpi)
    addarg=no
    ;;
    -ilp64)
    ilp64=yes
    addarg=no
    ;;
    -i8)
    if [ -z "$no_ilp64" ] ; then
        ilp64=yes
    fi
    if [ "$F90" = gfortran ]; then
        FFLAGS="-fdefault-integer-8 $FFLAGS"
        addarg=no
    else
        addarg=yes
    fi
    ;;
    -fdefault-integer-8)
    if [ -z "$no_ilp64" ] ; then
        ilp64=yes
    fi
    ;;
    -no_ilp64)
    no_ilp64=yes
    ilp64=no
    addarg=no
    ;;
    -check_mpi)
    if [ -z "$profConf" ]; then
        if [ -z "$I_MPI_CHECK_PROFILE" ]; then  
            profConf="vtmc"  
        else  
            profConf="$I_MPI_CHECK_PROFILE"  
        fi
    else
        echo "Warning: the -check_mpi option will be ignored because the profile was set."
    fi  
    addarg=no  
    ;;  
    -nativelinking)
    # Internal option to use native compiler for linking without MPI libraries
    nativelinking=yes
    addarg=no
    ;;
    -trace-imbalance)                                                 
    if [ -z "$profConf" ]; then
        profConf="vtim"                                                                 
    else
        echo "Warning: the -trace-imbalance option will be ignored because the profile was set."                                                            
    fi  
    addarg=no  
    ;;
    -t | -trace | -t=* | -trace=* )  
    if [ -z "$profConf" ]; then
        if [ -z "$I_MPI_TRACE_PROFILE" ]; then  
            profConf="vt"  
        else  
            profConf="$I_MPI_TRACE_PROFILE"  
        fi  
    else
        echo "Warning: the -trace option will be ignored because the profile was set."
    fi  
    addarg=no
    ;;
    -fc=*)
    FC=`echo A$arg | sed -e 's/A-fc=//g'`
    if [ "$#" -eq "1" ] ; then
            echo "Error: extra arguments required"
            echo "usage: mpiifort -fc=<name> -v"
            exit 1
    fi
    addarg=no
    ;;
    -link_mpi=* )
    mpilib_override=`echo A$arg | sed -e 's/A-link_mpi=//g'`
    addarg=no
    ;;
    -nostrip )
    strip_debug_info=no
    addarg=no
    ;;
    -norpath )
    no_rpath=yes
    addarg=no
    ;;
    # Other arguments.  We are careful to handle arguments with 
    # quotes (we try to quote all arguments in case they include 
    # any spaces)
    *\"*) 
    qarg="'"$arg"'"
    case $arg in 
       -D*)
       cppflags="$cppflags $qarg"
       ;;
    esac
    ;;
    *\'*) 
    qarg=`echo \"$arg\"`
    case $arg in 
       -D*)
       cppflags="$cppflags $qarg"
       ;;
    esac
    ;;
    # The following are special args used to handle .F files when the
    # Fortran compiler itself does not handle these options
    -I*)
    qarg="'$arg'"
    cppflags="$cppflags $qarg"
    ;;
    -D*)
    qarg="'$arg'"
    cppflags="$cppflags $qarg"
    ;;
    *.F|*.F90|.fpp|.FPP)
# If FCCPP is not empty, then we need to do the following:
#    If any input files have the .F or .F90 extension, then    
#        If FCCPP = false, then
#            generate an error message and exit
#        Use FCCPP to convert the file from .F to .f, using 
#            $TMPDIR/f$$-$count.f as the output file name
#            Replace the input file with this name in the args
# This is needed only for very broken systems
#     
    if [ -n "$FCCPP" ] ; then
        if [ "$FCCPP" = "false" ] ; then
            echo "This Fortran compiler does not accept .F or .F90 files"
        exit 1
        fi
        addarg=no
    # Remove and directory names and extension
    $ext=`expr "$arg" : '.*\(\..*\)'`
        bfile=`basename $arg $ext`
    # 
    TMPDIR=${TMPDIR:-/tmp}
    # Make sure that we use a valid extension for the temp file.
        tmpfile=$TMPDIR/f$$-$bfile.$FCEXT
        if $FCCPP $cppflags $arg > $tmpfile ; then
            # Add this file to the commandline list
        count=`expr $count + 1`
        allargs="$allargs $tmpfile"
        rmfiles="$rmfiles $tmpfile"
        else
        echo "Aborting compilation because of failure in preprocessing step"
        echo "for file $arg ."
        exit 1
        fi
    fi
    # Otherwise, just accept the argument
    ;;
    # - end of special handling for .F files

    *)
    qarg="'$arg'"
    ;;

    esac
    if [ $addarg = yes ] ; then
        allargs="$allargs $qarg"
    fi
done

if [ $# -eq 0 ] ; then
    echo "Error: Command line argument is needed!"
    "$0" -help
    exit 1
fi

if [ -n "$mpilib_override" ] ; then
    case "$mpilib_override" in
    opt ) 
        MPILIBDIR=${release_lib_dir}
        ;;
    opt_mt )
        MPILIBDIR=${release_lib_dir}
        ;;
    dbg )
        MPILIBDIR=${debug_lib_dir}
        ;;
    dbg_mt )
        MPILIBDIR=${debug_lib_dir}
        ;;
    * )
        echo "Warning: incorrect library version specified. Automatically selected library will be used."
        ;;
    esac
fi
# -----------------------------------------------------------------------
# Choose mod file corresponded gfortran version
# Tr#2270, Tr#2453, Tr#3206, Tr#3434
gfort_ver=`$FC --version | head -n 1 | cut -d '(' -f1,2 | sed -e 's/\[.*//' | sed -e 's/.*(//' | sed -e 's/[a-zA-Z,/)]//g' | sed -e 's/^[[:space:]]*//' | sed -e 's/ .*//g' | sed -e 's/-.*//'`
if [ -n "$gfort_ver" ]; then
    #gfort_ver=`echo $gfort_ver | sed -e 's/gcc version //' | awk '{print $1}'`
    major=`echo $gfort_ver | awk -F. '{print $1}'`
    mid=`echo $gfort_ver | awk -F. '{print $2}'` 
    low=`echo $gfort_ver | awk -F. '{print $3}'` 
    case "$major" in
    4 )
        case "$mid" in
        0 )
            if [ $low -eq 0 -o $low -eq 1 ]; then
            gver="/4.0.0"
            else
            gver="/4.0.2"
            fi
            ;;
        8 )
                gver="/4.8.0"
            ;;
        9 )
                gver="/4.9.0"
            ;;
        * )
                gver="/4.9.0"
            ;;
        esac
        ;;
    5 )
        case "$mid" in
        1 )
                gver="/5.1.0"
            ;;
        * )
                gver="/5.1.0"
            ;;
        esac
        ;;
    6 )
        case "$mid" in
        1 )
                gver="/6.1.0"
            ;;
        * )
                gver="/6.1.0"
            ;;
        esac
        ;;
    7 )
        case "$mid" in
        1 )
                gver="/7.1.0"
            ;;
        * )
                gver="/7.1.0"
            ;;
        esac
        ;;
    8 )
        case "$mid" in
        2 )
                gver="/8.2.0"
            ;;
        * )
                gver="/8.2.0"
            ;;
        esac
        ;;
    9 )
        case "$mid" in
        1 )
                gver="/9.1.0"
            ;;
        * )
                gver="/9.1.0"
            ;;
        esac
        ;;
    10 )
        case "$mid" in
        2 )
                gver="/10.2.0"
            ;;
        * )
                gver="/10.2.0"
            ;;
        esac
        ;;
    11 )
        case "$mid" in
        1 )
                gver="/11.1.0"
            ;;
        * )
                gver="/11.1.0"
            ;;
        esac
        ;;  
    12 )
        gver="/12.4.0"
        ;;  
    13 )
        gver="/13.3.0"
        ;;  
    14 )
        gver="/14.2.0"
        ;;  
    * )
        gver=""
        ;;
    esac
else
    gver=""
fi

if [ "${FC}" = "gfortran" ]; then
    # Making type mismatch treated as warning to resolve issue with gfortran 10.x
    if [ "$major" -gt 9 ]; then
        FCFLAGS="$FCFLAGS -fallow-argument-mismatch"
    fi
fi

if [ "$ilp64" = yes ] ; then
    modincdir="${modincdir}/ilp64/gfortran${gver}"
else
    modincdir="${modincdir}/gfortran${gver}"
fi

if [ "$static_mpi" = yes ] ; then
    mpilibs="${libdir}/libmpifort.a ${libdir}${MPILIBDIR}/lib${MPILIBNAME}.a"
    I_MPI_OTHERLIBS=" -lrt -lpthread "
    if [ "$ilp64" = yes ]; then
    mpilibs="$libdir/libmpi_ilp64.a $mpilibs"
    fi
    CXX_BIND_LIB="$libdir/lib.a"
    if [ "x$strip_debug_info" = "x" ] ; then
    strip_debug_info=yes
    fi
else
    mpilibs="-lmpifort -l$MPILIBNAME"
    I_MPI_OTHERLIBS=" -lrt -lpthread "
    if [ "$ilp64" = yes ]; then
    mpilibs="-lmpi_ilp64 $mpilibs"
    fi
    CXX_BIND_LIB="-l"
fi
# Derived variables.  These are assembled from variables set from the
# default, environment, configuration file (if any) and command-line
# options (if any)

PROFILE_FOO=
# Handle the case of a profile switch
if [ -n "$profConf" ] ; then
    profConffile=
    if [ -s "$libdir/lib$profConf.a" -o -s "$libdir/lib$profConf.so" ] ; then
    PROFILE_FOO="-l$profConf"
        mpilibs="-l$profConf $mpilibs"             
    elif [ -s "$sysconfdir/$profConf.conf" ] ; then
    profConffile="$sysconfdir/$profConf.conf"
    elif [ -s "$profConf.conf" ] ; then
        profConffile="$profConf.conf"
    else
        echo "Profiling configuration file $profConf.conf not found in $sysconfdir"
    fi
    if [ -n "$profConffile" -a -s "$profConffile" ] ; then
    . $profConffile
        if [ -n "$PROFILE_INCPATHS" ] ; then                                                                            
           CFLAGS="$PROFILE_INCPATHS $CFLAGS"                                                                          
        fi                                                                                                             
        if [ -n "$PROFILE_PRELIB" ] ; then                                                                             
           mpilibs="$PROFILE_PRELIB $mpilibs"                                                                          
        fi
        if [ -n "$PROFILE_POSTLIB" ] ; then
           mpilibs="$mpilibs $PROFILE_POSTLIB"
        fi
    fi
fi

# Construct the line to add the include directory (not all compilers
# use -I, unfortunately)
if [ -z "${FCINC}" ] ; then
    # If there is no path, add a link to the mpif.h file.
    # There *must* be a way to provide the path the any modules (there
    # may be too many to link)
    if [ ! -r mpif.h ] ; then
        #echo "Adding a symbolic link for mpif.h"
    trap "$Show rm -f mpif.h" 0
    # This should really be the (related) f77includedir.
    $Show ln -s ${includedir}/mpif.h mpif.h
    # Remember to remove this file
    rmfiles="$rmfiles mpif.h"
    fi
    FCINCDIRS=
else
    # Normally, FCINC is just -I, but some compilers have used different
    # command line arguments
    FCINCDIRS="${FCINC}\"${includedir}\" ${FCINC}\"${includedir}/mpi\""
fi

# Handle the specification of the directory containing the modules
if [ -n "$FCMODINCSPEC" ] ; then
    newarg=`echo A"$FCMODINCSPEC" | \
    sed -e 's/^A//' -e 's%<dir>%'"$includedir%g" -e 's/<file>/mpi/g'`
    FCMODDIRS="$newarg"
elif [ -n "$FCMODINC" ] ; then
    FCMODDIRS="${FCMODINC}\"${modincdir}\""
fi

final_fcflags=" "
final_ldflags="  -Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Xlinker --enable-new-dtags -ldl  "
final_libs="-lpthread -lrt "

# A temporary statement to invoke the compiler
# Place the -L before any args incase there are any mpi libraries in there.
# Eventually, we'll want to move this after any non-MPI implementation
# libraries
if [ "$no_rpath" = "yes" ]; then
    rpath_opt="-Xlinker --enable-new-dtags"
else
    rpath_opt="-Xlinker --enable-new-dtags -Xlinker -rpath -Xlinker \"${libdir}${MPILIBDIR}\" -Xlinker -rpath -Xlinker \"${libdir}\""
fi
if [ "$linking" = yes ] ; then
    if [ "$nativelinking" = yes ] ; then
        $Show $FC $PROFILE_INCPATHS   -Wl,-z,now -Wl,-z,relro -Wl,-z,noexecstack -Xlinker --enable-new-dtags -ldl   $allargs
        rc=$?
    else
        $Show $FC $FCFLAGS $allargs $FCMODDIRS $FCINCDIRS -L\"${libdir}${MPILIBDIR}\" -L\"${libdir}\" $rpath_opt $mpilibs $I_MPI_OTHERLIBS ${final_ldflags}
        rc=$?
        if [ $rc -eq 0 -a "x$strip_debug_info" = "xyes" ] ; then
            $Show objcopy --only-keep-debug ${executable} ${executable}.dbg
            $Show objcopy --strip-debug ${executable}
            $Show objcopy --add-gnu-debuglink=${executable}.dbg ${executable}
        fi
    fi
#        if [ "$static_mpi" = no ] ; then
#          $Show $FC $PROFILE_INCPATHS ${final_fcflags} ${final_ldflags} "${allargs[@]}" $FCINCDIRS $FCMODDIRS -L$libdir -lmpifort $PROFILE_PRELIB $PROFILE_FOO ${wrapper_dl_type_flags} -lmpi  $PROFILE_POSTLIB ${final_libs} 
#        else
#          $Show $FC $PROFILE_INCPATHS ${final_fcflags} ${final_ldflags} "${allargs[@]}" $FCINCDIRS $FCMODDIRS -L$libdir -lmpifort $PROFILE_PRELIB $PROFILE_FOO ${wrapper_dl_type_flags} $libdir/libmpi.a  $PROFILE_POSTLIB ${final_libs} 
#        fi
#        rc=$?
#        if [ $rc -eq 0 -a "x$strip_debug_info" = "xyes" ] ; then
#        $Show objcopy --only-keep-debug ${executable} ${executable}.dbg
#        $Show objcopy --strip-debug ${executable}
#        $Show objcopy --add-gnu-debuglink=${executable}.dbg ${executable}
#    fi
#    fi
else
    cmd_line="$FC $FCFLAGS $allargs $FCMODDIRS $FCINCDIRS"
    if [ "$Show" = echo ] ; then
        echo $cmd_line
    else
        eval `echo $cmd_line`
    fi
    rc=$?
fi
if [ -n "$rmfiles" ] ; then
    for file in $rmfiles ; do
        objfile=`basename $file .f`
    if [ -s "${objfile}.o" ] ; then
        # Rename 
        destfile=`echo $objfile | sed -e "s/.*$$-//"`
        mv -f ${objfile}.o ${destfile}.o
    fi
        rm -f $file
    done
    rm -f $rmfiles
fi
exit $rc
