Add sorting functions, clarify some comments