refacto wagon-sorting