function [index, word2index] = ADE_word2index(word, word2index, ADDFLAG)

% The initial map was created as:
%     word2index = containers.Map(objectnames, [1:3441]);
%
% after this the initial map is irrelevant. We will just keep adding names
% as new words appear and we will assign a number to them.


if nargin<3
    ADDFLAG = 0;
end

if nargin < 2
    load ('wordnet_ADE20K', 'word2index')
end

if nargin == 0 || ADDFLAG==2
    words = keys(word2index);
    indices = values(word2index);
    indices = [indices{:}];
    index = []; % this will contain index2word
    for i = 1:length(indices)
        index{indices(i)} = words{i};
    end
    for i = 1:length(index)
        if isempty(index{i})
            index{i} = ' ';
        end
    end
    return
end

word = strrep(word, '  ',' ');
word = strtrim(word);
word = lower(word);

% Correct the word (spelling errors, ...):
if isKey(word2index, word)
    index = word2index(word);
else
    disp('Word not found in "word2index". Adding...')
    disp(['Current word: ' word]);
    
    word2index(word) = length(keys(word2index))+1;
    new = containers.Map(word, length(keys(word2index))+1);
    
    word2index = [word2index; new];
    index = word2index(word);
    
    if ADDFLAG == 1
        file = which('wordnet_ADE20K.mat');
        save (file, 'word2index', '-append')
        
    else
        disp('Word not not saved in the index');
    end
end

