Clean up and test relation sorting code.