Here's an updated version of the patch, thanks to Andreas Goesele for reporting and testing.