Major cleanup and optimization.