This is better, but I'm not going to do your debugging for you. There's nothing that leaps out of the page here as obviously wrong. You're just going to have to step through the logic to see where it's producing faulty output. If you isolate a construct that's producing output you don't understand, the come back to the forum with a cut-down example that demonstrates the problem.
Some suggestions for debugging:
(a) use an XSLT debugger such as Stylus Studio or oXygen
(b) use a schema aware XSLT 2.0 processor such as Saxon 8.x: if you switch on validation of the output against the XHTML schema, you'll get error messages that pinpoint which lines of the stylesheet are generating invalid XHTML
(c) or simple put xsl:message statements into your code to see what path it is taking.
Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference