After discussion with Jeroen Massar, here's a patch (mostly his)