Added advanced sorting function.