function [tree,json] = wordnetTree(D, mincounts)


if nargin == 1
    mincounts = 0;
end

tree.parent = []; % node = 0 is the root node
tree.nodewords = {};
tree.counts = [];

for n = 1:length(D)
    for j = 1:LMcountobject(D(n))
        name = D(n).annotation.object(j).name;
        wordnet = wn(name);
        
        if ~isempty(wordnet)
            branch = wordnet.hypernym;
            [tree, nodes] = addbranch(tree, branch);
            for nd = 1:length(nodes)
                if nodes(nd)>length(tree.counts)
                    tree.counts(nodes(nd)) = 1;
                else
                    tree.counts(nodes(nd)) = tree.counts(nodes(nd))+1;
                end
            end
        end
        
    end
end
% 
% 
%     i
%     if length(sensesfile)>0
%         branch = [synonims{i}; strread(synset{i}, '%s', 'delimiter', '.')];
%     else
%         branch = strread(synset{i}, '%s', 'delimiter', '.');
%     end
% 
%     [tree, nodes] = addbranch(tree, branch);
%     for nd = 1:length(nodes)
%         if nodes(nd)>length(tree.counts)
%             tree.counts(nodes(nd)) = counts(i);
%         else
%             tree.counts(nodes(nd)) = tree.counts(nodes(nd))+counts(i);
%         end
%     end
% end
% 

if nargout > 1
    json = getStringBranch(tree,0,mincounts);
    
    % write json file
    fid = fopen('tree.json', 'w');
    fwrite(fid, json, 'char');
    fclose(fid);
end

if nargout==0
    showTree(tree)
end





%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [tree, nodes] = addbranch(tree, branch)
%
% Add a new branch to the tree

N = length(branch);
M = length(tree.parent);
parent = 0; %start on the root
for n = N:-1:1
    % two different nodes might have the same name!
    np = find(tree.parent==parent);
    node = strmatch(strtrim(branch{n}), tree.nodewords(np), 'exact');
    node = np(node);

    if isempty(node)
        % connect node to the root
        tree.parent(M+1) = parent;
        tree.nodewords{M+1} = strtrim(branch{n});
        nodes(n) = M+1;

        M = M+1;
        parent = M;
    else
        parent = node;
        nodes(n) = node;
    end
end

function json = getStringBranch(tree, parent, mincounts)

json = [];

if parent == 0
    json = sprintf('{ "name": "root"');
else
    nodename = tree.nodewords{parent};
    j = strfind(nodename, ',');
    if ~isempty(j)
        nodename = nodename(1:j(1)-1);
    end
    json = sprintf('{ "name": "%s (%d)"', nodename, tree.counts(parent));
end

j = find((tree.parent == parent).*(tree.counts>=mincounts));

% sort j alphabetically
[~,jj] = sort(tree.nodewords(j));
j = j(jj);

if ~isempty(j)
    json = [json sprintf(',\n"children": [\n')];
    for n = 1:length(j)
        json = [json getStringBranch(tree, j(n), 10+0*mincounts)];
    end
    json = json(1:end-2);
    json = [json sprintf('\n]\n')];
end

json = [json sprintf('},\n')];

if parent == 0
    json = json(1:end-2);
end

