This is a second version of the patch that adds tests for this bug. I also rebased it onto master.