## Copyright (C) 2011 Ferran Mesas Garcia <ferran.mesas01@gmail.com>
## 
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; If not, see <http://www.gnu.org/licenses/>.

## Converts a Huffman Dictionary created by @code{huffmandict} to 
## a Huffman Tree stored in an array.

function tree = dict2tree(dict)

  if ( nargin ~= 1 || strcmp(class(dict),"cell")~=1 )
    error('usage: dict2tree(dict)');
  end

  L = length(dict);
  lengths = zeros(1,L);

% the depth of the tree is limited by the maximum word length.
  for i = 1:L
    lengths(i) = length(dict{i});
  end
  m = max(lengths);
  tree = zeros(1,2^(m+1)-1); 

  for i = 1:L
    pointer = 1;
    word = dict(i);
    for bit = word
      pointer = 2*pointer+bit;
    end
    tree(pointer) = i;
  end
end
