General code refactoring and cleanup.