Bugfixes and code cleanups