Fix some bugs with sorting. Need tests for the best decision