Large code cleanup patch