Added sort order switch to enable reverse sorting
Reordered some functions for reading clarity