Massive refactoring and cleanup.