Major cleanup and refactoring.