This code was written for my use only, and the commenting reflects that. It all makes sense to me, but I expect it to be a bit of a riddle for anyone else.
It's here because a colleague asked for it, although I'm not sure they knew what they'd be getting!