Major code cleanup and overhaul