%
%
% Demonstration of modified Zhao&Koch algorithm of
% modulating relative values of DCT coefficients
%
% filename is the input TIFF filename, 
% message is the text message to hide
% 
%
function [mat] = jpeg_stego_encode(filename, message)

% read the TIFF file
mat = imread(filename , 'TIFF');

% store the old matrix
old = mat;

% get the size of the message
msize = size(message);
msize = msize(1,2);

% get the size of the image
s = size(mat);
s = s(1,1)*s(1,2);

% calculate message size == number of blocks
message = dec2bin(message, 8);
marraysize = size(message);
binmessage ='';
for i = 1:marraysize(1,1),
    binmessage = strcat(binmessage,message(i,:));
end
message_size = size(message);
msize = message_size(1,1)*message_size(1,2);
if (s/64) < msize,
    display('Maximum message size is ');
    int32(s/64)
    return;
end

% initialize variables
imsize = size(mat);
xdim= imsize(1,1);
ydim = imsize(1,2);
count = 1;
finished = 0;    

% loop through the image in blocks of 8x8
for i=1:8:xdim,
    for j=1:8:ydim,
        
        % get one block
        temp = double(mat(i:1:min(i+7, xdim), j:1:min(j+7,ydim)));        
        tempsize = size(temp);
        width = tempsize(1,1);
        if width < 8,
            temp(width:8,:) = 0;
        end
        height=tempsize(1,2);
        if height < 8,
            temp(:,height:8) = 0;
        end
        
        % perform dct
        % (initially not knowing matlab so well i used 
        % a piece of dct matlab code I found in the literature)
        % i then found about blkproc but left this as it is
        B = bdct(temp);
        
        if count > msize,
            finished = 1;
            break;
        end
        
        
        if binmessage(1,count) == '0',
            if B(2,3) > B(4,1),
                t = B(2,3);
                B(2,3) = B(4,1);
                B(4,1) = t;
            end
        else
            if B(2,3) < B(4,1),
                t = B(2,3);
                B(2,3) = B(4,1);
                B(4,1) = t;
            end
        end
        
        if abs(B(2,3) - B(4,1)) < 4,
            if B(2,3) > B(4,1),
                B(2,3) = B(2,3) + 6;
                B(4,1) = B(4,1) + 1;
            else,
                B(4,1) = B(4,1) + 6;
                B(2,3) = B(2,3) + 1;
            end
        end
        
        b1 = ibdct(B);        
        mat(i:1:i+7,j:1:j+7) = b1;        
        count= count+1;
    end        
    if finished == 1,
        break;
    end;        
end

% display the old and the new figures
figure; 
subplot(2,1,1); imshow(old);
subplot(2,1,2); imshow(mat);

