function [D, attributes, counts] = LMcreateAttributesIndexField(D)
%
% [D, names] = LMcreateObjectIndexField(D);
%
% This function adds a new field to the LabelMe index that provides a
% numeric index into the attribute class. 
% 
% The new field is:
%    annotation.object.namendx
% and this is a pointer into 'names'

for n = 1:length(D)
    % sort attributes alphabetically and remove spaces
    if isfield(D(n).annotation, 'object') && isfield(D(n).annotation.object, 'attributes')
        for p = 1:length(D(n).annotation.object)
            atr = D(n).annotation.object(p).attributes;
            if ~isempty(atr)
                c = strtrim(textscan(atr, '%s','Delimiter', ','));
                c = sort(c{1});
                c = setdiff(c, '');
                atr = sprintf('%s,', c{:});
                atr = atr(1:end-1);
                D(n).annotation.object(p).attributes = lower(atr);
            end
        end
    end
end

% Create list of objects:
[attributes, counts, imagendx, attributendx, atrclass_ndx] = LMobjectnames(D, 'attributes');
% add new field
for k = 1:length(atrclass_ndx)
    D(imagendx(k)).annotation.object(attributendx(k)).attributendx = atrclass_ndx(k);
end


