Lots of cleanup and minor bugfixes all over the code