function scale = adjustScaleForEBR (fg, bg, offset, targetEBR, snrType, eps)
% Computes the value of 'scale' such that fg*scale has a given EBR
% relatively to bg at position 'offset'.
% ebrType is used to select what kind of EBR should be considered:
% 1 - standard temporal ebr over whole length of sample
% 2 - max of standard temporal ebr over 1/4s windows
% 3 - more to come ?
% eps is the epsilon used to check for convergence; optional, defaults to
% 0.01

% This program was written by Mathias Rossignol & Grégoire Lafay
% is Copyright (C) 2015 IRCAM <http://www.ircam.fr>
%
% This program is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by the Free
% Software Foundation, either version 3 of the License, or (at your option)
% any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
% for more details.
%
% You should have received a copy of the GNU General Public License along
% with this program.  If not, see <http://www.gnu.org/licenses/>.

if (nargin == 5) eps = 0.01; end
%if (targetSNR <= 0) targetSNR = exp(targetSNR); end
prevScale = 1;
scale = 1;
ebrFunc=@ebr;
if (snrType==2) ebrFunc=@maxWindowEBR; end
count = 0;
while (ebrFunc(fg, bg, offset, scale) > targetEBR && count < 100)
    prevScale = scale;
    scale = scale/2;
    count = count+1;
end
if (count == 100)
    msg = ['Max count, stage 1, scale = ', num2str(scale), ' - ', num2str(ebrFunc(fg, bg, offset, scale)), ' - ', num2str(ebrFunc(fg, bg, offset, prevScale)), ' - ', num2str(ebrFunc(fg, bg, offset, 1))];
    error(msg)
end
count=0;
while (ebrFunc(fg, bg, offset, scale) < targetEBR && count < 100)
    prevScale = scale;
    scale = scale*2;
    count = count+1;
end
if (count == 100)
    msg = ['Max count, stage 2, scale = ', num2str(scale)];
    error(msg)
end
count=0;
if (scale<prevScale)
    a = scale;
    b = prevScale;
else
    a=prevScale;
    b=scale;
end
delta = ebrFunc(fg, bg, offset, (a+b)/2) - targetEBR;
while (abs(delta) > eps && count < 100)
    if (delta>0)
        b = (a+b)/2;
    else
        a = (a+b)/2;
    end
    delta = ebrFunc(fg, bg, offset, (a+b)/2) - targetEBR;
    count = count+1;
end
if (count == 100)
    msg = ['Max count, stage 3, scale = ', num2str(a)];
    error(msg)
end
scale = (a+b)/2;
end