# ===========================================================================
#     https://www.gnu.org/software/autoconf-archive/ax_prog_cxx_mpi.html
# ===========================================================================
#
# SYNOPSIS
#
#   AX_PROG_CXX_MPI([MPI-WANTED-TEST[, ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]]])
#
# DESCRIPTION
#
#   This macro tries to find out how to compile C++ programs that use MPI
#   (Message Passing Interface), a standard API for parallel process
#   communication (see http://www-unix.mcs.anl.gov/mpi/).  The macro has to
#   be used instead of the standard macro AC_PROG_CXX and will replace the
#   standard variable CXX with the found compiler.
#
#   MPI-WANTED-TEST is used to test whether MPI is actually wanted by the
#   user. If MPI-WANTED_TEST is omitted or if it succeeds, the macro will
#   try to find out how to use MPI, if it fails, the macro will call
#   AC_PROG_CC to find a standard C compiler instead.
#
#   When MPI is found, ACTION-IF-FOUND will be executed, if MPI is not found
#   (or MPI-WANTED-TEST fails) ACTION-IF-NOT-FOUND is executed. If
#   ACTION-IF-FOUND is not set, the macro will define HAVE_MPI.
#
#   The following example demonstrates usage of the macro:
#
#     # If --with-mpi=auto is used, try to find MPI, but use standard C
#     compiler if it is not found.
#     # If --with-mpi=yes is used, try to find MPI and fail if it isn't found.
#     # If --with-mpi=no is used, use a standard C compiler instead.
#     AC_ARG_WITH(mpi, [AS_HELP_STRING([--with-mpi],
#         [compile with MPI (parallelization) support. If none is found,
#         MPI is not used. Default: auto])
#     ],,[with_mpi=auto])
#
#     AX_PROG_CXX_MPI([test x"$with_mpi" != xno],[use_mpi=yes],[
#       use_mpi=no
#       if test x"$with_mpi" = xyes; then
#         AC_MSG_FAILURE([MPI compiler requested, but couldn't use MPI.])
#       else
#         AC_MSG_WARN([No MPI compiler found, won't use MPI.])
#       fi
#     ])
#
# LICENSE
#
#   Copyright (c) 2010,2011 Olaf Lenz <olenz@icp.uni-stuttgart.de>
#
#   This program is free software: you can redistribute it and/or modify it
#   under the terms of the GNU General Public License as published by the
#   Free Software Foundation, either version 3 of the License, or (at your
#   option) any later version.
#
#   This program is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
#   Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program. If not, see <https://www.gnu.org/licenses/>.
#
#   As a special exception, the respective Autoconf Macro's copyright owner
#   gives unlimited permission to copy, distribute and modify the configure
#   scripts that are the output of Autoconf when processing the Macro. You
#   need not follow the terms of the GNU General Public License when using
#   or distributing such scripts, even though portions of the text of the
#   Macro appear in them. The GNU General Public License (GPL) does govern
#   all other use of the material that constitutes the Autoconf Macro.
#
#   This special exception to the GPL applies to versions of the Autoconf
#   Macro released by the Autoconf Archive. When you make and distribute a
#   modified version of the Autoconf Macro, you may extend this special
#   exception to the GPL to apply to your modified version as well.

#serial 3

