Don't do this:
<xsl:variable name="pos">
<xsl:value-of select="position()"/>
</xsl:variable>
Do this:
<xsl:variable name="pos" select="position()"/>
In the first case you are creating a result tree fragment: a heavyweight data structure with a root node and a text node containing the value of position() converted from a number to a string. In the second case the variable is a simple number. I can't understand why so many people make this mistake (perhaps they are paid by how many lines of code they write?)
I can't help you with the question you asked, I'm afraid - I'm not sure what you're trying to achieve. Please simplify it to show the essence of the difficulty.
Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference