Improve matching algorithm and fix bugs