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

function reconstructed_approx_out = recombine_layers_using_saved_data(label, condition)

[r,c,k ] =size(label);
number_of_layers = max(max(max(label)));
reconstructed_approx_out = double(zeros(r,c,k));
if condition == 0

    for ii = number_of_layers:-1:1
        if (ii ~=5)
        %out_buffer = out_compressed(:,:, ((ii-1)*k + 1: ii*k)) ;
        out_buffer = input{ii};
        out_buffer(out_buffer <0) = 0;
        out_buffer(out_buffer <10) = 0;
        image = round(out_buffer);
        else
            %image =out_compressed(:,:, ((ii-1)*k + 1: ii*k));
            image = input{ii};
            image(image < 0) = 0;
            image = round(image);
        end
            %image =  round(reconstruction_compensated_harr_transform(approx_out(:,:,((i-1)*k1+1:i*32)),x(i),deapth(i)));
     
        buffer1 = reconstructed_approx_out;
        buffer1(buffer1 > 0) = 1;
    
        buffer2 = image;
        buffer2(buffer2 > 0) = 1;
    
        new_index = buffer2.*buffer1;
    
        reconstructed_approx_out(new_index == 1) = 0;
    
        reconstructed_approx_out = reconstructed_approx_out + image;
    end
else
%label(label == 0) = 5;

w = cd;
cd('operation/reconstructed_layers');
label = double(label);
for i = 1:number_of_layers
    label_layer = label;
    label_layer(label_layer ~=i) = 0;
    label_layer(label_layer == i)= 1;
    load(['layer',num2str(i)]);
    layer_output = double(layer_output);
    reconstructed_approx_out = reconstructed_approx_out + layer_output.*label_layer;
    
end
cd(w);
end  

end
    