<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
        version='1.0'
        xmlns:x='http://www.w3.org/1999/xhtml'
        xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'
        xmlns:dc='http://purl.org/dc/elements/1.1/'
>

<!--
     Personal project plus screen-scraping equals a serious relaxation
      of coding standards.
-->

<xsl:output encoding='utf-8' indent='yes'/>

<xsl:template match='/'>
 <rdf:RDF>
  <xsl:apply-templates select='.//x:table[@class="wikitable"]/x:tr[not(x:th)]'/>
  <xsl:apply-templates select='.//x:ol'/>
 </rdf:RDF>
</xsl:template>

<xsl:template match='x:tr'>
 <xsl:variable name='seasonName' select='../preceding-sibling::x:h3[1]/x:span[@class="mw-headline" and starts-with(., "Series")]'/>
 <xsl:variable name='season' select='substring($seasonName, 8)'/>
 <xsl:variable name='epnum' select='substring-before(x:td[1], ".")'/>
<xsl:text>
</xsl:text>
 <rdf:Description rdf:about='tag:kafsemo.org,2005:mtmp/spooks/{$season}x{$epnum}' dc:title='{normalize-space(x:td[2])}'>
 <xsl:if test='x:td[3] != "N/A"'>
  <dc:description><xsl:value-of select='normalize-space(x:td[3])'/></dc:description>
 </xsl:if>
 </rdf:Description>
</xsl:template>

<!-- Optimisable away? -->
<xsl:template match='x:span'>
  <xsl:apply-templates select='../following-sibling::x:ol'/>
</xsl:template>

<xsl:template match='x:ol/x:li'>
 <xsl:if test='x:b != "^"'>
 <xsl:variable name='seasonName' select='../preceding-sibling::x:h3[1]/x:span[@class="mw-headline" and starts-with(., "Series")]'/>
 <xsl:variable name='season' select='substring($seasonName, 8)'/>
 <xsl:variable name='epnum' select='number(position()) div 2'/>
 
 <rdf:Description rdf:about='tag:kafsemo.org,2005:mtmp/spooks/{$season}x{$epnum}' dc:title='{normalize-space(x:b)}'>
 <xsl:if test='x:i[not(starts-with(.,"Written"))]'>
  <dc:description><xsl:value-of select='normalize-space(x:i)'/></dc:description>
 </xsl:if>
 </rdf:Description>
 </xsl:if>
</xsl:template>

</xsl:stylesheet>
