{%- set section_stack = [] -%}
{%- set counters = namespace(level=0,indent=0) -%}
{%- for item_name, item_value in document_dictionary.items() -%}
{%- set count_flag = True -%}
{%- set counters.level = 0 -%}
{%- for item_level, current_level in zip(item_name[1], section_stack) -%}
{%- if not item_level == current_level -%}
{%- set count_flag = False -%}
{%- elif count_flag -%}
{%- set counters.level = counters.level + 1 -%}
{%- endif -%} 
{%- endfor -%}
{%- for section_name in section_stack[counters.level: ] | reverse -%}
{%- set counters.indent = counters.indent - 1 -%}
{{- '    ' * counters.indent }}</{{ section_name[0] }}>
{% if loop.last %}
{% endif -%}
{% do section_stack.pop() -%}
{%- endfor -%}
{%- for comment in item_value[:-1] -%}
{% if loop.first %}
{% endif -%}
{{ '    ' * counters.indent }}{{ comment }}
{% endfor -%}
{%- for section_name in item_name[1][counters.level: ] -%}
{{ '    ' * counters.indent }}<{{ section_name | join(' ') }}>
{% set counters.indent = counters.indent + 1 -%}
{%- do section_stack.append(section_name) -%}
{%- endfor -%}
{{ '    ' * counters.indent }}{{ item_name[2:] | join(' ') }}{% if not item_value[-1] == '' %} {{ item_value[-1] }}{% endif %}
{% endfor -%}
{%- for section_name in section_stack | reverse -%}
{%- set counters.indent = counters.indent - 1 -%}
{{ '    ' * counters.indent }}</{{ section_name[0] }}>
{%- if not loop.last %}
{% endif -%}
{%- endfor %}

