<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="text" />

<xsl:key name="sort" match="country" use="number"/>
<xsl:variable name="list" select="countries/country[generate-id(.) = generate-id(key('sort', number))]"/>

<xsl:template match="/">
  <xsl:call-template name="process-list">
    <xsl:with-param name="rank" select="1" />
    <xsl:with-param name="position" select="1" />
    <xsl:with-param name="counter" select="0" />
  </xsl:call-template>
</xsl:template>

<xsl:template name="process-list">
  <xsl:param name="rank" />
  <xsl:param name="position" />
  <xsl:param name="counter" />
  <xsl:choose>
    <!-- process new number -->
    <xsl:when 
   test="$counter = count($list[number = 
   $list[$rank]/number]) - 1">
      <xsl:apply-templates select="$list[$rank]">
        <xsl:with-param name="rank" select="$rank" />
      </xsl:apply-templates>
      <xsl:call-template name="process-list">
        <xsl:with-param name="rank" select="$rank" />
        <xsl:with-param name="position" select="$position + 1" />
        <xsl:with-param name="counter" select="1" />
      </xsl:call-template>
    </xsl:when>
    <!-- process the rest of the current number -->
    <xsl:otherwise>
      <xsl:apply-templates select="countries/country[number =
$list[$rank]/number][$counter + 1]">
        <xsl:with-param name="rank" select="$rank" />
      </xsl:apply-templates>
      <xsl:choose>
        <!-- goto next number -->
        <xsl:when test="$counter = count(countries/country[number =
$list[$rank]/number])">
          <!-- test if there are more numbers -->
          <xsl:if test="$rank &lt; count($list)">
            <xsl:call-template name="process-list">
              <xsl:with-param name="rank" select="$rank + 1" />
              <xsl:with-param name="position" select="$position" />
              <xsl:with-param name="counter" select="0" />
            </xsl:call-template>
          </xsl:if>
        </xsl:when>
        <!-- goto next in this number -->
        <xsl:otherwise>
          <xsl:call-template name="process-list">
            <xsl:with-param name="rank" select="$rank" />
            <xsl:with-param name="position" select="$position + 1" />
            <xsl:with-param name="counter" select="$counter + 1" />
          </xsl:call-template>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<xsl:template match="country">
  <xsl:param name="rank" />
  <xsl:value-of select="$rank" />
  <xsl:text> - </xsl:text>
  <xsl:value-of select="number" />
  <xsl:text> - </xsl:text>
  <xsl:value-of select="name" />
  <xsl:text>; </xsl:text>

</xsl:template>

</xsl:stylesheet>