% P = find_dog_peaks(DoG, octSize)
%  searches a set of DoG levels for keypoints and returns a 
%  list of such keypoints, scaled (using octSize) back to the
%  positions on the original image. 

function P = find_dog_peaks(DoG, octSize)

Points = [];

PERIM_MARGIN = 5;

%% get parameters
[InitSigma,Scales,PeakThresh,R] = get_dog_params;

for dog_level = 2:size(DoG,3)-1,
  for i=PERIM_MARGIN:size(DoG,1)-PERIM_MARGIN,
    for j=PERIM_MARGIN:size(DoG,2)-PERIM_MARGIN,
      
      % extract a 3x3x3 neighborhood patch from the DOG pyramid
      patch = DoG([i-1:i+1],[j-1:j+1],[dog_level-1:dog_level+1]);

      if ( (patch(2,2,2) > PeakThresh/Scales) &&  ...
	    is_local_extremum(patch) &&  ...
	    nae(DoG,i,j,R,5))
%%	    true)


	 % it's a keypoint! 

%% DEBUG =============================================================
%         sprintf('adding patch %d,%d,%d',i,j,dog_level)
%	 patch
%	 figure(20*dog_level+4*i+j);
%	 imshow(patch);
%	 title(sprintf('dog %d row %d col %d', dog_level, i, j));
%% END
%% DEBUG==========================================================

%% used merely for drawing
         k=2^(1/Scales);
         sigma_cur = (1/octSize)*InitSigma*k.^(dog_level-1);
%% --
	 
	 Points = [Points; [i j sigma_cur]];
      end;
      
    end;
    
  end;
%% debug =========================================================
% DoGsize = size(DoG)
% Peet = Points
% octSize = octSize
% scaledP = (1/octSize)*Points
%% end debug =====================================================
    
%% rescale image points back to positions in original image
P = (1/octSize)*Points;
end;