Major code cleanup and reorganization