Bugfixes and refactoring cleanup.