Fix docs and refactor sort function