function imgOut = imscramble(imgIn,numTiles,varargin);
% IMSCRAMBLE: scramble images
% Usage: imgOut = imscramble(imgIn,numTiles,[options]);
%               OR
%        imgOut = imscramble(Name of Image File/s, numTiles, [options]);
%               OR
%        imgOut = imscramble(Name of Image Directory/s, numTiles, 'dir', [options]);
%
%
% scrambles an input image as if it was divided into a grid of size
% numTiles, with the tiles being randomly shuffled. 
%
% imgIn can be a raw image itself (that is, a numeric matrix), 
% or a name of the full path where the image file is located
% (string). imgIn may also be a cell-of-images, in which case, 
% each entry is a separate image (image itself or name of image), 
% and imgOut is a cell-of-images corresponding to each entry scrambled. 
% imgIn can also be the name of a directory containing images (see below).
%
% numTiles can be a single number or a size-2 vector. If it is a
% single number, then the number of tiles is assumed to be square;
% otherwise, the first element defines the number of tiles along
% the Y axis and the second element defines the number along the X
% axis.
%
% Options are:
%
%   'save': save the scrambled images into files. Uses
%   imwrite. This will output the image in the format specified by 
%   'filetype'. The output images will be named 'scr-[name of image]'.
%
%   'filetype': specify the format of the image file, as the next
%               argument. Default format is 'jpg'. 
%   
%   'outputdir': specify a directory to place the output image
%   files. Default is current working directory.
%
%   'dir': convert an entire directory. In this case, imgIn should be a
%   string containing the name of a directory with images to scramble.
%
% Doesn't currently work with true color images (which are loaded
% by imread as an M X N X 3 matrix).

% ras 03/25/03
if length(numTiles)==1
    numTiles = [numTiles numTiles];
end

%%%%% params/defaults
fileType = 'jpg';
saveImgsFlag = 0;
outputDir = pwd;
outputFilePrefix = 'scr-';
filename = 'image';
convertDirFlag = 0;

%%%%% parse the option flags
for i = 1:length(varargin)
    if ischar(varargin{i})
        varargin{i} = lower(varargin{i});
    end
    switch varargin{i}
    case 'filetype',
        fileType = varargin{i+1};
    case 'save',
        saveImgsFlag = 1;
    case 'dir',
        convertDirFlag = 1;
        varargin{i} = '';
    case 'outputdir',
        outputDir = varargin{i+1};
    end
end

%%%%% if a directory is entered, find images in that dir
if convertDirFlag
    tmp = grabfields(filterdir(fileType,imgIn),'name');
    for i = 1:length(tmp)
        tmp2{i} = fullfile(imgIn,tmp{i});
    end
    imgIn = tmp2;
end

%%%%% figure out how the images got passed in
if iscell(imgIn)    % separately scramble each image in the cell
    for i = 1:length(imgIn)
		call = ['imgOut{i} = imscramble(imgIn{i},numTiles'];
        for j = 1:length(varargin)
            call = [call ',''' varargin{j} ''''];
        end
        call = [call ');'];
        eval(call);
    end
    return
else
    if ischar(imgIn)
        tmp = findstr(filesep,imgIn);
        if isempty(tmp)
            filename = imgIn; 
        else
            filename = imgIn(tmp(end)+1:end);
        end
        imgIn = imread(imgIn,fileType);
    end
end

%%%%% init variables for main calculation
[a b] = size(imgIn);
totalTiles = numTiles(1)*numTiles(2);
rowsPerTile = a/numTiles(1);
colsPerTile = b/numTiles(2);
pixelsPerTile= rowsPerTile*colsPerTile;
Ind = reshape(1:a*b,[a b]);

%%%%% seed random number generator
rand('state',sum(100*clock)); 

%%%%% grab indices of each square
rows = round(1:rowsPerTile:a);
cols = round(1:colsPerTile:b);
corners = reshape(Ind(rows,cols),[1 totalTiles]);

%%%%% create numTiles x numTiles matrix N, represented scrambled
%%%%% tile order
N = reshape(shuffle(corners),[numTiles(1) numTiles(2)]);

%%%%% M is the shuffled index, the same size as imgIn, showing
%%%%% which pixel from imgIn maps to which pixel in imgOut
M = ones(a,b);
M(corners) = N;

% fill in each tile in M, first by rows then by cols
for i = 1:rowsPerTile-1
    M(rows+i,cols) = N + i;
end
for i = 1:colsPerTile-1
    M(:,cols+i) = M(:,cols) + i*a;
end

%%%%% Use M as an index to make the scrambled image
imgOut = imgIn(M);

%%%%% write out image file, if selected
if saveImgsFlag
    tmp = strfind(filename,['.' fileType]);  % crop extension name
    if ~isempty(tmp)    filename = filename(1:tmp(1)-1);  end
    tmp2 = filterdir(filename,outputDir);
    imcount = num2str(length(tmp2)+1);
    if isequal(imcount,'1') imcount = '';   end
	outputFile = [outputFilePrefix,filename,imcount,'.',fileType];
	outputPath = fullfile(outputDir,outputFile);
    imwrite(imgOut,outputPath,fileType);
    fprintf('%s \n',outputPath);
end

return
