Separate out logic
Fix typo.
Improve implementation of sorting and fix bug.