Bugfixes and code cleanup.