Added sorting, refactored for better clarity