This third patch is not really needed to fix the bug, but I had to simplify the code in order to figure out what was going on anyway.