I realised this would be better with some minor refactoring of the existing code, so I'm attaching a new version of that patch. I've used "git diff --ignore-space-change" for clarity (hence the indentation isn't correct).