<?xml version='1.0'?>
<!DOCTYPE doc SYSTEM "../../../../lib/xml/xsl.dtd" >
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" exclude-result-prefixes="x" xmlns:x="http://www.w3.org/1999/xhtml">
 
 <!-- Merge wrapped latin and prepped english to produce two-column
      bilingual for a single Summa Question -->
 <xsl:param name="lf">xyzzy</xsl:param>
 <xsl:variable name="latin" select="document($lf,/)/*"/>
 <xsl:key name="lq" match="x:div[@class='q']" use="@id"/>
 <xsl:variable name="di" select="/x:div/@id"/>
 <xsl:variable name="qi" select="concat('q',substring-after($di,'_Q'))"/>
 <xsl:variable name="la" select="key('lq',$qi,$latin)"/>

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 
 <xsl:template match="/x:div/x:div[not(@n)]">
  <!-- Wrap a prooemium -->
  <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
   <xsl:apply-templates select="$la/x:div[@class='p']/x:p"/>
  </xsl:copy>
 </xsl:template>
 
 <xsl:template match="/x:div/x:div[@n]">
  <!-- Wraps a single article within a question -->
  <xsl:variable name="n" select="count(preceding-sibling::x:div[@n])+1"/>
  <xsl:variable name="ld" select="$la/x:div[@class='a'][position()=$n]"/>
  <xsl:message><xsl:value-of select="@n"/>,<xsl:value-of select="$n"/>,<xsl:value-of select="@title"/>,<xsl:value-of select="count(x:div)"/>,<xsl:value-of select="$ld/x:h3"/>,<xsl:value-of select="count($ld/x:p)"/></xsl:message>
  <xsl:choose>
   <xsl:when test="count(x:div)=count($ld/x:p)">
    <xsl:copy>
     <xsl:apply-templates select="@*|x:h4"/>
     <xsl:for-each select="x:div">
      <xsl:variable name="i" select="position()"/>
      <xsl:copy>
         <xsl:apply-templates select="@*|x:div[1]"/>
         <xsl:for-each select="x:div[2]">
          <xsl:copy>
           <xsl:apply-templates select="@*"/>
           <xsl:apply-templates select="$ld/x:p[position()=$i]"/>
          </xsl:copy>
         </xsl:for-each>
        </xsl:copy>
     </xsl:for-each>
    </xsl:copy>
   </xsl:when>
   <xsl:otherwise>
    <xsl:message>Can't merge article <xsl:value-of select="@n"/>, <xsl:value-of select="count(x:div)"/>!=<xsl:value-of select="count($ld/x:p)"/></xsl:message>
   </xsl:otherwise>
  </xsl:choose>  
 </xsl:template>
</xsl:stylesheet>
