function [vertices, required_bits] = contour_absolute_encode(layers, bit_budget)
% -------------------------------------------------------------------------
% 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       : contour_absolute_encode.m
% -------------------------------------------------------------------------
% Extract the contour of each layer and encode it to satisfy the required
% bit budget.
% Absolute coordinates of each vertex are stored. The required number of
% bits to store one coordinate in an image of size NxM is:
%  + q = ceil(log2(max([N, M])))
% Required bits:
%  + 32 bits to store the number of layers
%  + 32 bits per layer to store the length of the contour
%  + 2 * q bits * num_of_vertices


%%

% Size of the data
[r, c, num_layers] = size(layers);

% Compute the required amount of bits per coordinate
bits_per_coordinate = ceil(log2(max([r c])));


%% Extract contours
pixels_error = -1;
required_bits = Inf;
while required_bits > bit_budget
    pixels_error = pixels_error + 1;
    vertices     = cell(1, num_layers);
    num_vertices = 0;
    
    disp(['Processing layers with max pixel error: ' num2str(pixels_error)])
    
    for i = 1 : num_layers
        disp(['Processing layer ' num2str(i) ' out of ' num2str(num_layers) '...'])
        vertices{i} = estimate_vertices(layers(:,:,i), pixels_error);
        close gcf

        num_vertices = num_vertices + length(vertices{i});
        disp('... done')
    end

    required_bits = 32 + 32 * num_layers;
    required_bits = required_bits + bits_per_coordinate * num_vertices;
end

disp('Summary:')
disp([' - Required bits: ' num2str(required_bits)])
disp([' - Pixels error: ' num2str(pixels_error)])
disp([' - Number of layers: ' num2str(num_layers)])
disp([' - Total number of vertices: ' num2str(num_vertices)])
%%

