Completely rewrite sort, obviously didn't know what I was doing earlier.