Major clean up of engine code