{# MACRO #}
{#- generic range #}
{% macro range(msb, lsb) %}
    {% if msb == lsb %}
{{ msb }}
    {%- else %}
{{ msb }}:{{ lsb }}
    {%- endif %}
{%- endmacro %}

{#- bit field mode #}
{% macro mode(bf) %}
{{ bf.access }}
{%- endmacro %}

{#- value in hex format #}
{% macro literal(reset, width) %}
{{ "0x%0{w}x".format(w=width // 4) % reset }}
{%- endmacro %}

{#- TEMPLATE NAMESPACE #}
{% set tmp = namespace() %}

{#- TEMPLATE #}
# {{ title }}

Created with [Corsair](https://github.com/esynr3z/corsair) v{{ corsair_ver }}.

{% if print_conventions %}
## Conventions

| Access mode | Description               |
| :---------- | :------------------------ |
| rw          | Read and Write            |
| rw1c        | Read and Write 1 to Clear |
| rw1s        | Read and Write 1 to Set   |
| ro          | Read Only                 |
| roc         | Read Only to Clear        |
| roll        | Read Only / Latch Low     |
| rolh        | Read Only / Latch High    |
| wo          | Write only                |
| wosc        | Write Only / Self Clear   |
{% endif %}

## Register map summary

Base address: {{ "0x%08x" % config['base_address'] }}

| Name                     | Address    | Description |
| :---                     | :---       | :---        |
{% for reg in rmap %}
{{ "| %-24s | %-10s | %s" % ("[%s](#%s)" % (reg.name, reg.name.lower()), literal(reg.address, config['address_width']), reg.description) }} |
{% endfor %}
{% for reg in rmap %}

## {{ reg.name }}

{{ reg.description }}

Address offset: {{ literal(reg.address, config['address_width']) }}

Reset value: {{ literal(reg.reset, config['data_width']) }}

{% if print_images %}
![{{ reg.name.lower()}}]({{ image_dir }}/{{ reg.name.lower()}}.svg)
{% endif %}

| Name             | Bits   | Mode            | Reset      | Description |
| :---             | :---   | :---            | :---       | :---        |
    {% set tmp.reserved_msb = config['data_width'] - 1 %}
    {% for bf in reg.bitfields[::-1] %}
        {% if tmp.reserved_msb > bf.msb %}
            {% set tmp.reserved_lsb = bf.msb + 1 %}
            {% set tmp.reserved_width = tmp.reserved_msb - tmp.reserved_lsb + 1 %}
{{ "| %-16s | %-6s | %-15s | %-10s | %s |" % ('-', range(tmp.reserved_msb, tmp.reserved_lsb), '-', literal(0, tmp.reserved_width), 'Reserved') }}
        {% endif %}
{{ "| %-16s | %-6s | %-15s | %-10s | %s |" % (bf.name, range(bf.msb, bf.lsb), mode(bf), literal(bf.reset, bf.width), bf.description) }}
        {% set tmp.reserved_msb = bf.lsb - 1 %}
    {% endfor %}
    {% for bf in reg %}
        {% if bf.enums %}

Enumerated values for {{ reg.name }}.{{ bf.name }}.

| Name             | Value   | Description |
| :---             | :---    | :---        |
            {% for enum in bf %}
{{ "| %-16s | %-6s | %s |" % (enum.name, literal(enum.value, bf.width), enum.description) }}
            {% endfor %}
        {% endif %}
    {% endfor %}

Back to [Register map](#register-map-summary).
{% endfor %}