function [layers_stack] = generate_layer_stack(label, D)
% -------------------------------------------------------------------------
% 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        : generate_layer_stack.m
% -------------------------------------------------------------------------
% Generate a stack of images where each image contains one label. The
% labels are obtained merging the labels distortion corrected among the
% label images.
%
% [layers_stack] = generate_layer_stack(label, D)
%
% INPUT:
%  - label        : Set of images with the labels .
%  - D            : Disparity vector.
%
% OUTPUT:
%  - layers_stack : Stack of images with one label per images.
%

% Obtain images size
[r, c, num_images] = size(label);

% 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

end