function w = ind2word(n,ind)

% n is an integer (size of alphabet)
% ind is the index of a word
% Outputs word on {1,...,n} corresponding to index ind

% Find l such that (n^l - 1) / (n-1) < ind <= (n^(l+1) - 1)/(n-1)
% The returned word will have length l
% Note: I found log2 to be more accurate than log
% For example ceil(log(9)/log(3)) incorrectly returns 3
% whereas ceil(log2(9)/log2(3)) correctly returns 2
l = ceil(log2(ind*(n-1)+1)/log2(n))-1;
assert((n^l - 1) / (n-1) < ind && ind <= (n^(l+1) - 1) / (n-1), sprintf('ind=%d, l=%d\n',ind, l));
if l == 0
    % Empty word
    w = [];
else
    w = cell(1,l);
    [w{:}] = ind2sub(n*ones(1,l),ind - ((n^l - 1) / (n-1)));
    w = cell2mat(w);
end