<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
		xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
		xmlns:sp="http://www.w3.org/2005/sparql-results#"
        exclude-result-prefixes="sp">
  <xsl:output
    method="xml"
    omit-xml-declaration="yes"/>

    
  <xsl:template match="/">
    <ul>
      <!-- Step through row keys -->
      <xsl:for-each select="/sp:sparql/sp:results/sp:result/sp:binding[1]/*">
	<xsl:variable name="current" select="."/>
	<xsl:variable name="position" select="position()"/>
	<!-- Make sure we haven't seen it before... -->
	<xsl:if test="count(/sp:sparql/sp:results/sp:result[position()&lt;$position]/sp:binding[1][* = $current]) = 0">
	  <xsl:apply-templates select="." mode="listing">
	    <xsl:with-param name="row" select="."/>
	  </xsl:apply-templates>
	</xsl:if>
      </xsl:for-each>
    </ul>
  </xsl:template>
  
  <!-- List each key -->
  <xsl:template mode="listing" match="*">
    <li><xsl:apply-templates select="." mode="display"/>
      <!-- List properties -->
      <ul>
	<xsl:apply-templates select="ancestor::sp:sparql/sp:head/sp:variable[position()>1]/@name"
			     mode="properties">
	  <xsl:with-param name="row" select="$row"/>
	</xsl:apply-templates>
      </ul>
    </li>
    <xsl:text>
</xsl:text>
  </xsl:template>
  
  <!-- List out the properties per row -->
  <xsl:template mode="properties" match="@*">
    <xsl:variable name="attr_name"><xsl:value-of select="."/></xsl:variable>
    <xsl:if test="count(ancestor::sp:sparql/sp:results/sp:result[sp:binding[1]/*=$row]/sp:binding[@name=$attr_name]/*/text()) > 0">
      <li><xsl:value-of select="."/><xsl:text>: </xsl:text>
      	<ul>
	  <xsl:apply-templates select="ancestor::sp:sparql/sp:results/sp:result[sp:binding[1]/*=$row]/sp:binding[@name=$attr_name]/*[text()]"
			       mode="values"/>
	</ul>
      </li>
    </xsl:if>
  </xsl:template>

  <xsl:template mode="values" match="*">
    <li>
      <xsl:apply-templates mode="display" select="."/>
    </li>
  </xsl:template>

  <!-- Various node display templates -->
  <xsl:template match="sp:uri" mode="display">
    <a>
      <xsl:attribute name="href"><xsl:value-of select="./text()"/></xsl:attribute>
      <xsl:value-of select="./text()"/>
    </a>
  </xsl:template>

  <xsl:template match="sp:literal" mode="display">
    <xsl:value-of select="./text()"/>
  </xsl:template>

  <xsl:template match="sp:bnode" mode="display">
    <xsl:text>_:</xsl:text><xsl:value-of select="./text()"/>
  </xsl:template>

  <xsl:template match="sp:unbound" mode="display">
    <xsl:text>Unknown</xsl:text>
  </xsl:template>
  
</xsl:stylesheet>
