This question extends a [previous question](https://stackoverflow.com/questions/30605892/how-can-i-use-xslt-to-permutate-a-node-hierarchy).

In the previous question I asked how to permutate the node hierarchy in a tree of fixed depth. For example for every leaf with the path /x/y/z I wanted the leaf in the output to have the path y/x/z. (permutation 2,1,3). 

Instead of handling fixed-length permutations, what I want to do now are permutations like "2,1, 3..n-1"

So my XSLT now looks like this:

```
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/input">
    <output>
        <xsl:apply-templates select="text()"/>
    </output>
</xsl:template>

    <!-- example 2,1,3:n -->

    <xsl:template match="text()">
        <xsl:variable name="n" select="5" /> <!-- this should later be the depth of the leaf -->
        <xsl:element name="{name(ancestor::*[2])}"> <!-- 2 -->
            <xsl:element name="{name(ancestor::*[1])}"> <!-- 1 -->
                <xsl:call-template name="loop"> <!-- 3:5 -->
                    <xsl:with-param name="i" select="3" />
                    <xsl:with-param name="end" select="$n - 1" />
                </xsl:call-template>
            </xsl:element>
        </xsl:element>
    </xsl:template>

    <xsl:template name="loop">
        <xsl:param name="i" />
        <xsl:param name="end" />

        <xsl:choose>
            <xsl:when test="$i = $end">
                    <xsl:copy-of select="."/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:element name="{name(ancestor::*[$i])}">
                    <!-- recursive call -->
                    <xsl:call-template name="loop">
                        <xsl:with-param name="i" select="$i+1" />
                        <xsl:with-param name="end" select="$end" />
                    </xsl:call-template>

                </xsl:element>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

</xsl:stylesheet>

```

I'm not even sure if this recursive use of templates could work theoretically. Am I on the right track?