function [substreams] = arithm_enc_stream(bitstream, layer_limits, 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 encoder. Takes as input a binary stream that 
% represents words of different length. 
%
% [substreams] = arithm_enc_stream(bitstream, layer_limits)
%
% INPUT:
%  - bitstream    : BITstream to be encoded.
%  - layer_limits : Limits in the bitstream of each of the layers (each 
%                   layer contains words of different length).
%  - field_bits   : Amount of bits per word for each layer.
%
% OUTPUT:
%  - substreams   : List of arithmetic encoded BYTEstreams. Each substream
%                   of the list corresponds to a chunk of the input
%                   bitstream that has a certain word length.
%

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

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

% Reorder subtstreams
for ith_stream = 1 : num_sub_streams
    if ith_stream == 1
        start_idx = 1;
    else
        start_idx = layer_limits(ith_stream) + 1;
    end
    if ith_stream == num_sub_streams
        end_idx = length(bitstream);
    else
        end_idx = layer_limits(ith_stream+1);
    end

    cur_bits = field_bits(ith_stream);
    
    substream   = bitstream(start_idx:end_idx);
    num_symbols = length(substream) / cur_bits;
    dec_stream  = zeros(1, num_symbols);
    for ith_symbol = 1 : num_symbols
        i_end   = ith_symbol * cur_bits;
        i_start = i_end - cur_bits + 1;
        dec_stream(ith_symbol) = bin2dec(substream(i_start:i_end),false);
    end

    % Apply arithmetic encoding to the stream
    alphabet_size     = 2^cur_bits;
    compressed_stream = arithm_enc(dec_stream, alphabet_size);

    % Save the compressed stream to the output varialbe
    substreams{ith_stream} = compressed_stream;
end

