Sorting function fleshed out