function [layer_stack, segmentation_cost] = quad_tree_lossy_segmentation(layer_stack, target_rate)

%Test lossless segmentation encoding cost
number_of_layers = length(layer_stack(1,1,:));

w = cd;
cd('../Original QuadTree_EncDec_v9');

%addpath(w);

%initialize
%min_lambda = 1;
%max_lambda = 1.1;
min_lambda = 0.01;
max_lambda = 20;
middle_lambda = (min_lambda + max_lambda)/2;
iteration = 0;

%evaluate initial cost
[total_segmentation_cost{1}, layer_stack_buffer{1}] = evaluate_segmentation_cost(layer_stack, number_of_layers, min_lambda);
[total_segmentation_cost{2}, layer_stack_buffer{2}] = evaluate_segmentation_cost(layer_stack, number_of_layers, middle_lambda);
[total_segmentation_cost{3}, layer_stack_buffer{3}] = evaluate_segmentation_cost(layer_stack, number_of_layers, max_lambda);

if ((target_rate > total_segmentation_cost{1}) || (target_rate < total_segmentation_cost{3}))
    if(target_rate > total_segmentation_cost{1})
        segmentation_cost = total_segmentation_cost{1};
        layer_stack = layer_stack_buffer{1};
    else       
        segmentation_cost = total_segmentation_cost{3};
        layer_stack = layer_stack_buffer{3}; 
    end

else

    while (iteration < 3 && abs(target_rate-total_segmentation_cost{2}) > target_rate*0.03)
        abs(target_rate-total_segmentation_cost{2})
        pause(2);
        if total_segmentation_cost{2} > target_rate                                   
            min_lambda = middle_lambda;       
            middle_lambda = (min_lambda + max_lambda)/2;              
            total_segmentation_cost{1} = total_segmentation_cost{2};             
            layer_stack_buffer{1} = layer_stack_buffer{2};    
        else                      
            max_lambda = middle_lambda;      
            middle_lambda = (min_lambda + max_lambda)/2;      
            total_segmentation_cost{3} = total_segmentation_cost{2};       
            layer_stack_buffer{3} = layer_stack_buffer{2};                   
        end        
        [total_segmentation_cost{2}, layer_stack_buffer{2}] = evaluate_segmentation_cost(layer_stack, number_of_layers, middle_lambda);   
        iteration = iteration + 1;
        iteration
    end        
    layer_stack = layer_stack_buffer{2};
    segmentation_cost = total_segmentation_cost{2};
    segmentation_cost = number_of_layers*16 + segmentation_cost;
end
cd(w);
