function  [dmix,dnoise] = mix_noise(dfclean, dnoise, srnoise, SNR)
%  dmix = mix_noise(dfclean, dnoise, srnoise, SNR);  
%      Take the (filtered) clean signal <dfclean>, repeat or trim noise
%      signal <dnoise> to the same length, then combine them to achieve a
%      resulting snr of <SNR> according to P.56 active level estimates.
% 2011-02-10 Dan Ellis dpwe@ee.columbia.edu

% If noise is too short, replicated it, but use cosine cross-fades
xfadetime = 0.050;
xfadesamps = round(srnoise*xfadetime);
xfadewin = 0.5*(1+cos([0:(xfadesamps-1)]/xfadesamps*pi))';

while length(dnoise) < length(dfclean)
  lnoise = length(dnoise);
  % copy everything except overlap part onto end
  dnoise(end+[1:lnoise-xfadewin]) = dnoise((xfadewin+1):end);
  % rewrite the overlap portion with the crossfade
  dnoise((lnoise-xfadesamps+1):lnoise) = dnoise(end-xfadesamps+1:end).*xfadewin ...
      + dnoise(1:xfadesamps).*(1-xfadewin);
end

% replicate or trim noise
dnoise = dnoise(1+rem([0:length(dfclean)-1],length(dnoise)));

% mix
fcleanlev = activlev(dfclean, srnoise);
noiselev = activlev(dnoise, srnoise);
fcleangain = sqrt(noiselev/fcleanlev)*(10^(SNR/20));
dmix = dnoise + fcleangain * dfclean;
