Fix matching bug and refactor sort