Refactor the matching algorithm.