Code cleanup and minor refactoring