algorithm of template matching