improved matching algorithm