Code cleanup and bugfix