AC_DEFUN([AX_PROG_CXX_MPI], [
AC_PREREQ(2.50)

# Check for compiler
# Needs to be split off into an extra macro to ensure right expansion
# order.
AC_REQUIRE([_AX_PROG_CXX_MPI],[_AX_PROG_CXX_MPI([$1])])

AS_IF([test x"$_ax_prog_cxx_mpi_mpi_wanted" = xno],
  [ _ax_prog_cxx_mpi_mpi_found=no ],
  [
    AC_LANG_PUSH([C++])

    # test whether MPI_Init() is available
    # We do not use AC_SEARCH_LIBS here, as it caches its outcome and
    # thus disallows corresponding calls in the other AX_PROG_*_MPI
    # macros.
    for lib in NONE mpi mpich; do
      save_LIBS=$LIBS
      if test x"$lib" = xNONE; then
        AC_MSG_CHECKING([for function MPI_Init])
      else
        AC_MSG_CHECKING([for function MPI_Init in -l$lib])
        LIBS="-l$lib $LIBS"
      fi
      AC_LINK_IFELSE([
        AC_LANG_PROGRAM([
extern "C" { void MPI_Init(); }
],[MPI_Init();])],
        [ _ax_prog_cxx_mpi_mpi_found=yes ],
        [ _ax_prog_cxx_mpi_mpi_found=no ])
      AC_MSG_RESULT($_ax_prog_cxx_mpi_mpi_found)
      if test "x$_ax_prog_cxx_mpi_mpi_found" = "xyes"; then
        break;
      fi
      LIBS=$save_LIBS
    done

    # Check for header
    AS_IF([test x"$_ax_prog_cxx_mpi_mpi_found" = xyes], [
      AC_MSG_CHECKING([for mpi.h])
      AC_COMPILE_IFELSE([AC_LANG_PROGRAM([#include <mpi.h>])],
        [ AC_MSG_RESULT(yes)],
        [ AC_MSG_RESULT(no)
         _ax_prog_cxx_mpi_mpi_found=no
      ])
    ])
    AC_LANG_POP([C++])
])

# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
AS_IF([test x"$_ax_prog_cxx_mpi_mpi_found" = xyes], [
        ifelse([$2],,[AC_DEFINE(HAVE_MPI,1,[Define if you have the MPI library.])],[$2])
        :
],[
        $3
        :
])

])dnl AX_PROG_CXX_MPI

dnl _AX_PROG_CXX_MPI is an internal macro required by AX_PROG_CXX_MPI.
dnl To ensure the right expansion order, the main function AX_PROG_CXX_MPI
dnl has to be split into two parts.
dnl
dnl Known MPI C++ compilers:
dnl  mpic++
dnl  mpicxx
dnl  mpiCC
dnl  sxmpic++     NEC SX
dnl  hcp
dnl  mpxlC_r
dnl  mpxlC
dnl  mpixlcxx_r
dnl  mpixlcxx
dnl  mpg++
dnl  mpc++
dnl  mpCC
dnl  cmpic++
dnl  mpiFCC       Fujitsu
dnl  CC
dnl
AC_DEFUN([_AX_PROG_CXX_MPI], [
  AC_ARG_VAR(MPICXX,[MPI C++ compiler command])
  ifelse([$1],,[_ax_prog_cxx_mpi_mpi_wanted=yes],[
    AC_MSG_CHECKING([whether to compile using MPI])
    if $1; then
      _ax_prog_cxx_mpi_mpi_wanted=yes
    else
      _ax_prog_cxx_mpi_mpi_wanted=no
    fi
    AC_MSG_RESULT($_ax_prog_cxx_mpi_mpi_wanted)
  ])
  if test x"$_ax_prog_cxx_mpi_mpi_wanted" = xyes; then
    if test -z "$CXX" && test -n "$MPICXX"; then
      CXX="$MPICXX"
    else
      AC_CHECK_TOOLS([CXX], [mpic++ mpicxx mpiCC sxmpic++ hcp mpxlC_r mpxlC mpixlcxx_r mpixlcxx mpg++ mpc++ mpCC cmpic++ mpiFCC CCicpc pgCC pathCC sxc++ xlC_r xlC bgxlC_r bgxlC openCC sunCC crayCC g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC])
    fi
  fi
  AC_PROG_CXX
])dnl _AX_PROG_CXX_MPI

# CAPABILITY TESTING MACROS
m4_define(
  [M4_HDF5_LIB],
  [
    cat > nptm_test_hdf5.cpp <<EOF
#include <hdf5.h>
int main(int argc, char **argv) {
  hid_t file_id = 0;
  herr_t status = H5Iis_valid(file_id);
  return (int)status;
}
EOF
    $CXX -o nptm_test_hdf5 nptm_test_hdf5.cpp -I$HDF5_INCLUDE -L$HDF5_LIB -lhdf5 > /dev/null 2>>error.log
    export TEST_HDF5_LIB=$?
    rm nptm_test_hdf5.cpp
    if test "x$TEST_HDF5_LIB" = "x0"; then
      rm nptm_test_hdf5
    fi
  ]
)

m4_define(
  [M4_DETECT_LAPACK],
  [
    export -p | grep MKL
    MKL_DEF=$?
    if test "x$MKL_DEF" = "x0"; then
      export LAPACKFLAGS="-DUSE_LAPACK -DLAPACK_ILP64 -DUSE_ILP64 -I{MKLROOT}/include"
      export LAPACKLDFLAGS="-L${MKLROOT}/lib -Wl,--no-as-needed -lmkl_intel_ilp64 -lmkl_gnu_thread -lmkl_core -lgomp -lpthread -lm -ldl"
    else
      if test -f /usr/include/lapacke.h; then
        export LAPACKFLAGS="-DUSE_LAPACK -DLAPACK_ILP64 -DUSE_ILP64"
	export LAPACKLDFLAGS="-llapacke64"
      fi
    fi
  ]
)

m4_define(
  [M4_DETECT_MAGMA],
  [
    if test "x$CUDA_LIB" = "x"; then
      export -p | grep CUDA
      CUDA_DEF=$?
      if test "x$CUDA_DEF" = "x0"; then
        CUDA_LIB=${CUDA_HOME}/targets/x86_64-linux/lib
      else
        CUDA_LIB=/usr/local/cuda/targets/x86_64-linux/lib
      fi
    fi
    export -p | grep MAGMA
    MAGMA_DEF=$?
    if test "x$MAGMA_DEF" = "x0"; then
      export MAGMAFLAGS="-DUSE_MAGMA -DMAGMA_ILP64 -I${MAGMA_INCLUDE}"
      export MAGMALDFLAGS="-L${CUDA_LIB} -lcudart -L${MAGMA_LIB} -lmagma"
    else
      if test "x$MAGMA_INCLUDE" != "x"; then
        export MAGMAFLAGS="-DUSE_MAGMA -DMAGMA_ILP64 -I${MAGMA_INCLUDE}"
      else
        if test -f /usr/include/magma_v2.h; then
          export MAGMAFLAGS="-DUSE_MAGMA -DMAGMA_ILP64"
	fi
      fi
      if test "x$MAGMA_LIB" != "x"; then
        export MAGMALDFLAGS="-L${CUDA_LIB} -lcudart -L${MAGMA_LIB} -lmagma"
      else
        if test -f /usr/include/magma_v2.h; then
          export MAGMALDFLAGS="-L${CUDA_LIB} -lcudart -lmagma"
	fi
      fi
    fi
  ]
)
# END CAPABILITY TESTING MACROS

# autoconf setup initialization
AC_INIT([np_tmcode], [8.04], [giovanni.lamura@inaf.it])

# Folder structure safety check
AC_CONFIG_SRCDIR([../src/libnptm/TransitionMatrix.cpp])

# Auxiliary build folder
AC_CONFIG_AUX_DIR([build_aux])

# automake initialization
AM_INIT_AUTOMAKE([-Wall -Werror foreign])

# Compiler detection
AM_PROG_AR
AC_ARG_ENABLE(
  [mpi],
  [AS_HELP_STRING([--enable-mpi], [enable MPI compilation [default=auto]])],
  [AC_MSG_NOTICE([Handling explicit option.])],
  [
    AC_MSG_NOTICE([Handling implicit option.])
    AX_PROG_CXX_MPI()
    AC_SUBST([MPIFLAGS], [-DUSE_MPI])
  ]
)
AS_IF(
  [test "x$CXX" = "x"],
  [AC_PROG_CXX([g++ clang])],
  [AC_MSG_NOTICE([Using $CXX])]
)
AC_PROG_F77([mpif90 gfortran f77])

# Libtool initialization
LT_INIT

# Environment setup
AS_IF(
  [test "x$HDF5_INCLUDE" = "x"],
  [AC_SUBST([HDF5_INCLUDE], ["/usr/include/hdf5/serial"])],
  [AC_MSG_NOTICE([HDF5_INCLUDE=$(HDF5_INCLUDE)])]
)
AS_IF(
  [test "x$HDF5_LIB" = "x"],
  [AC_SUBST([HDF5_LIB], ["/usr/lib/x86_64-linux-gnu/hdf5/serial"])],
  [AC_MSG_NOTICE([HDF5_LIB=$(HDF5_LIB)])]
)

# Check for required headers
AC_CHECK_HEADER(
  [$HDF5_INCLUDE/hdf5.h],
  ,
  AC_MSG_ERROR(["Could not find HDF5 headers!]),
)

# Check for required libraries
M4_HDF5_LIB
AS_IF(
  [test "x$TEST_HDF5_LIB" = "x0"],
  [AC_SUBST([HDF5_LDFLAGS], ["-L${HDF5_LIB} -lhdf5"])],
  [AC_MSG_ERROR(["HDF5 library not found!"])]
)

# Configure the optional features
M4_DETECT_LAPACK
AS_IF(
  [test "x$LAPACKLDFLAGS" != "x"],
  [AC_MSG_NOTICE([LAPACK detected. Activating by default (use --without-lapack to disable).])],
  [AC_MSG_NOTICE([No LAPACK found.])]
)

M4_DETECT_MAGMA
AS_IF(
  [test "x$MAGMALDFLAGS" != "x"],
  [AC_MSG_NOTICE([MAGMA detected. Activating by default (use --without-magma to disable).])],
  [AC_MSG_NOTICE([MAGMA not found.])]
)

AC_ARG_ENABLE(
  [openmp],
  [AS_HELP_STRING([--enable-openmp], [enable OpneMP multi-threading [default=yes]])],
  [
    if test "x$enableval" != "xno"; then
      AC_SUBST([OMPFLAGS], ["-fopenmp"])
    fi
  ],
  [
    AC_SUBST([OMPFLAGS], ["-fopenmp"])
  ]
)

AC_ARG_WITH(
  [lapack],
  [AS_HELP_STRING([--with-lapack], [use LAPACK @<:@default=check@:>@])],
  [
    if test "x$withval" = "xno"; then
      AC_SUBST([LAPACKFLAGS], [""])
      AC_SUBST([LAPACKLDFLAGS], [""])
    else
      AC_SUBST([LAPACKFLAGS], [${LAPACKFLAGS}])
      AC_SUBST([LAPACKLDFLAGS], [${LAPACKLDFLAGS}])
    fi
  ],
  [
    AC_SUBST([LAPACKFLAGS], [${LAPACKFLAGS}])
    AC_SUBST([LAPACKLDFLAGS], [${LAPACKLDFLAGS}])
  ]
)

AC_ARG_WITH(
  [magma],
  [AS_HELP_STRING([--with-magma], [use MAGMA @<:@default=check@:>@])],
  [
    if test "x$withval" = "xno"; then
      AC_SUBST([MAGMAFLAGS], [""])
      AC_SUBST([MAGMALDFLAGS], [""])
    else
      AC_SUBST([MAGMAFLAGS], [${MAGMAFLAGS}])
      AC_SUBST([MAGMALDFLAGS], [${MAGMALDFLAGS}])
    fi
  ],
  [
    AC_SUBST([MAGMAFLAGS], [${MAGMAFLAGS}])
    AC_SUBST([MAGMALDFLAGS], [${MAGMALDFLAGS}])
  ]
)

FFLAGS="-std=legacy -O3"
CXXFLAGS="-O3 -ggdb -I$HDF5_INCLUDE $MPIFLAGS $OMPFLAGS $LAPACKFLAGS $MAGMAFLAGS"
SUBDIRS="cluster libnptm sphere testing trapping"

# Send output to Makefiles
AC_CONFIG_FILES([Makefile])

# Generate the output
AC_OUTPUT