Rework template matching logic