improved template matching