Code cleanup and bugfixes