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

function [output_dwt, output_label_dwt, intra_pixels, uncovered_pixels, motion_Vect, final_label_location] = lifting_haar_transform(input, label, D, round_param, required_iterations)

%pad input and all of the values
%zeropad intra frame and label

%label = padarray(label, [0, ceil(number_of_images*max(max(D))), 0], 'both');
%input = padarray(input, [0, ceil(number_of_images*max(max(D))), 0], 'both');
[r,c,k] = size(input);
original_D = D;

%initialize output
output_dwt = zeros(r,c,k);
uncovered_pixels = zeros(r,c,k);

m = ceil(log2(k));
if isempty(required_iterations)
    required_iterations = m;
end
%initialize locations

%location = 0:1:(k-1);
location = 1:k;
%initialize low
low = input;
low_label = label;
clear input; clear label

%Make pointer where the end of the high pass are located
end_high = k;
for i = 1:required_iterations
      
    %We need a function here which computes intra and uncovered pixels from
    %the label
    [uncovered] = compute_uncovered_pixels(low_label, original_D, round_param, k, i);
    
    %Have an additional test, to test whether the intra pixels can be
    %placed in the low pass subband - the label must also be updated in
    %this case       
    [intra, uncovered, low_label, low] = move_pixels_into_different_frames(uncovered, original_D, i, k, round_param, low_label, low);
    
    [low, low_label, high, high_label, uncovered, motion_Vect_buffer] = lifting_view_haar_1_decomposition(low, low_label, D, intra, round_param);   
    
    %Apply forward prediction to the data - disoccluded data is predicted
    %from the subsequent frame
    %[high, intra] = forward_prediction(low, low_label, high, high_label, covered, D, round_param);   
    
    [q,w, length_high] = size(high);
    
    begin_high = end_high - length_high+1;
    %Place high into their correct position at the output
    output_dwt(:,:,begin_high:end_high) = high;
    uncovered_pixels(:,:,begin_high:end_high) = uncovered;
    intra_pixels(:,:,begin_high:end_high) = intra;
    motion_Vect(begin_high:end_high) = motion_Vect_buffer;
    
    final_label_location(begin_high:end_high) = downsample(location,2,1);
    output_label_dwt(:,:,begin_high:end_high) = high_label;
    
    end_high = begin_high -1;
    location = downsample(location,2);
    D = 2*D;
end

output_dwt(:,:,1:length(low(1,1,:))) = low;
final_label_location(1:length(location))=location;

output_label_dwt(:,:,1:length(low_label(1,1,:))) = low_label;


end

