function [bits, fields] = get_required_bits(label_verts_tree, max_offsets, max_depth)
% -------------------------------------------------------------------------
% 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        : get_required_bits.m
% -------------------------------------------------------------------------
% 
%
% [bits, fields] = get_required_bits(label_verts_tree, max_offsets, max_depth)
%
% INPUT:
%  - 
%
% OUTPUT:
%  - 
%

% Extract tree parameters
num_of_layers = length(label_verts_tree);

bits   = 0;
fields = 0;

% 2 x 16 bits to store the image size
bits   = bits + 16*2;
fields = fields + 2;

% 8 bits to store the number of layers
bits   = bits + 8;
fields = fields + 1;

% 8 bits to store the number of levels of the tree
bits   = bits + 8;
fields = fields + 1;

% For each layer, 8 bits to store the number of contours
bits   = bits + 8*num_of_layers;
fields = fields + num_of_layers;

for ith_layer = 1 : num_of_layers
    num_of_contours = length(label_verts_tree{ith_layer});
    
    % For each contour, store the absolute position of the first vertex
    bits   = bits + 16*2*num_of_contours;
    fields = fields + 2*num_of_contours;
    
    for ith_contour = 1 : num_of_contours
        for depth = 1 : max_depth
            offset_bits = log2(max_offsets(depth) + 1) + 1;
            
            num_verts = 0;
            if ~iscell(label_verts_tree{ith_layer}{ith_contour}{depth})
                num_verts = size(label_verts_tree{ith_layer}{ith_contour}{depth}, 2) - 1;
                
                % Add 8 bits to store the number of vertices
                bits   = bits + 8;
                fields = fields + 1;
                
                % Add offset_bits*2 per vertex
                bits   = bits + offset_bits*num_verts*2;
                fields = fields + num_verts*2;
                
            else
                num_of_segs = length(label_verts_tree{ith_layer}{ith_contour}{depth});
                for ith_seg = 1 : num_of_segs
                    num_verts = num_verts + size(label_verts_tree{ith_layer}{ith_contour}{depth}{ith_seg}, 2) - 1;
                end
                
                % No need to store the number of segments because it
                % corresponds to the number of vertices of the previous
                % level
                
                % Add 8 bits to store the length of each seg
                bits   = bits + 8*num_of_segs;
                fields = fields + num_of_segs;
                
                % Add offset_bits*2 per vertex
                bits   = bits + offset_bits*num_verts*2;
                fields = fields + num_verts*2;
            end
        end
    end
end
