Bugfixes, some code cleanup.