An Algorithm for Efficient and Exhaustive Template Matching