%Coxwmk.m
function [J, W] = CoxWmk(I, alpha, N, W)
%COXWMK Insert a random watermark.
%   [J, W] = COXWMK(I) watermarks the grayscale picture I using
%   Cox's scheme [2] with default parameters. J is the watermarked
%   picture and W is the watermark.
%   The watermark W is drawn from a Normal random process N(0,1)
%   if it is not given by the user as last parameter.
% 
%   [J, W] = COXWMK(I, Alpha, N) watermarks the grayscale picture I
%   using modifying the Nth largest DCT coefficients v_i in the
%   following way: v_i := v_i * (1 + Alpha * w_i) where w_i
%   are the components of the watermark.
%
%   See: COXDETECT

%   This is a modified version of Fabien Petitcolas' implementation
%   of Cox's technique by Gabriela Delfino and Fabian Martinez
%
%   Fabien Petitcolas' website: http://petitcolas.net/fabien/

if (nargin == 1)
   N = 1000;
%  alpha = 0.1;
   alpha = 0.01;
   % We modify the value of alpha to achieve better visual quality
   W = randn(1,N);
end
if (nargin == 2)
   N = 1000;
   W = randn(1,N);
end
if (nargin == 3)
   W = randn(1,N);
end

sI = size(I);
if ((sI(1) * sI(2)) < N)
   error('Image too small or too many coefficients.');
end

% CoxWmk also works with color images
% In that case we watermark the Y component of the
& imagen in YIQ representation.
copiaI=I; 
% If the imagen is a color image we just watermark the Y plane
if (isrgb(I))
   IenYIQ=RGBtoYIQ(I);
   I=IenYIQ(:,:,1);
end

% Compute the DCT of the image
DCTI = dct2(I);

% Find the N largest coefficients in the DCT matrix
% Better if the extraction of the N largest was done
% at the same time than the computation of the DCT...
Index = FindNLargest(abs(DCTI), N);

% Modify these coefficients
for i = 1:N
   DCTI(Index(1,i),Index(2,i)) = DCTI(Index(1,i),Index(2,i)) * (1 + alpha * W(i));
end

% Simply take the inverse DCT of the modifyied matrix
% J = idct2(DCTI);
IconMarca = idct2(DCTI);
% We save the inverse DCT results in an auxiliar matrix
% If the image was a color image we convert it to RGB again
if (isrgb(copiaI))
   JenYIQ=IenYIQ;
   JenYIQ(:,:,1)=IconMarca;
   J=YIQtoRGB(JenYIQ);
else
   J=IconMarca;
end

% We change the values above 255 to 255 in order to avoid posible 
% distortions caused by the double representation of MatLab
J=abs(J);
J=cambiarValores(J,255,255);
J=uint8(J);
