Major code cleanup and optimization