Various bugfixes and cleanups.