%
% Function to decode the text message hidden via LSB substitution
%
% Input matrix, the keys representing the locations
%
function final_message = lsb_recv(mat, keys)

% get the length of the keys
ksize = size(keys);
ksize = ksize(1,2);
k = keys(1);
message = '';

% iterate over the keys 
s = size(mat); count = s(1,1)*s(1,2);
for i = 1:ksize,    
    
    % convert 1d k position value into
    % 2d x,y value
    y= mod(k, s(1,2));
    if y == 0, 
        y = s(1,2);
    end
    
    if floor(k/s(1,2)) < k/s(1,2),
        x = floor(k/s(1,2)) + 1;
    else,
        x = k/s(1,2);           
    end    
    
    % edge case check
    if x > s(1,1),
        x = s(1,1);
    end        

    % convert to binary string and append it to the message
    m = dec2bin(double(mat(x,y,3)),8);
    message = strcat(message, m(1,8));
    
    % goto next random location
    k = k + keys(i);
    
    % wrap around
    if k > count,
        k = count-k;        
    end        
    
end

% get the final message in char's
final_message = '';
for i=1:8:ksize,
    num = bin2dec(message(i:i+7));
    final_message = [final_message char(num)];     
end    
