# - Try to find Bison
# Once done this will define
#
#  BISON_FOUND - system has Bison
#  BISON_EXECUTABLE - path of the bison executable
#  BISON_VERSION - the version string, like "2.5.31"
#

MACRO(FIND_BISON)
	FIND_PROGRAM(BISON_EXECUTABLE NAMES bison)

	IF(BISON_EXECUTABLE)
		SET(BISON_FOUND TRUE)

		EXECUTE_PROCESS(COMMAND ${BISON_EXECUTABLE} --version
			OUTPUT_VARIABLE _BISON_VERSION
		)
		string (REGEX MATCH "[0-9]+\\.[0-9]+\\.[0-9]+" BISON_VERSION "${_bison_VERSION}")
	ENDIF(BISON_EXECUTABLE)

	IF(BISON_FOUND)
	  IF(NOT Bison_FIND_QUIETLY)
		MESSAGE(STATUS "Found Bison: ${BISON_EXECUTABLE}")
	  ENDIF(NOT Bison_FIND_QUIETLY)
	ELSE(BISON_FOUND)
	  IF(Bison_FIND_REQUIRED)
		MESSAGE(FATAL_ERROR "Could not find Bison")
	  ENDIF(Bison_FIND_REQUIRED)
	ENDIF(BISON_FOUND)
ENDMACRO(FIND_BISON)

MACRO(BISON_GENERATOR _PREFIX _Y_INPUT _H_OUTPUT _CPP_OUTPUT)
	IF(BISON_EXECUTABLE)
		GET_FILENAME_COMPONENT(_Y_DIR ${_Y_INPUT} PATH)
		ADD_CUSTOM_COMMAND(
			OUTPUT  ${_CPP_OUTPUT}
			OUTPUT  ${_H_OUTPUT}
			DEPENDS ${_Y_INPUT}
			COMMAND ${BISON_EXECUTABLE}
			ARGS
				-p ${_PREFIX} -o"${_CPP_OUTPUT}"
				--defines="${_H_OUTPUT}" ${_Y_INPUT}
			WORKING_DIRECTORY ${_Y_DIR}
		)
		SET_SOURCE_FILES_PROPERTIES(
			${_CPP_OUTPUT} ${_H_OUTPUT}
			GENERATED
		)
	ELSE(BISON_EXECUTABLE)
		MESSAGE(SEND_ERROR "Can't find bison program, and it's required")
	ENDIF(BISON_EXECUTABLE)
ENDMACRO(BISON_GENERATOR)
