{%- if page.type == 'categories' -%}
  {%- assign taxonomies = site.categories -%}
{%- elsif page.type == 'tags' -%}
  {%- assign taxonomies = site.tags -%}
{%- else -%}
  {%- assign taxonomies = none -%}
{%- endif -%}

{%- assign max_count = 0 -%}
{%- for taxonomy in taxonomies -%}
  {%- assign posts = taxonomy[1] -%}
  {%- if posts.size > max_count -%}
    {%- assign max_count = posts.size -%}
  {%- endif -%}
{%- endfor -%}

<ul class="taxonomies">
  {%- for i in (1..max_count) reversed -%}
    {%- for taxonomy in taxonomies -%}
      {%- assign taxonomy_name = taxonomy[0] -%}
      {%- assign slugified_taxonomy_name = taxonomy_name | slugify -%}
      {%- assign posts = taxonomy[1] -%}
      {%- if posts.size == i -%}
        <li>
          {%- capture link -%}{{ page.permalink }}#{{ slugified_taxonomy_name }}{%- endcapture -%}
          <a class="taxonomy" href="{{ link | relative_url }}">
            <span>
              {%- if page.type == 'tags' -%}
                {{ slugified_taxonomy_name }}
              {%- else -%}
                {{ taxonomy_name }}
              {%- endif -%}
            </span>
            <span>{{ posts.size }}</span>
          </a>
        </li>
      {%- endif -%}
    {%- endfor -%}
  {%- endfor -%}
</ul>

{%- for i in (1..max_count) reversed -%}
  {%- for taxonomy in taxonomies -%}
    {%- assign taxonomy_name = taxonomy[0] -%}
    {%- assign slugified_taxonomy_name = taxonomy_name | slugify -%}
    {%- assign posts = taxonomy[1] -%}
    {%- if posts.size == i -%}
      <h2 id="{{ slugified_taxonomy_name }}">
        {%- if page.type == 'tags' -%}
          {{ slugified_taxonomy_name }}
        {%- else -%}
          {{ taxonomy_name }}
        {%- endif -%}
      </h2>
      <ul>
        {%- for post in posts -%}
          <li>
            <time class="archive-date" datetime="{{ page.date | date_to_xmlschema }}">{{ post.date | date: "%Y-%m-%d" }}</time> 
            &raquo; 
            <a href="{{ post.url | relative_url }}">{{ post.title | escape }}</a>
          </li>
        {%- endfor -%}
      </ul>
    {%- endif -%}
  {%- endfor -%}
{%- endfor -%}