Thanks so much to Wendell and Jarno for your help. It is working beautifully.
Whew! not bad for a bit of work, eh?
This should work fine for input at the scale of most human-readable
documents. For higher performance (that numbering is a beast), you'll want
to split out an analytic/sorting pass before processing, or get out the big
rotary saw (XSLT 2.0).
Note: I just typed this up, and haven't tested, but I have used such code
and it works. Beware particularly of missing parentheses in my XPaths, etc.
Cheers,
Wendell