implemented most of the sort