fixed logic error in sort out function