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

function [psnr_distortion, output_rate, total_segmentation_cost, output_lambda] = encode_data(data_name, data_seg_parameters, bpp, lossless_seg_rate)

load(data_seg_parameters);
%Load R_tot and R_seg, which specifies how many bits should be allocated 
%to the segmentation and texture
[R_tot, IX] = sort(R_tot);
R_seg = R_seg(IX);

%find r,c,k parameters of the input data
load(data_name);
[r,c,k] = size(in);
clear in label D;

psnr_distortion = zeros(1,length(bpp));
output_rate = zeros(1,length(bpp));
total_segmentation_cost = zeros(1,length(bpp));
output_lambda = zeros(1,length(bpp));


for l = 1:length(bpp)
    encoding_rate = bpp(l)*r*c*k;
   
    %linearly interpolate the segmentation rate
    index_1 = find(R_tot <= encoding_rate);
    if ~isempty(index_1)
        index_1 = index_1(end);
    end
    
    index_2 = find(R_tot >= encoding_rate);
    if ~isempty(index_2)
        index_2 = index_2(1);
    end
    
    %Linearly interpolate segmentation rate
    if ~isempty(index_1) && ~isempty(index_2)       
        segmentation_rate = R_seg(index_1) + (R_seg(index_2) - R_seg(index_1))*((encoding_rate - R_tot(index_1))/(R_tot(index_2) - R_tot(index_1)));       
    end
    
    %if encoding rate is larger than the available rate encode at the
    %encode losslessly
    if isempty(index_2)
        %segmentation_rate = R_seg(index_1);
        segmentation_rate = 100e3; %i.e. losslessly encode segmentation
    end
    
    %linearly interpolate from the previous pair
    if isempty(index_1)
        segmentation_rate = R_seg(1) - (R_seg(2) - R_seg(1))*((R_tot(1) - encoding_rate)/((R_tot(2) - R_tot(1))));
    end
    
    %remove this comment after
    %if segmentation_rate < lossless_seg_rate*0.85
        [psnr_distortion(l), output_rate(l), total_segmentation_cost(l), output_lambda(l), information_data] = run_method('ceil', data_name, bpp(l), segmentation_rate);
    %end
        
    save current_results2;
end

end