<?xml version='1.0' encoding='UTF-8' ?>
<!-- Copyright 2004 Rowan Rodrik van der Molen
   - Distributed under the terms of the GNU General Public Licence v2
   - Sort an XBEL file -->

<xsl:stylesheet version='1.0' extension-element-prefixes='exsl'
  xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
  xmlns:exsl='http://exslt.org/common'>

  <xsl:output method='xml' media-type="text/xml" encoding="UTF-8" indent="yes"
    doctype-system='http://www.python.org/topics/xml/dtds/xbel-1.0.dtd'
    doctype-public='+//IDN python.org//DTD XML Bookmark Exchange Language 1.0//EN//XML' />

  <xsl:param name='sort_folders_first'>yes</xsl:param>


  <!-- Process the root element -->
  <xsl:template match="/">
    <xsl:apply-templates />
  </xsl:template>


  <xsl:template match="xbel">
    <xbel>
      <xsl:copy-of select="@*|title|desc" />

      <xsl:call-template name="sub" />
    </xbel>
  </xsl:template>


  <xsl:template match="folder">
    <folder>
      <xsl:copy-of select="@*|title|info|desc" />

      <xsl:call-template name="sub" />
    </folder>
  </xsl:template>


  <xsl:template match="bookmark|alias">
    <xsl:copy-of select="." />
  </xsl:template>


  <xsl:template name="sub">
    <xsl:choose>
      <xsl:when test="$sort_folders_first = 'yes'">
        <xsl:apply-templates select="folder|alias[name(id(@ref)) = 'folder']">
          <xsl:sort select="title|id(@ref)/title" />
        </xsl:apply-templates>

        <xsl:apply-templates select="bookmark|alias[name(id(@ref)) = 'bookmark']">
          <xsl:sort select="(title|id(@ref)/title)[1]" />
        </xsl:apply-templates>
      </xsl:when>

      <xsl:otherwise>
        <xsl:apply-templates select="folder|bookmark|alias">
          <xsl:sort select="title|id(@ref)/title" />
        </xsl:apply-templates>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>
