Bugfixes, code cleanup