Major cleanup and refactoring