%EUSIPCO 2012
%Imperial College London 
%Andriy Gelman, Jon Onativia and Pier Luigi Dragotti 


function label = generate_3D_label(layer_stack, input_dims, D, number_of_images, string, stack_phi_reference)

%layer_stack(layer_stack <0) =-1;
%layer_stack(layer_stack >=0) = 0;
%layer_stack = -layer_stack;

rows_label = input_dims(1);
cols_label = input_dims(2);

[rows_stack_label, cols_stack_label, number_of_layers] = size(layer_stack); 

number_of_layers = length(D);
if (strcmp(string, 'ceil') == 1)
    disparity = ceil(([0:1: number_of_images-1] - (stack_phi_reference-1))'*D');
else
    disparity = round(([0:1: number_of_images-1] - (stack_phi_reference-1))'*D');
end

%Initialize
label = -ones(rows_stack_label, cols_stack_label, number_of_images); 

%Extract contour from stack phi and set labels;

%Start with the smallest disparity and loop to the largest disparity
for l  = 1:number_of_layers    
    label = create_label(label, layer_stack(:,:,end + 1 - l), (number_of_layers-l+1), disparity(:,end - l + 1), stack_phi_reference);
end

row_diff = (rows_stack_label - rows_label)/2;
col_diff = (cols_stack_label - cols_label)/2;

label = label(1+row_diff:end-row_diff, 1+col_diff:end-col_diff, :);

end

function label = create_label(label, stack_label, layer_number, disparity, location)

[rows, cols, number_of_images] = size(label);

    for l = 1:number_of_images
        buffer = label(:,:,l);
        stack_label_buffer  = integer_shift(stack_label, (disparity(l)-disparity(location)));
        buffer(stack_label_buffer == 1) = stack_label_buffer(stack_label_buffer == 1);
        buffer(buffer==1) = layer_number;
        label(:,:,l) = buffer;
    end

end