% -------------------------------------------------------------------------
% 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_statistics.m
% -------------------------------------------------------------------------


clear all
close all
clc

% MATLAB data files
% files = {'cones.mat', 'animal_farm.mat', 'teddy.mat', 'tsukuba_extracted4.mat'};
files = {'tsukuba_extracted4.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);

    % Extract layers and merge

    labels     = unique(label(:,:,:));
    labels     = labels(labels > 0);
    num_layers = length(labels);
    disparity  = ceil( (0:num_images-1)' * D' );

    % The disparity measures the displacement of a layer with respect to the
    % first image (EPI images, camera only moves in the horizontal axis)
    pos_disp = max(disparity(:));
    neg_disp = -min(disparity(:));
    ext_cols = c + pos_disp + neg_disp;

    % The layers_stack will contain one label per image, adding up the layer
    % among all the images disparity compensated
    layers_stack = zeros(r, ext_cols, num_layers);

    for l = 1 : num_layers
        ith_layer                      = zeros(r, ext_cols);

        for i = 1 : num_images
            cur_disp  = disparity(i, l);
            cur_label = label(:,:,i);

            % Indices of the location corresponding to the current layer in the
            % current image
            ind_orig = (cur_label == l);

            % Indices corresponding to the location in the extended layer
            ind_dest  = false(r, ext_cols);
            first_col = neg_disp + 1 + cur_disp;
            last_col  = first_col + c - 1;
            ind_dest(:, first_col:last_col) = ind_orig;

            % Copy 
            ith_layer(ind_dest) = cur_label(ind_orig) / l;
        end

        layers_stack(:,:,l) = ith_layer;    
    end
    
    % ====> Data is available here in "layer_stack" variable
    
    error_distances = [3 2 1 0];
    max_deltas      = [31 15 7 1];
%     distances = 0;
    
    [height, width, num_layer] = size(layers_stack);
    approx_layers              = zeros(height, width, num_layers-1);
    
    fid = fopen(['stats_' data_name '.txt'], 'w');
    disp(['File : ' data_name])

    
    for i = 1 : length(error_distances)
        
        d_max = error_distances(i);
        delta = max_deltas(i);
        
        max_offset    = 0;
        num_of_segs   = 0;
        num_of_verts  = 0;
        max_verts_seg = 0;
        
        for l = 1 : num_layers-1
            
            verts                = estimate_contours_vertices(layers_stack(:,:,l), d_max, delta);
            approx_layers(:,:,l) = contour2shape(verts, width, height);

            segment_inds  = find(verts(1,:) == 0);
            seg_lengths   = verts(2,segment_inds);
            
            max_offset    = max([max_offset get_max_offset(verts)]);
            num_of_segs   = max([num_of_segs length(segment_inds)]);
            num_of_verts  = max([num_of_verts max(seg_lengths)]);
            max_verts_seg = max([max_verts_seg max(seg_lengths)]);
            
        end % end of l = 1 : num_layers
        
        d = get_distortion(layers_stack(:,:,1:num_layers-1), approx_layers);
        
        disp(['Maximum distance          : ' num2str(d_max)])
        disp(['Obtained distortion       : ' num2str(d)]);
        disp(['Max offset                : ' num2str(max_offset)]);
%         disp(['Max num. of vertices      : ' num2str(num_of_verts)]);
        disp(['Max num. of segments      : ' num2str(num_of_segs)]);
        disp(['Max. vertices per segment : ' num2str(max_verts_seg)]);

        fprintf(fid, '\n');
        fprintf(fid, 'Maximum distance          : %f\n', d_max);
        fprintf(fid, 'Obtained distortion       : %f\n', d);
        fprintf(fid, 'Max offset                : %d\n', max_offset);
%         fprintf(fid, 'Num. of vertices          : %d\n', num_of_verts);
        fprintf(fid, 'Max num. of segments      : %d\n', num_of_segs);
        fprintf(fid, 'Max. vertices per segment : %d\n', max_verts_seg);
        
    end % end of d_max = distances
    
    fclose(fid);
    
end % end of file_name_cell = files
