I'm sorry, but I can't see the logic of why
<th id="un_4" headers="un_1">header5</th>
<th id="un_5" headers="un_1">header6</th>
point to un_1 rather than un_0. I'm afraid specification by example doesn't always work - the logic may be obvious to you, but it's not necessarily obvious to the reader. It would help to submit a much smaller example and explain the functional relationship more clearly.
Having said that, this kind of problem is hard in XSLT 1.0 (and it's no pleasure to solve it for someone who uses XSLT 2.0 every day). It's usually best to tackle it as a multi-pass transformation, with the first pass perhaps adding absolute row/column numbers of the top-left and bottom-right corners of each cell.
Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference