Some refactoring and code cleanup.