<?xml version="1.0" encoding="utf-8"?>

<!--
*
*  Extract scoring information from Booker Regionals 2005 results pages.
*
*-->

<xsl:stylesheet
	version="2.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:bmp="tag:edavies.nildram.co.uk,2006-05-23:bumps"
	xmlns:xhtml="http://www.w3.org/1999/xhtml"
	exclude-result-prefixes="xhtml">
	
	<xsl:output method="xml" encoding="utf-8" indent="yes"/>
	
<!--===============================================================================
*
*	Get the name of the competition from the first day's data.
*
*-->
<xsl:template name="extract-comp-name">
	<xsl:value-of select="normalize-space(document(//bmp:day[1]/@href)//xhtml:table[1]//xhtml:b[1]/node())"/>
</xsl:template>


<!--===============================================================================
*
*	Processing for a single day.
*
*-->
<xsl:template match="bmp:day">

	<!-- Set up general context information for the day. -->
	<xsl:variable name="day-file" select="document(@href)"/>
	<xsl:variable name="results-table" select="$day-file//xhtml:table[@cellpadding]"/>
	<xsl:variable name="title-text" select="string($results-table/xhtml:tr[1]//xhtml:b)"/>
	<xsl:variable name="day-no" select="number(substring-after(substring-before($title-text, ','), ' '))"/>
	<xsl:variable name="date" select="normalize-space(substring-before(substring-after($title-text, ','), ','))"/>
	<xsl:variable name="score-lines" select="$results-table/xhtml:tr[not(@bgcolor='#94ABF6')][xhtml:td[@colspan=1]]"/>
	
	<!-- Extract pilot names and glider numbers if it's the first day. -->
	<xsl:if test="$day-no=1">
		<xsl:for-each select="$score-lines">
			<xsl:sort select="string(xhtml:td[2]//xhtml:font)" data-type="text"/>
			<bmp:glider
				ident="{string(xhtml:td[2]//xhtml:font)}"
				pilot="{string(xhtml:td[3]//xhtml:b)}"/>
		</xsl:for-each>
	</xsl:if>
	
	<!-- Copy the bmp:day element adding the day-no and date attributes. -->
	<xsl:copy>
		<xsl:copy-of select="@*"/>
		<xsl:attribute name="day-no" select="$day-no"/>
		<xsl:attribute name="date" select="$date"/>
		<xsl:copy-of select="*"/>
	</xsl:copy>
	
	<!-- Extract the glider score information for each glider for the day. -->
	<xsl:for-each select="$score-lines">
		<bmp:glider-day
			day-no="{$day-no}"
			ident="{string(xhtml:td[2]//xhtml:font)}"
			score="{string(xhtml:td[12]//xhtml:b)}"/>
	</xsl:for-each>
	
</xsl:template>


<!--===============================================================================
*
*	Top level processing.
*
*-->
<xsl:template match="bmp:results">

	<xsl:copy>
		<xsl:copy-of select="@*"/>
		
		<xsl:attribute name="comp">
			<xsl:call-template name="extract-comp-name"/>
		</xsl:attribute>
		
		<xsl:copy-of select="*[not(self::bmp:day)]"/>

		<xsl:for-each select="bmp:day">
			<xsl:apply-templates select="."/>
		</xsl:for-each>
	
	</xsl:copy>
	
	<xsl:text>
</xsl:text>

</xsl:template>
	
</xsl:stylesheet>
