Here's a revised draft of the patch, which updates the comments and refactors the code a bit to (hopefully) make it a bit more readable. Mark