function [bitstream] = arithm_dec_stream(substreams, field_bits)
% -------------------------------------------------------------------------
% MSc Project - MSc in Communications and Signal Processing
% Department of Electrical and Electronic Engineering
% Imperial College London, 2011
%
% Supervisor  : Dr Pier Luigi Dragotti
% Contributor : Andriy Gelman
% Author      : Jon Onativia Bravo
%
% File        : arithm_enc_stream.m
% -------------------------------------------------------------------------
% 0-order 'arithmetic decoder'. Takes as input a list of substreams 
% generated by arithm_enc_stream and the size of the words of each 
% substream.
%
% [bitstream] = arithm_dec_stream(substreams, field_bits)
%
% INPUT:
%  - substreams   : BYTEstream generated by 'arithmetic decoder'.
%  - field_bits   : Size in bits of the words of each substream.
%
% OUTPUT:
%  - bitstream    : List of binary decoded stream.
%

% Obtain the number of substreams
num_sub_streams = length(substreams);

% Output variable
bitstream = cell(1, num_sub_streams);

% Reorder subtstreams
for ith_stream = 1 : num_sub_streams
    cur_bits = field_bits(ith_stream);
    
    % Apply arithmetic encoding to the stream
    alphabet_size = 2^cur_bits;
    dec_stream    = arithm_dec(substreams{ith_stream}, alphabet_size);

    num_symbols  = length(dec_stream);
    decompressed = zeros(1, num_symbols * cur_bits);
    for ith_symbol = 1 : num_symbols
        i_end   = ith_symbol * cur_bits;
        i_start = i_end - cur_bits + 1;
        
        decompressed(i_start:i_end) = dec2bin(dec_stream(ith_symbol), cur_bits);
    end
    
    % Save the compressed stream to the output varialbe
    bitstream{ith_stream} = decompressed;
end


