matching algorithm working correctly