I've fixed a few problems I've found with more extensive testing. Attached is the version 2 of the patch series.