Some initial code cleanup and refactoring