cleaned up sorting code