% -------------------------------------------------------------------------
% 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       : compute_tree_statistics.m
% -------------------------------------------------------------------------


clear all
close all


% MATLAB data files
% files = {'animal_farm.mat', 'cones.mat', 'teddy.mat', 'tsukuba_extracted4.mat'};
files = {'teddy.mat'};


% Loop over all files
for file_name_cell = files
    
    file_name         = file_name_cell{1};
    [~, data_name, ~] = fileparts(file_name);

    % Load data

    % Disparity vector
    load(file_name, 'D');
    % Images array
    load(file_name, 'in');
    % Labels array
    load(file_name, 'label');

    % Size of the data
    [r, c, num_images] = size(in);

    % Obtain the stack of labels
    layers_stack = generate_layer_stack(label, D);
    
    % Subsampling parameters
    subs_fact = 4;

    % Labels parameters
    [height, width, num_layers] = size(layers_stack);
    approx_layers               = zeros(height, width, num_layers);
    
    % Compute the contours for each image
    contours = cell(1, num_layers - 1);
    a        = cell(1, num_layers - 1);
    b        = cell(1, num_layers - 1);
    disp('Estimating subsampled contours...')
    for l = 1 : num_layers - 1
        disp(['layer = ' num2str(l)])
        [contours{l}, a{l}, b{l}] = estimate_subsampled_contours(layers_stack(:,:,l), subs_fact);
    end
    
    % Convert contours into bitstream to measure the bitrate
    bitstream = subscontour2bitstream(contours, a, b, width, height);
    
    % Reconstruc the shapes to measure the distortion
    disp('Reconstructing subsampled contours...')
    for l = 1 : num_layers - 1
        disp(['layer = ' num2str(l)])
        approx_layers(:,:,l) = reconstruct_subsampled_contours(contours{l}, subs_fact, a{l}, b{l}, width, height);
    end
    
    % Measure the distortion
    d = get_distortion(layers_stack(:,:,1:num_layers-1), approx_layers(:,:,1:num_layers-1));
    
    % Start printing statistics
    disp(' ')
    disp(['File : ' file_name])

    disp(['Bits                      : ' num2str(length(bitstream))]);
    disp(['Obtained distortion       : ' num2str(d)]);
    
end % end of file_name_cell = files

% Play a sound when finished
fs = 8000;
Ts = 1 / 8000;
t  = 0:Ts:2;
fo = 220;
so = sin(2*pi*fo*t);

% soundsc(so, fs)
