Various bugfixes and cleanups