set(__ac_config_content "")

function(ac_subst name)
    if(ARGN)
        set(__ac_config_content "#define ${name} \"${ARGN}\"\n\n" PARENT_SCOPE)
    else()
        set(__ac_config_content "#define ${name} \"${${name}}\"\n\n" PARENT_SCOPE)
    endif()
endfunction()

include(CheckIncludeFile)
function(ac_check_headers header)
    set(varname "HAVE_${header}")
    string(REGEX REPLACE "[^A-Za-z0-9]" "_" varname "${varname}")
    string(TOUPPER "${varname}" varname)
    check_include_file("${header}" "${varname}")
    if(${varname})
        set(__ac_config_content "${__ac_config_content}#define ${varname} 1\n\n" PARENT_SCOPE)
    endif()
endfunction()

include(CheckTypeSize)
function(ac_check_sizeof type)
    set(varname "SIZEOF_${type}")
    string(REPLACE "*" "P" varname "${varname}")
    string(REPLACE "[^A-Za-z0-9]" "_" varname "${varname}")
    string(REPLACE " " "_" varname "${varname}")
    string(TOUPPER "${varname}" varname)
    check_type_size("${type}" "${varname}")
    if(${varname})
        set(__ac_config_content "${__ac_config_content}#define ${varname} ${${varname}}\n\n" PARENT_SCOPE)
    endif()
endfunction()

function(ac_config_headers name)
    if (__ac_config_content STREQUAL "")
        message(FATAL_ERROR "ac_config_headers called, but __ac_config_content is empty")
    endif()

    if (EXISTS "${CMAKE_CURRENT_BINARY_DIR}/${name}")
        file(READ "${CMAKE_CURRENT_BINARY_DIR}/${name}" config_h_content)
    endif()
    if (NOT "${config_h_content}" STREQUAL "${__ac_config_content}")
        message(STATUS "Writing ${name}")
        file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${name}" "${__ac_config_content}")
    endif()
endfunction()
