Fix some bugs with sorting