Big cleanup and refactoring.