##
##
function(cmake_script_parse content)
  set(args ${ARGN})
  list_extract_flag(args --comment-header)
  ans(return_comment_header)
  list_extract_flag(args --ignore-newlines)
  ans(ignore_newlines)
  list_extract_flag(args --first-function-header)
  ans(return_first_function_header)
  set(res)  
  set(non_empty_script_found false)

  while(true)
    set(empty false)
    string_take_whitespace(content)
    string_take_regex(content "[^\n]+")
    ans(line)
    string_take_regex(content "\n")
    list(LENGTH content len)
   
    if(NOT len)
      break()
    endif()
    map_new()
    ans(current)
    map_set(${current} line "${line}")
    if("${line}" MATCHES "^(#+)(.*)")
      map_set(${current} type "comment")
      map_set(${current} comment "${CMAKE_MATCH_2}")
      map_set(${current} comment_depth "${CMAKE_MATCH_1}")
    else()
      map_set(${current} type "script")
      string_take_whitespace(line)
      if("${line}_" STREQUAL "_" )
        map_set(${current} empty true)
        set(empty true)
      else()
        map_set(${current} empty false)
        set(non_empty_script_found true)
        set(empty false)

        if(return_comment_header)
          return_ref(res)
        endif()
      endif()
      map_set(${current} script "${line}")
      set(CMAKE_MATCH_3)
      if("${line}" MATCHES "^([^\\(]+)(\\(.*\\))(.*)")
        map_set(${current} function_name "${CMAKE_MATCH_1}")   
        map_set(${current} function_call "${CMAKE_MATCH_2}")
        set(function_name "${CMAKE_MATCH_1}")
        set(function_call "${CMAKE_MATCH_2}")
        string(REGEX REPLACE "\\((.*)\\)" "\\1" function_call "${function_call}")
          while(true)
            string_take_whitespace(function_call)
            if("${function_call}_" STREQUAL "_")
              break()
            endif()
            ans(arg)
            if("${arg}_" STREQUAL "_")
              string_take_regex(function_call "[^ ]+")
              ans(arg)
            endif()
            string_encode_semicolon("${arg}")
            ans(arg)
            map_append(${current} function_args "${arg}")
         
          endwhile()
        if("${CMAKE_MATCH_3}" MATCHES "^[ ]*#(.*)[ ]*$")
          map_set(${current} comment "${CMAKE_MATCH_1}")
        endif()
        if(return_first_function_header AND ( "${function_name}" STREQUAL "function" OR "${function_name}" STREQUAL "macro"))
          return(${current})
        endif()
      endif()
    endif()
    if(NOT (empty AND ignore_newlines))
      list(APPEND res ${current})
    endif()
  endwhile()
  return_ref(res)
endfunction()

