Big mofo of bugfixes and cleanup