Dennis' patch (modified, with code to facilitate debugging)