factored code somewhat.  Still has strange sorting transitions