%  This program finds the correlation between the scene and the
%  footprints.  It uses the whitespace optimization.
function [N] = cor2(S, W)
  [sr, sc] = size(S);
  N = [];
  %  Iterate through the footprints.
  for imagenum =1:1:3
    M =[];
    hits =0;
    if imagenum == 1
      A = Loadin('myboot.tif');
    end
    if imagenum == 2
      A = Loadin('mydeer.tif');
    end
    if imagenum == 3
      A = Loadin('mybobcat.tif');
    end
    %  Find the self correlation so we have a maximum value on which
    %  to base our measurements.  
    self = max(max(xcorr2(A,A)));
    %  To prevent rotation from adding weird errors, make white have
    %  a value of zero in the matrix.
    A = A -.5.*ones(size(A));
    %  Prepare A for convolution
    A = fliplr(flipud(A));
    [ar, ac] = size(A);
    %  Check for both left and right feet.
    for flip = 0:1:1
      if flip==1
	A = fliplr(A);
      end
      for a = -90:30:90
	%  Rotate our footprint, then correlate
	B = imrotate(A, a, 'crop');
	%  Make white have a value of .5 again
	B = B + .5.*ones(size(B));
	c = 1;
	while c <= size(W, 2)
	  %slice extends the box found by WhiteSpace by half the
          %print image size all around to prepare it for Matlab's
          %conv2 command.
	  slice = S(W(1,c)-ar/2+1:W(2,c)+ar/2-1, W(3,c)-ac/2+1:W(4,c)+ac/2-1);
	  C = conv2(slice, B, 'valid');
	  %  Find the peak correlation values of the image
	  P = peaks(C, self);
	  %  Adjust the peaks since we are not starting our correlation
	  %  at the origin.  Also, undo the zero padding
	  [pr, pc] = size(P);
	  P = P + [(W(1,c)-17).*ones(pr/2, pc);(W(3,c)-17).* ...
		   ones(pr/2,pc)];
	  %  Store the information into the output matrix
	  if sum(size(P))>0
	    if sum(size(M))>0
	      M = [M(1,:), P(1,:); M(2,:), P(2,:); M(3,:), ...
		   a.*ones(1,size(P,2)); M(4,:),imagenum.*ones(1,size(P,2))];
	    else
	      M = [P;a.*ones(size(P,2));imagenum.*ones(size(P,2))];
	    end
	  end
	  Hits = size(P,2);
	  c = c+1;
	end
	%  This takes a while so update the user as to progress, or it
	%  becomes very frustrating!
	sprintf('Image = %d, Angle = %d, Hits so far= %d',imagenum, ...
		a, size(M,2))
      end
    end
    %  Plot out the points where footprints were found in different colors.
    if (imagenum==1)&(sum(size(M))>0)
      plot(M(2,:), M(1,:), 'rx')
      pause(.01)
      N = M
    end
    if (imagenum==2)&(sum(size(M))>0)
      plot(M(2,:), M(1,:), 'gx')
      pause(.01)
      N = [N, M]
    end
    if (imagenum==3)&(sum(size(M))>0)
      plot(M(2,:), M(1,:), 'bx')
      pause(.01)
      N = [N, M]
    end
  end
