function [bestmatches, errors] = findMatches(template,sample,G)
% searches sample for template and returns the 

epsilon = 0.1;

sizeG = size(G);
sizetemplate = size(template);

w = size(template,1);
v = size(template,2);
%sigma = w/6.4;
%gmask = gauss2d(w,sigma);

total = sum(sum(G)); % find maximum by summing over the mask

SSD = [];
for i=1:(size(sample,1) - w),
    for j=1:(size(sample,2) - v),
        SSD(i,j) = sum(sum( ...
	    ((template-sample([i:i+w-1],[j:j+v-1])).^2 ) .* G));
    end
    SSD(i,j) = SSD(i,j)/total;
end

% minSSD cutoff -- 
% minSSD = min(SSD(:));
% idxs = find(SSD < minSSD*(1+epsilon));

[minSSD minidx] = min(SSD(:));
idxs = minidx;

if (length(idxs) > 0) 
    % choose one at random
%    NUMMATCHES = length(idxs);
%    idx = idxs(floor(rand(1)*length(idxs)) + 1);
    [i j] = ind2sub(size(SSD),idxs);
    i = i(1); j = j(1);
    bestmatches = sample([i:i+w-1],[j:j+v-1]);
    errors = SSD(i,j);
else
    bestmatches = [];
    errors = [];
end

