function [dictionary] = CalculateDictionary( imageFileList, dictionarySize )
%function [ ] = CalculateDictionary( imageFileList, dataBaseDir, featureSuffix, dictionarySize, numTextonImages, canSkip )
%
%Create the texton dictionary
%
% First, all of the sift descriptors are loaded for a random set of images. The
% size of this set is determined by numTextonImages. Then k-means is run
% on all the descriptors to find N centers, where N is specified by
% dictionarySize.
%
% imageFileList: cell of file paths
% dataBaseDir: the base directory for the data files that are generated
%  by the algorithm. If this dir is the same as imageBaseDir the files
%  will be generated in the same location as the image files.
% featureSuffix: this is the suffix appended to the image file name to
%  denote the data file that contains the feature textons and coordinates. 
%  Its default value is '_sift.mat'.
% dictionarySize: size of descriptor dictionary (200 has been found to be
%  a good size)
% numTextonImages: number of images to be used to create the histogram
%  bins
% canSkip: if true the calculation will be skipped if the appropriate data 
%  file is found in dataBaseDir. This is very useful if you just want to
%  update some of the data or if you've added new images.

fprintf('Building Dictionary\n\n');

% parameters

ndata_max = 500000;
total_descriptors = 0;
for i=1:length(imageFileList)
    imageFName = imageFileList{i};
    load(imageFName, 'x');
    total_descriptors = total_descriptors + length(x);
end

siftArr = zeros(total_descriptors, 128);
currentIdx = 1;
for f = 1:length(imageFileList)
    imageFName = imageFileList{f};
    load(imageFName, 'data');
    siftArr(currentIdx:currentIdx+size(data, 1)-1, :) = data;
end

fprintf('\nTotal descriptors loaded: %d\n', size(siftArr,1));

ndata = size(siftArr,1);
if (ndata > ndata_max)
    fprintf('Reducing to %d descriptors\n', ndata_max);
    p = randperm(ndata);
    siftArr = siftArr(p(1:ndata_max),:);
end
        
% run kmeans
fprintf('\nRunning k-means\n');

[dictionary, ~] = litekmeans(siftArr', dictionarySize);

dictionary = dictionary';

end
