
function [response, x, y] = match(map, patch, psize)

% function matches quadratic patch into map
%
% input:
%   map = map (need not to be quadratic)
%   patch = image patch (needs to be quadratic of size psize)
%   psize = patch size
% output:
%    response = goodness of match
%    x y = coordinates of best match


% 1. compute template for convolution (derived from the patch)

template=fliplr(flipud(patch)); % reorder - necessary for convolution
template=template-mean(mean(template)); % subtract mean, to
                                        % normalize response

% 2. convolve

response=conv2(map, template, 'same'); 
response=response-min(min(response));
response=response/max(max(response));


% 3. find maximum element - this is a little ugly in matlab

[max1,indx1]=max(response);
[max2,indx2]=max(max1);
x=indx1(indx2);
y=indx2;                       % max is now response(x,y)

