Looks like a tough one to crack with XSLT 1.0. Can you use 2.0?
Please try to describe your *requirements", that is, the input and output of the transformation, not the code you are trying to write to solve the requirement. Then we could consider alternative approaches.
Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference