set(FILE_VERSION_CMAKE_PATH ${CMAKE_CURRENT_LIST_DIR})

function(version_configure FILE_PATH VERSION_RESULT BUILD_RESULT)
  if(EXISTS "${FILE_PATH}")
    file(STRINGS ${FILE_PATH} FILE_STRINGS)
  endif()
  set(VERSION_MAJOR 0)
  set(VERSION_MINOR 0)
  set(VERSION_PATCH 0)
  set(VERSION_TWEAK 0)
  foreach(FILE_STRING ${FILE_STRINGS})
    string(REPLACE " " ";" STRING_LIST ${FILE_STRING})
    list(LENGTH STRING_LIST len)
    if (${len} GREATER 1)
      list(GET STRING_LIST 0 VAR_NAME)
      list(GET STRING_LIST 1 VAR_VALUE)
      if ((NOT VAR_VALUE MATCHES "^[0-9]+$") AND
          (NOT VAR_NAME STREQUAL "BUILD"))
        set(VAR_VALUE "0")
      endif()
      set(VERSION_${VAR_NAME} ${VAR_VALUE})
    endif()
  endforeach()

  set(VERSION_NAME "")
  if (VERSION_TWEAK GREATER 0)
    set(VERSION_NAME ".${VERSION_TWEAK}")
  endif()
  if ((VERSION_PATCH GREATER 0) OR
      (VERSION_NAME))
    set(VERSION_NAME ".${VERSION_PATCH}${VERSION_NAME}")
  endif()
  if ((VERSION_MINOR GREATER 0) OR
      (VERSION_NAME))
    set(VERSION_NAME ".${VERSION_MINOR}${VERSION_NAME}")
  endif()
  if ((VERSION_MAJOR GREATER 0) OR
      (VERSION_NAME))
    set(VERSION_NAME "${VERSION_MAJOR}${VERSION_NAME}")
  endif()
  set(${VERSION_RESULT} ${VERSION_NAME} PARENT_SCOPE)
  set(${BUILD_RESULT} ${VERSION_BUILD} PARENT_SCOPE)
endfunction(version_configure)

macro(version_make_file FILE_PATH)
  set(RELATIVE_PATH ${FILE_PATH})
  string(REPLACE "${PROJECT_BINARY_DIR}/" "" RELATIVE_PATH "${RELATIVE_PATH}")
  string(REGEX REPLACE "^src/" "" RELATIVE_PATH "${RELATIVE_PATH}")
  string(REGEX REPLACE "^srcs/" "" RELATIVE_PATH "${RELATIVE_PATH}")
  string(REGEX REPLACE "^source/" "" RELATIVE_PATH "${RELATIVE_PATH}")
  string(REGEX REPLACE "^sources/" "" RELATIVE_PATH "${RELATIVE_PATH}")
  string(REGEX REPLACE "^include/" "" RELATIVE_PATH "${RELATIVE_PATH}")
  string(REGEX REPLACE "^${PROJECT_NAME}/" "" RELATIVE_PATH "${RELATIVE_PATH}")
  string(TOUPPER "${RELATIVE_PATH}" RELATIVE_PATH)
  string(REGEX REPLACE "[^0-9a-zA-Z]" "_" RELATIVE_PATH "${RELATIVE_PATH}")
  string(TOUPPER "${PROJECT_NAME}" PROJECT_UPPER)
  configure_file(
    "${FILE_VERSION_CMAKE_PATH}/version.h.in"
    "${FILE_PATH}"
  )
  unset(PROJECT_UPPER)
  unset(RELATIVE_PATH)
endmacro(version_make_file)
