Rewrite matching code to make more extensible