<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
               xmlns:a="http://www.w3.org/1999/XSL/TransformAlias"
               xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:f="http://fxsl.sf.net/"
               exclude-result-prefixes="a"
               version="2.0">

  <xsl:output indent="yes"/>

  <xsl:namespace-alias stylesheet-prefix="a" result-prefix="xsl"/>

  <xsl:template match="/">
    <whens>
      <a:choose xml:id="basic">
        <xsl:apply-templates select="types/type[xs:boolean(@basic)]">
          <xsl:with-param name="sa" select="false()"/>
        </xsl:apply-templates>
        <a:otherwise>
          <f:untypedAtomic>
            <a:copy-of select="$arg"/>
          </f:untypedAtomic>
        </a:otherwise>
      </a:choose>
      <a:choose xml:id="sa">
        <xsl:apply-templates select="types/type[@name = ('string', 'decimal')]" mode="nested"/>
        <xsl:apply-templates select="types/type[not(@name = ('string', 'decimal'))]"/>
        <a:otherwise>
          <atomic>
            <a:copy-of select="$arg"/>
          </atomic>
        </a:otherwise>
      </a:choose>
    </whens>
  </xsl:template>

  <xsl:template match="type">
    <xsl:param name="sa" select="true()" as="xs:boolean"/>
    <xsl:apply-templates select="type[xs:boolean(@basic) or $sa]">
      <xsl:with-param name="sa" select="$sa"/>
    </xsl:apply-templates>
    <a:when test="$arg instance of xs:{@name}">
      <xsl:choose>
        <xsl:when test="$sa">
          <atomic a:type="xs:{@name}">
            <a:copy-of select="$arg" validation="preserve"/>
          </atomic>
        </xsl:when>
        <xsl:otherwise>
          <xsl:element name="f:{@name}">
            <a:copy-of select="$arg"/>
          </xsl:element>
        </xsl:otherwise>
      </xsl:choose>
    </a:when>
  </xsl:template>

  <xsl:template match="type" mode="nested">
    <a:when test="$arg instance of xs:{@name}">
      <a:choose>
        <xsl:apply-templates select="type"/>
        <a:otherwise>
          <atomic a:type="xs:{@name}">
            <a:copy-of select="$arg" validation="preserve"/>
          </atomic>
        </a:otherwise>
      </a:choose>
    </a:when>
  </xsl:template>

</xsl:transform>
