Fixes #3851 - various code cleanups and a few bug fixes along the way.