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


function [optimum_rate, optimum_distortion, optimum_pass] = choose_optimum_rate_v2(rate, distortion, pass, lambda)


lagrange_cost = distortion + rate*lambda;
ind = find(lagrange_cost == min(lagrange_cost));
ind = ind(1);

optimum_rate = rate(ind);
optimum_distortion = distortion(ind);
optimum_pass = pass(ind);

%{
%Calculate gradient of input data

grad = zeros(1, length(rate)-1);
for i = 1:length(rate) - 1 
    %grad(i) = -(distortion(i) - distortion(i+1)) / (rate(i) - rate(i+1)) ;
    grad(i) = (distortion(i) - distortion(i+1))/(rate(i+1)-rate(i));
end

%Choose minimum gradient, such that grad(i) is strictly larger than lamda
%Find points where gradient is larger than lamda, and then find the minimum
%of those points. 
buffer = min(grad(grad>lamda));
if ~isempty(buffer)
    opt_coord = find(grad == min(grad(grad>lamda)));

    if ndims(opt_coord) > 1
        opt_coord = opt_coord(end);
    end
    optimum_rate = rate(opt_coord+1);
    optimum_distortion = distortion(opt_coord+1);
    optimum_pass = pass(opt_coord+1);
else
    opt_coord = 1;
    optimum_rate = rate(opt_coord);
    optimum_distortion = distortion(opt_coord);
    optimum_pass = pass(opt_coord);
end
%}
  