function s = ebr (fg, bg, offset, fgScale)
% Computes the EBR of fg relatively to bg
% If the optional argument offset is provided, will compute the EBR of fg
% at position 'offset' in bg
% If the optional argument fgScale is provided, the SNR of fg*fgScale over
% bg will be returned instead

% 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<=2) offset=1; end
if (nargin<=3) fgScale=1; end

endPosBg = min(offset+length(fg)-1, length(bg));
endPosFg = endPosBg-offset+1;

aFg = sqrt(sum((fg(1:endPosFg).*fgScale).^2)/endPosFg); %RMS
aBg = sqrt(sum(bg(offset:endPosBg).^2)/endPosFg); %RMS

s = 20*log10(aFg/(aBg+.001));
%fprintf('fg from position %i to %i, %i samples, scale = %f, bg pow = %f, fg pow = %f, snr = %f\n', offset, endPosBg, endPosFg, fgScale, aBg, aFg, s);
end
