string (REPLACE " " ";" FILES ${FILES}) # make back into a list

function (indent)
  foreach (temp RANGE ${level})
    file (APPEND ${contents_file} "  ")
  endforeach ()
endfunction ()

function (end_entry)
  file (APPEND ${contents_file} "\n")
  set(first 0 PARENT_SCOPE)
  math (EXPR level "${level} - 1")
  indent ()
  file (APPEND ${contents_file} "]\n")
  math (EXPR level "${level} - 2")
  indent ()
  file (APPEND ${contents_file} "}")
  string (FIND "${dirs}" "${cwd}" pos)
  set (level ${level} PARENT_SCOPE)
endfunction ()

file (WRITE ${contents_file} "[")
set (cwd)
set (level 0)
set (first 1)
list (SORT FILES)
foreach (file IN LISTS FILES)
  string (REGEX MATCHALL "[^/]*/" dirs "${file}")
  string (REPLACE "/" "" dirs "${dirs}")
  string (REGEX MATCH "[^/]*$" name "${file}")
  string (FIND "${dirs}" "${cwd}" pos)
  list (LENGTH cwd cwd_count)
  if (${pos} EQUAL 0)
    # same root
    while (${cwd_count} GREATER 0)
      list (REMOVE_AT dirs 0)
      math (EXPR cwd_count "${cwd_count} - 1")
    endwhile ()
  else ()
    # reduce cwd until matched
    while ((NOT ${pos} EQUAL 0) AND ${cwd_count} GREATER 0)
      math (EXPR cwd_count "${cwd_count} - 1")
      list (REMOVE_AT cwd ${cwd_count})
      end_entry ()
    endwhile ()
    # back to same root
    while (${cwd_count} GREATER 0)
      list (REMOVE_AT dirs 0)
      math (EXPR cwd_count "${cwd_count} - 1")
    endwhile ()
  endif ()
  list (LENGTH cwd cwd_count)
  list (LENGTH dirs path_count)
  while (${path_count} GREATER 0)
    list (GET dirs 0 dir)
    list (APPEND cwd "${dir}")
    list (REMOVE_AT dirs 0)
    if (${first})
      file (APPEND ${contents_file} "\n")
      set (first 0)
    else ()
      file (APPEND ${contents_file} ",\n")
    endif ()
    indent ()
    file (APPEND ${contents_file} "{\n")
    math (EXPR level "${level} + 1")
    indent ()
    file (APPEND ${contents_file} "\"type\": \"directory\",\n")
    indent ()
    file (APPEND ${contents_file} "\"name\":  \"${dir}\",\n")
    indent ()
    file (APPEND ${contents_file} "\"entries\": [")
    set (first 1)
    math (EXPR level "${level} + 2")
    math (EXPR path_count "${path_count} - 1")
  endwhile ()
  file (COPY ${file} DESTINATION ${DEST}/web/samples/${cwd})
  if (${first})
    file (APPEND ${contents_file} "\n")
    set (first 0)
  else ()
    file (APPEND ${contents_file} ",\n")
  endif ()
  indent ()
  file (APPEND ${contents_file} "{\n")
  math (EXPR level "${level} + 1")
  indent ()
  file (APPEND ${contents_file} "\"type\": \"file\",\n")
  indent ()
  file (APPEND ${contents_file} "\"name\": \"${name}\"\n")
  math (EXPR level "${level} - 1")
  indent ()
  file (APPEND ${contents_file} "}")
  set (first 0)
endforeach ()
if (${level} GREATER 1)
  end_entry ()
endif ()
file (APPEND ${contents_file} "\n]\n")
