If you post code samples then consider to indent them and mark them up with
http://p2p.wrox.com/misc.php?do=bbcode#code as that makes it easier for other to read them.
As for your problem, I would not write one template with lots of for-each, instead I would write templates with different modes so that you can have one mode for creating an index for instance. That way it is easier to separate the different tasks.
Also note that instead of doing
Code:
<xsl:variable name="varCat">
<xsl:value-of select="title"/>
</xsl:variable>
you can and should simply use
Code:
<xsl:variable name="varCat" select="title"/>