# This file defines:
# - ZLIB_INCLUDE_DIRS
# - ZLIB_LIBRARIES
# - ZLIB_FOUND
# - ZLIB_DEFINITIONS
# Taking into account:
# - ZLIB_PREFIX

FIND_PATH(ZLIB_INCLUDE zlib.h
  ${ZLIB_PREFIX}/include
  /usr/include
)

IF(WIN32)
  FIND_LIBRARY(ZLIB_LIB_RELEASE
    NAMES
      zlibstat zlibstatic zlib 
    PATHS
      /usr/lib
      ${ZLIB_PREFIX}/lib
  )

  FIND_LIBRARY(ZLIB_LIB_DEBUG
    NAMES
      zlibstatd zlibstaticd zlibd
    PATHS
      ${ZLIB_PREFIX}/lib
  )

  IF(ZLIB_INCLUDE AND ZLIB_LIB_RELEASE AND ZLIB_LIB_DEBUG)
    SET(ZLIB_FOUND TRUE)

    # We used to set this, but that was a bad idea. Try to remain backward
    # compatible
    SET(ZLIB_test_fname "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/zlib.c")
    FILE(WRITE
      "${ZLIB_test_fname}"
      "#include \"zlib.h\"\nint main() { deflate(0,0); return 0; }"
    ) 
    TRY_COMPILE(ZLIB_WORKS_WITHOUT_DEFINES
      "${CMAKE_BINARY_DIR}" "${ZLIB_test_fname}"
      CMAKE_FLAGS
        -DLINK_LIBRARIES=${ZLIB_LIB_RELEASE}
        -DINCLUDE_DIRECTORIES=${ZLIB_INCLUDE}
    )
    FILE(WRITE
      "${ZLIB_test_fname}"
      "#include \"zlib.h\"\nint main() { deflate(0,0); return 0; }"
    ) 
    TRY_COMPILE(ZLIB_WORKS_WITH_DEFINES
      "${CMAKE_BINARY_DIR}" "${ZLIB_test_fname}"
      CMAKE_FLAGS
        -DLINK_LIBRARIES=${ZLIB_LIB_RELEASE}
        -DINCLUDE_DIRECTORIES=${ZLIB_INCLUDE}
      COMPILE_DEFINITIONS
        "-DZLIB_WINAPI"
    )
    IF(ZLIB_WORKS_WITH_DEFINES AND NOT ZLIB_WORKS_WITHOUT_DEFINES)
      SET(ZLIB_DEFINITIONS -DZLIB_WINAPI)
      MESSAGE(STATUS "zlib requires -DZLIB_WINAPI, consider recompiling")
    ENDIF(ZLIB_WORKS_WITH_DEFINES AND NOT ZLIB_WORKS_WITHOUT_DEFINES)

    SET(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE})
    SET(ZLIB_LIBRARIES optimized ${ZLIB_LIB_RELEASE} debug ${ZLIB_LIB_DEBUG})
  ELSE(ZLIB_INCLUDE AND ZLIB_LIB_RELEASE AND ZLIB_LIB_DEBUG)
    SET(ZLIB_FOUND FALSE)
  ENDIF(ZLIB_INCLUDE AND ZLIB_LIB_RELEASE AND ZLIB_LIB_DEBUG)
ELSE(WIN32)
  FIND_LIBRARY(ZLIB_LIB
    NAMES
      z
    PATHS
      /usr/lib
      ${ZLIB_PREFIX}/lib
  )

  IF(ZLIB_INCLUDE AND ZLIB_LIB)
    SET(ZLIB_FOUND TRUE)
    SET(ZLIB_INCLUDE_DIRS ${ZLIB_INCLUDE})
    SET(ZLIB_LIBRARIES ${ZLIB_LIB})
  ELSE(ZLIB_INCLUDE AND ZLIB_LIB)
    SET(ZLIB_FOUND FALSE)
  ENDIF(ZLIB_INCLUDE AND ZLIB_LIB)
ENDIF(WIN32)

