Code cleanup and minor bugfix