Large-scale refactoring for optimization and cleanup.