## 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/>.
##

## -*- texinfo -*-
## @deftypefn {Function File} {@var{sig} = } huffmandeco (@var{hcode}, @var{dict})
##
## Returns the original signal that was Huffman encoded signal using 
## @code{huffmanenco}. This function uses a dict built from the 
## @code{huffmandict} and uses it to decode a signal list into a huffman 
## list. A restriction is that @var{hcode} is expected to be a binary code
## The returned signal set that strictly belongs in the range @code{[1,N]}
## with @code{N = length(@var{dict})}. Also @var{dict} can only be from the
## @code{huffmandict} routine. Whenever decoding fails, those signal values a
## re indicated by @code{-1}, and we successively  try to restart decoding 
## from the next bit that hasn't failed in decoding, ad-infinitum. An example
## of the use of @code{huffmandeco} is
##
## @example
## @group
##   hd = huffmandict(1:4,[0.5 0.25 0.15 0.10])
##   hcode = huffmanenco(1:4,hd) #  [ 1 0 1 0 0 0 0 0 1 ]
##   huffmandeco(hcode,h d) # [1 2 3 4]
## @end group
## @end example
## @end deftypefn
## @seealso{huffmandict, huffmanenco}

function symbols = huffmandeco2(hcode,dict);
  if ( nargin < 2 || strcmp(class(dict),"cell")~=1 )
    error('usage: huffmanenco(sig,dict)');
  end
  if (max(hcode) > 1 || min(hcode) < 0)
    error("hcode has elements that are outside alphabet set ...
	Cannot decode.");
  end

% Convert the Huffman Dictionary to a Huffman Tree represented by
% an array.
  tree = dict2tree(dict);

% Traverse the tree and store the symbols.
  symbols =[];
  pointer = 1; % a pointer to a node of the tree.
  for i = 1:length(hcode);
    if (tree(pointer) ~= 0)
      symbols =[symbols, tree(pointer)];
      pointer = 1;
    end
    pointer = 2*pointer + hcode(i);
  end

% Check if decodification was successful
  if (tree(pointer) ~= 0)
    symbols =[symbols, tree(pointer)];
  else
    symbols = [symbols, -1];
    warning('Could not decode last symbol.')
  end
end

