clean up sorting code a bit