<?xml version="1.0" encoding="UTF-8"?>
<?arboreal menu-item-name="Ficus" interactive-params="image-series"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
		xmlns:xlink="http://www.w3.org/1999/xlink">

  <xsl:output indent="no" method="xml" doctype-system="../dtd/archimedes.dtd"/>
  <xsl:param name="image-series">01</xsl:param>

  <!-- get the locator -->
  <xsl:variable name="locator">
    <xsl:value-of select="substring-before(//info/locator/text(), '.')"/>
  </xsl:variable>

  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="archimedes">
    <xsl:copy>
      <xsl:comment>
        <xsl:text> Links on PB and FIGURE were inserted by Ficus 2.1. </xsl:text>
      </xsl:comment>
      <xsl:apply-templates select="@*|node()|text()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="pb">
    <xsl:variable name="page-number">
      <xsl:number value="count(preceding::pb) + 1" format="001"
		  grouping-size="0"/>
    </xsl:variable>
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:attribute name="id">
	<xsl:value-of select="concat('id.', $locator, '.', $image-series, '.', $page-number)"/>
      </xsl:attribute>
      <xsl:attribute name="xlink:href">
	<xsl:value-of select="concat($locator, '/', $image-series, '/', $page-number, '.jpg')"/>
      </xsl:attribute>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="figure">
    <xsl:variable name="preceding-page-count">
      <xsl:number value="count(preceding::pb)" format="001" grouping-size="0"/>
    </xsl:variable>
    <xsl:variable name="last-figure-id">
      <xsl:value-of select="preceding::figure[1]/@id"/>
    </xsl:variable>
    <xsl:variable name="last-figure-page">
      <xsl:value-of select="substring($last-figure-id, 11, 3)"/>
    </xsl:variable>
    <xsl:variable name="last-figure-counter">
      <xsl:value-of select="substring($last-figure-id, 15, 1)"/>
    </xsl:variable>
    <xsl:variable name="figure-id-format">
      <xsl:choose>
	<xsl:when test="$last-figure-page = $preceding-page-count">
	  <xsl:value-of select="concat($locator, '.', $image-series, '.', $preceding-page-count, '.', (number($last-figure-counter) + 1))"/>
	</xsl:when>
 	<xsl:otherwise>
	  <xsl:value-of select="concat($locator, '.', $image-series, '.', $preceding-page-count, '.1')"/>
	</xsl:otherwise>
     </xsl:choose>
    </xsl:variable>
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:attribute name="id">
	<xsl:value-of select="concat($figure-id-format, '.jpg')"/>
      </xsl:attribute>
      <xsl:attribute name="xlink:href">
	<xsl:value-of select="concat(translate($figure-id-format, '.', '/'), '.jpg')"/>
      </xsl:attribute>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
