<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes"/>

<xsl:param name="tag">Fandom:Lord_Peter_Wimsey</xsl:param>

<xsl:template match="posts">

  <p class="tag"><xsl:value-of select="translate(substring-after($tag,':'),'_',' ')" /></p>
  <xsl:text>
  </xsl:text>

    <xsl:for-each select="post[contains(@tag,$tag)]">
      <div class="story">
      <xsl:text>
      </xsl:text>
      <div class="title">
        <a>
          <xsl:attribute name="href">
            <xsl:value-of select="@href" />
          </xsl:attribute>
          <xsl:value-of select="@description" />
        </a>
      </div>
      <xsl:text>
      </xsl:text>
      <div class="summary"><xsl:value-of select="@extended" /></div>
      <div class="fandomlist">
        <xsl:text>Fandom(s):</xsl:text> 
        <xsl:call-template name="parsetags">
          <xsl:with-param name="text" select="normalize-space(@tag)" />
          <xsl:with-param name="category" select="'Fandom'" />
        </xsl:call-template>
      </div>
      <xsl:text>
      </xsl:text>
      <div class="characterlist">
        <xsl:text>Character(s):</xsl:text>
        <xsl:call-template name="parsetags">
          <xsl:with-param name="text" select="normalize-space(@tag)" />
          <xsl:with-param name="category" select="'Character'" />
        </xsl:call-template>
      </div>
      <xsl:text>
      </xsl:text>
      <div class="genrelist">
        <xsl:text>Genre(s):</xsl:text>
        <xsl:call-template name="parsetags">
          <xsl:with-param name="text" select="normalize-space(@tag)" />
          <xsl:with-param name="category" select="'Genre'" />
        </xsl:call-template>
      </div>
      <xsl:text>
      </xsl:text>
      </div>
    </xsl:for-each>
  </xsl:template>

  <xsl:template name="parsetags">
    <xsl:param name="text" />
    <xsl:param name ="category"/>

    <xsl:choose>
      <xsl:when test="contains($text, ' ') and contains($text, $category)" >
        <xsl:if test="contains(substring-before($text, ' '), $category)">
          <xsl:value-of select="translate(substring-after(substring-before($text,' '), ':'), '_', ' ')" />
          <xsl:if test="contains(substring-after($text, ' '), $category)">
            <xsl:text>, </xsl:text>
          </xsl:if>
        </xsl:if>

        <xsl:call-template name="parsetags">
          <xsl:with-param name="text" select="normalize-space(substring-after($text, ' ')) "/>
          <xsl:with-param name="category" select="$category" />
        </xsl:call-template>
      </xsl:when>
      <xsl:when test="contains($text, $category)" >
        <xsl:value-of select="translate(substring-after($text, ':'), '_', ' ')" />
      </xsl:when>
    </xsl:choose>
      
  </xsl:template>
</xsl:stylesheet>
