%
% Extraction function demonstrating spread-spectrum
% watermarking (see webpage documentation)
%
% Input parameters
% ----------------
% D : the image matrix (output matrix opf the spread_watermark_insert)
%     function usually)
% V : the original values of the DCT coefficients
% X : the original statistical set of random values to compare using
%     the similarity function
% I : the indices of the high value DCT coefficients
% n : the number of watermark bits
% mode: 'random', 'jpeg', 'scaledjpeg' to test various
%       aspects of the spreadspectrum scheme
%
%
function spread_watermark_extract(D, V, X, I, n, mode)

% calculate the size of 
n = size(V);
n = n(1,2);


% perform DCT on the whole image
% using blockproc
mat = double(D);
fun = @dct2;
dct=blkproc(mat,[8 8], fun);


% get the dct indices corresponding
% to the keys
for i=1:n,
    V1(1,i) = dct(I(i,1), I(i,2));
end

% use the invertible formulate to 
% to get the new X1 vector
numer = V1-V;
denom = 0.1*V;
X1 = numer./denom;


if strcmp(mode, 'random'),
    % Generate the random watermarks
    % They are generated by using the randn
    % function with mean 0, std. deviation 1
    % and seeding the state everytime with the
    % clock. The first value contains the
    % watermark detector of the image. This is
    % the first demo in the demonstration page
    similarity(1,1) = (X.*X)/sqrt(X.*X);
    for i=2:100,
        randn('state',sum(100*clock));
        for j=1:n,        
            tempX(1,j) = randn(1);        
        end
        similarity(i,1) = (tempX.*X)/sqrt(tempX.*tempX);
    end    
else,    
    similarity = zeros(100,1);
    similarity(25,1) = (X.*X)/sqrt(X.*X);
    similarity(75,1) = (X1.*X)/sqrt(X1.*X1);
end
   
figure;
stem([1:100], similarity);
ylabel('Similarity');

if strcmp(mode, 'random'),
    xlabel('Original Watermark at 1; rest are random');
else,
    if strcmp(mode, 'scaledjpeg'),
        xlabel('Origianl watermark at 25; scaled quality jpeg watermark at 75; rest are random');
    else,
        xlabel('Origianl watermark at 25; (poor quality) jpeg watermark at 75; rest are random');
    end
end    
 
