function ADMINcreateDictionaryParts(D, HOMEIMAGES, thSize)
% VISUAL OBJECT DICTIONARY
%
% Creates a visual index of all the objects in the database
%
% ADMINcreateDictionary(D, HOMEIMAGES)
homethumbnails = 'objectDictionary';
if nargin<3
    thSize = 64;
    %thSize = 48;
end
minNumInstances = 0;

% create parts tree
[tree, json] = partsTree(D);
[node, level] = sortTree(tree,0,0);

Nnodes = length(tree.parent);
Ninstances = sum(tree.counts);
NwholeObjects = sum(level==0);

colors = {'red', 'blue', 'green', 'red', 'blue', 'green', 'red', 'blue', 'green'};
% sort whole objects alphabetically

% sort objects by the number of annotated parts
if 1
    for i = 1:Nnodes
        j = node(i);
        data = tree.crop(j).data;
        nparts = [];
        for d = 1:size(data,1)
            im = data(d,1);
            obj = data(d,2);
            [hasparts, ispartof] = findparts(D(im).annotation, obj);
            nparts(d) = length(hasparts);
        end
        [~,p]=sort(nparts, 'descend');
        tree.crop(j).data = data(p,:);
    end
else
    % only one image per object.
    for i = 1:Nnodes
        j = node(i);
        tree.crop(j).data = unique(data(:,1));
    end
end

% Create index with global names and with local instances
fid = fopen('dictionary.js', 'w');
fprintf(fid, 'var d=new Array();\n')
fprintf(fid, 'var n=new Array();\n')
fprintf(fid, 'var x=new Array();\n')
fprintf(fid, 'var a=new Array();\n')
fprintf(fid, 'var p=new Array();\n')
fprintf(fid, 'var q=new Array();\n')
fprintf(fid, 'var Nimages=%d;\n', length(D))
fprintf(fid, 'var Nnames=%d;\n', Nnodes)
fprintf(fid, 'var Ninstances=%d;\n', Ninstances)
fprintf(fid, 'var Nwholes=%d;\n', NwholeObjects)
fprintf(fid, 'var nrows=%d;\n', Nnodes)
fprintf(fid, 'var ncols=%d;\n', 1)

C = 0;
whole = 0;
ii = 0;
for i = 1:Nnodes
    j = node(i);
    na = strrep(tree.nodewords{j}, '''', '');
    if ~isempty(na) && tree.counts(j)>minNumInstances
        if level(i)>0
            na = lower(na);
            na = [repmat('&nbsp;', [1 1+3*level(i)]) '&nbsp;<font color="' colors{level(i)} '">&#8627;</font>' na];
        else
            whole = whole+1;
            
            
            na = sprintf('<b>%d) %s<b/>', whole, [upper(na(1)) lower(na(2:end))]);
        end
        
        ii = ii+1;
        fprintf(fid, 'd[%d]=''%s'';\n', ii, na);          % strings, object names
        fprintf(fid, 'n[%d]=''%d'';\n', ii, tree.counts(j));         % number of instances
        fprintf(fid, 'x[%d]=''%d'';\n', ii, j); % node index
        fprintf(fid, 'a[%d]=%d;\n', ii, C); % instance index
        C = C+size(tree.crop(j).data,1);
        disp([tree.counts(j) size(tree.crop(j).data,1)])
    else
        disp('short name:')
        disp(na)
    end
end

%keyboard

m=0;
for i = 1:Nnodes
    j = node(i);
    data = tree.crop(j).data;
    
    for d = 1:size(data,1)
        m = m+1;
        im = data(d,1);
        
        fprintf(fid, 'p[%d]="%s";\n', m, D(im).annotation.folder);  % strings, object names
        fprintf(fid, 'q[%d]="%s";\n', m, strrep(D(im).annotation.filename, '.jpg', ''));  % strings, object names
    end
end

fclose(fid)

return

indices = [];
for i = 1:Nnodes
    data = tree.crop(i).data;
    Nitems = size(data,1);
    data = cat(2, data, i*ones(Nitems, 1));
    data = cat(2, data, (1:Nitems)');
    indices = cat(1, indices, data);
end
% Indices = [image index into D, object index into D, node index, instance index]

% Loop on D, loop on object
%instancesCounts = zeros(Nnodes,1);
problems = {''};
done = 0;
for i = 1:length(D)
    
    % get thumbnail and extract object and mask
    try
        img = LMimread(D, i, HOMEIMAGES);
        
        % find all the nodes that have objects in this image
        objs = find(indices(:,1)==i);
        
        o = indices(objs, 2);
        node = indices(objs, 3);
        inst = indices(objs, 4);
        
        for n = 1:length(objs)
            T = LMobjectThumbnail(D(i).annotation, img, o(n), [thSize thSize]);
            
            %na = strrep(names{d(n)}, '''', '');
            %if length(na)>1
            %na = [upper(na(1)) lower(na(2:end))];
            folder = fullfile(homethumbnails, sprintf('obj_%d', node(n)));
            
            filename = fullfile(folder, sprintf('ins_%d.jpg', inst(n)));
            
            mkdir(folder)
            disp(filename)
            imwrite(T, filename, 'jpg', 'quality', 90);
            
            
            % Add to description file: folder, SUN name
            fid = fopen(fullfile(folder, 'description.txt'), 'a');
            fprintf(fid, '%s/%s \n', D(i).annotation.folder, D(i).annotation.filename);
            fclose(fid);
            
            done = done+1;
            disp(done)
            %end
        end
    catch
        a = lasterror
        problems = [problems; a.message];
        keyboard
    end
end





function [node, level] = sortTree(tree, parent, current_level)

node = [];
level = [];
if parent == 0
    current_level=0;
end

j = find(tree.parent == parent);
[~,k] = sort(tree.nodewords(j));
j = j(k);

if ~isempty(j)
    for n = 1:length(j)
        node = [node j(n)];
        level = [level current_level];
        [node_j, level_j] = sortTree(tree, j(n), current_level+1);
        node = [node node_j];
        level = [level level_j];
    end
end
