WIP for issue 682

I'm not sure I can add tests, but I'll look into tomorrow.