Major restructuring and code tidying