Lots of refactoring and cleanup.