Code cleanup + minor bugfixes