code cleanup and bugfixes