cmake_policy(PUSH)
if (POLICY CMP0075)
  cmake_policy(SET CMP0075 NEW)
endif()

include (CheckTypeSize)

if (mpi)
  find_package(MPI REQUIRED)
  list(APPEND CMAKE_REQUIRED_INCLUDES   ${MPI_CXX_INCLUDE_PATH})
  list(APPEND CMAKE_EXTRA_INCLUDE_FILES "mpi.h")
  list(APPEND CMAKE_REQUIRED_LIBRARIES  ${MPI_CXX_LIBRARIES})
else()
  list(APPEND CMAKE_REQUIRED_INCLUDES ${PROJECT_SOURCE_DIR}/include)
  list(APPEND CMAKE_EXTRA_INCLUDE_FILES "${diy_prefix}/mpi/no-mpi.hpp")
endif()

list(APPEND CMAKE_REQUIRED_INCLUDES ${PROJECT_SOURCE_DIR}/cmake)
list(APPEND CMAKE_EXTRA_INCLUDE_FILES "mpi_types.h")

if (NOT (DEFINED CACHE{previous_mpi} AND ((previous_mpi AND mpi) OR (NOT(previous_mpi OR mpi)))))
  unset(TYPESIZE_MPI_Comm          CACHE)
  unset(HAVE_TYPESIZE_MPI_Comm     CACHE)
  unset(TYPESIZE_MPI_Datatype      CACHE)
  unset(HAVE_TYPESIZE_MPI_Datatype CACHE)
  unset(TYPESIZE_MPI_Status        CACHE)
  unset(HAVE_TYPESIZE_MPI_Status   CACHE)
  unset(TYPESIZE_MPI_Request       CACHE)
  unset(HAVE_TYPESIZE_MPI_Request  CACHE)
  unset(TYPESIZE_MPI_Op            CACHE)
  unset(HAVE_TYPESIZE_MPI_Op       CACHE)
  unset(TYPESIZE_MPI_File          CACHE)
  unset(HAVE_TYPESIZE_MPI_File     CACHE)
  unset(TYPESIZE_MPI_Win           CACHE)
  unset(HAVE_TYPESIZE_MPI_Win      CACHE)

  set (previous_mpi ${mpi} CACHE INTERNAL "" FORCE)
endif()

set(CMAKE_CXX_STANDARD 11)

check_type_size("Wrapped_MPI_Comm"     TYPESIZE_MPI_Comm     LANGUAGE CXX)
check_type_size("Wrapped_MPI_Datatype" TYPESIZE_MPI_Datatype LANGUAGE CXX)
check_type_size("Wrapped_MPI_Status"   TYPESIZE_MPI_Status   LANGUAGE CXX)
check_type_size("Wrapped_MPI_Request"  TYPESIZE_MPI_Request  LANGUAGE CXX)
check_type_size("Wrapped_MPI_Op"       TYPESIZE_MPI_Op       LANGUAGE CXX)
check_type_size("Wrapped_MPI_File"     TYPESIZE_MPI_File     LANGUAGE CXX)
check_type_size("Wrapped_MPI_Win"      TYPESIZE_MPI_Win      LANGUAGE CXX)
configure_file("include/${diy_prefix}/mpi/mpitypes.hpp.in" "include/${diy_prefix}/mpi/mpitypes.hpp" @ONLY)

cmake_policy(POP)
