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

EPSILON = 0.1;
DELTA = 0.3;

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

idxs = [];

while (length(idxs) == 0) 
  % minSSD cutoff -- 
  minSSD = min(SSD(:));
  idxs = find(SSD < min( DELTA, minSSD*(1+EPSILON)));
  EPSILON = EPSILON*1.1;
  DELTA=DELTA*1.1;
end

bestmatches = [];
errors = [];

if (length(idxs) > 0) 
    [i j] = ind2sub(size(SSD),idxs);
    for match=1:length(i)
      i_match = i(match);  j_match = j(match);
      bestmatches(:,:,match) = ...
	  sample([i_match:i_match+w-1],[j_match:j_match+v-1]);
      errors(match) = SSD(i_match,j_match);
    end 
   % bestmatches = sample([i:i+w-1],[j:j+v-1]);
end

