refactored for hopefully better sorting