template matching code