<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:sch="http://purl.oclc.org/dsdl/schematron" xmlns:rng="http://relaxng.org/ns/structure/1.0" version="1.0">
<xsl:output method="xml" omit-xml-declaration="no" indent="yes" standalone="yes"/>
<xsl:template match="/rng:grammar | /rng:element">
<xsl:call-template name="gatherSchema">
<xsl:with-param name="schemas" select="."/>
<xsl:with-param name="includes" select="document(/rng:grammar/rng:include/@href | //rng:externalRef/@href)"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="gatherSchema">
<xsl:param name="schemas"/>
<xsl:param name="includes"/>
<xsl:choose>
<xsl:when test="count($schemas) < count($schemas | $includes)">
<xsl:call-template name="gatherSchema">
<xsl:with-param name="schemas" select="$schemas | $includes"/>
<xsl:with-param name="includes" select="document($includes/rng:grammar/rng:include/@href | $includes//rng:externalRef/@href)"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="output">
<xsl:with-param name="schemas" select="$schemas"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="output">
<xsl:param name="schemas"/>
<sch:schema>
<xsl:copy-of select="$schemas//sch:title[1]"/>
<xsl:for-each select="$schemas//sch:ns">
<xsl:if test="generate-id(.) = generate-id($schemas//sch:ns[@prefix = current()/@prefix][1])">
<xsl:copy-of select="."/>
</xsl:if>
</xsl:for-each>
<xsl:copy-of select="$schemas//sch:key[not(ancestor::sch:rule)]"/>
<xsl:copy-of select="$schemas//sch:phase"/>
<xsl:copy-of select="$schemas//sch:pattern"/>
<sch:diagnostics>
<xsl:copy-of select="$schemas//sch:diagnostics/*"/>
</sch:diagnostics>
</sch:schema>
</xsl:template>
</xsl:transform>