updated sorting routine