Lots of code cleanup, a few tweaks and minor bugfixes.