Serious code cleanup and refactoring