function croppos=searchcrop(imcropped,code,crosssize,origsize,range,update)

% croppos = SEARCHCROP(imcropped,code,crosssize,origsize,range,update);
%
%     Searches for the unknown crop position of the cropped
%     watermarked image IMCROP by maximizing the difference
%     between the first two bits of the signature.
%     This function uses the functions IMCROP and RETRIEVE for
%     signature retrieval.
%
%     origsize: size of the original image, eg. origsize=[640 480]
%     range: 2 dimesional search range
%            range=[xmin xmax ; ymin ymax], eg. range=[250 290;100 120]
%     update: if set to 1 the screen will constantly be updated
%             if set to 0 the screen will not be updated
%
%
% University of Rhode Island
% Dept. of Electrical Engineering
% Roger Meier, May '99

W=origsize(1);
H=origsize(2);
w=size(imcropped,2);
h=size(imcropped,1);
diff=-1*ones(H-h+1,W-w+1);
surfl(diff)
shading interp
colormap(jet(256))
x1=range(1,1);
x2=range(1,1);
y1=range(2,1);
y2=range(2,1);
tic
for x = range(1,1):range(1,2)
	for y = range(2,1):range(2,2)
		im=uint8(zeros(H,W,3));
		im(y:y+h-1,x:x+w-1,:)=imcropped;
		[signature,delta] = retrieve(im,code,crosssize);
		diff(y,x) = delta(2)-delta(1);
		if update == 1
			x2=max([x range(1,1)+1]);
			y2=max([y range(2,1)+1 y2]);
			imagesc([x1:x2],[y1:y2],diff(y1:y2,x1:x2),[-1 max(2,max(max(diff)))]);
			drawnow
			disp(['x: ' num2str(x) ', y: ' num2str(y) ',  Signature: ' signature])
		end
	end
end
toc
imagesc(diff);
[r,c]=find(diff == max(max(diff)))
croppos=[r c];
