Bugfixes and code cleanup