Some refactoring and cleanup.