%!! start: huffmantreehead
function res = huffmantree(symbols, freqs)
% huffmanTree(symbols, freqs) make Huffman code 
% symbols: char or numeric vector
% freqs: counts or relative frequencies
treelist = cell(length(symbols),1); %! Set up each symbol as a tree.
for k=1:length(symbols)
    treelist{k} = makenode(symbols(k));
end
while length(treelist) > 1 %! Merge until only one is left.
   [treelist,freqs]=reduceByOne(treelist,freqs);
end
res = treelist{1}; 
%!! end: huffmantreehead
%!! start: reduceByOne
function [t,f] = reduceByOne(t,f) %! eHlper function
if length(t) == 1
    return; % done
else %! Merge two into one tree.
    [trash,inds] = sort(f);
    t{inds(1)} = makenode(' ', ...%! Replace one with the new tree
        t{inds(1)},t{inds(2)});
    f(inds(1)) = f(inds(1)) + f(inds(2));
    t{inds(2)} = t{end}; %! Replace the other with the last item.
    f(inds(2)) = f(end);
    t = t(1:(end-1));%! Shorten the list.
    f = f(1:(end-1));
end
%!! end: reduceByOne