Code cleanup and minor bugfixes