Added new sort function with additional bugs

Errors happening during sorting.