minor fixes to sorting and refactoring