include(FindPackageHandleStandardArgs)
include(CheckFunctionExists)

FIND_PATH(PNETCDF_INCLUDE_DIR 
          pnetcdf.h
          HINTS ${PNETCDF_DIR}/include
          CACHE)
MESSAGE("PNETCDF_INCLUDE_DIR: ${PNETCDF_INCLUDE_DIR}")
IF (${PREFER_SHARED})
  FIND_LIBRARY(PNETCDF_LIBRARY 
               NAMES pnetcdf
               HINTS ${PNETCDF_DIR}/lib
               CACHE)
ELSE ()
  FIND_LIBRARY(PNETCDF_LIBRARY 
               NAMES libpnetcdf.a pnetcdf
               HINTS ${PNETCDF_DIR}/lib
               CACHE)
ENDIF ()

if(${PNETCDF_LIBRARY} STREQUAL "PNETCDF_LIBRARY-NOTFOUND")
  MESSAGE("PNETCDF library not found")
  return()
endif()

find_file( PNETCDFTEST NAMES TryPnetcdf_mod.f90  PATHS ${CMAKE_MODULE_PATH} NO_DEFAULT_PATH)
get_filename_component( CMAKE_TEST_PATH ${PNETCDFTEST} PATH)

TRY_COMPILE(PNETCDF_MOD  ${CMAKE_CURRENT_BINARY_DIR}/tryPnetcdf_mod
                          ${CMAKE_TEST_PATH}/TryPnetcdf_mod.f90
			  COMPILE_DEFINITIONS -I${PNETCDF_INCLUDE_DIR}
			  CMAKE_FLAGS "-DLINK_LIBRARIES:STRING=${PNETCDF_LIBRARY}"
                           OUTPUT_VARIABLE Pnet_OUT)

if(NOT PNETCDF_MOD)
  TRY_COMPILE(PNETCDF_INC  ${CMAKE_CURRENT_BINARY_DIR}/tryPnetcdf_inc
                          ${CMAKE_TEST_PATH}/TryPnetcdf_inc.f90
			  COMPILE_DEFINITIONS -I${PNETCDF_INCLUDE_DIR}
			  CMAKE_FLAGS "-DLINK_LIBRARIES:STRING=${PNETCDF_LIBRARY}"
                           OUTPUT_VARIABLE Pnet_OUT)
endif()

SET(CMAKE_REQUIRED_LIBRARIES ${PNETCDF_LIBRARY})
CHECK_FUNCTION_EXISTS(ncmpi_get_varn PNETCDF_VARN)
if(PNETCDF_VARN)
  LIST(APPEND PNETCDF_CPPDEFS -DUSE_PNETCDF_VARN)
  LIST(APPEND PNETCDF_CPPDEFS -DUSE_PNETCDF_VARN_ON_READ)
endif()  

SET(PNETCDF_LIBRARIES ${PNETCDF_LIBRARY} )
SET(PNETCDF_INCLUDE_DIRS ${PNETCDF_INCLUDE_DIR} )

# Handle QUIETLY and REQUIRED.
find_package_handle_standard_args(pnetcdf DEFAULT_MSG
  PNETCDF_LIBRARY PNETCDF_INCLUDE_DIR  )

mark_as_advanced(PNETCDF_INCLUDE_DIR PNETCDF_LIBRARY PNETCDF_INC PNETCDF_MOD PNETCDF_CPPDEFS)
