@tom025 this is a sketch of what I meant.

I hacked it out on a train journey, but I'm now at work and don't have
time to figure out why it doesn't work.

Hopefully it might give you enough to go on to finish this off. Feel
free to rebase/squash this commit out of existence :)