Code cleanup and a few bug fixes