major code cleanup and bugfix