function X = CoxExtract(I, J, alpha, N)
%COXEXTRACT Extract a watermark from an image
%   Given an original image I and a watermarked version J
%   (probably modified), COXEXTRACT extracts a watermark
%   from J using some knowledge about I.
%
%   See: COXWMK, COXDETECT, COXTEST, SIM

%   Fabien A.P. Petitcolas 26-11-97
%   Copyright (c) 1997 - University of Cambridge
%   $Revision: 0.6$

%   References:
%        1) Ross J. Anderson, editor. Information hiding: first
%           international workshop, volume 1174 of Lecture notes
%           in computer science. University of Cambridge, Isaac
%           Newton Institute, Springer Verlag, Berlin, Germany,
%           May 1996.
%        2) Ingemar J. Cox, Joe Kilian, Tom Leighton, and Talal
%           Shamoon. A secure, robust watermark for multimedia.
%           In Anderson [1], pages 183-206

if (nargin == 2)
   N = 1000;
   alpha = 0.1;
end
if (nargin == 3)
   N = 1000;
end

if (isrgb(I))
   error('Use grayscale image only');
end
sI = size(I);
if ((sI(1) * sI(2)) < N)
   error('Image too small or too many coefficients');
end
sJ = size(J);
if ((sI(1) ~= sJ(1)) | (sI(2) ~= sJ(2)))
   error('The images have different size.');
end

% Compute the DCT of the images
DCTI = dct2(I);
DCTJ = dct2(J);

% Find the N largest coefficients in the DCT matrix
Index = FindNLargest(abs(DCTI), N);

% Extract the watermark
for i = 1:N
   X(i) = (DCTJ(Index(1, i), Index(2, i)) / DCTI(Index(1, i), Index(2, i)) - 1) / alpha;
end
