Refactor sorting to a separate file