Issue #2: proposed bugfix plus a few tweaks found while trying to reproduce the bug