% Compute SNR_dB from waveform averaged sweeps
% Input:  avgData ... data structure holding waveform averaged sweeps 
%         Nsweep  ... vector holding sweep steps 
%         fsample ... sample rate
% Output: SNR     ... singal-to-noise ratio in [dB]
% Author G. Fischer
% -------------------------------------------------------------------------
function [SNR] = getSNR4MethX(avgData,Nsweep,fsample)
  %
  nEvo=avgData.ncl;                % number evoked samples in frame
  nA = round(0.015*fsample);       % response window TW index left boarder
  nB = round(0.025*fsample);       % response window TW index right boarder
  nC = nEvo-round(0.08*fsample);   % noise window TN index left boarder
  nD = nEvo-round(0.02*fsample);   % noise window TN index right boarder
  % compute SNR at n steps
  for n=1:size(Nsweep,2)              
    np = Nsweep(1,n);              % np ... step index 
    S = rms(avgData.mtx(np,nA:nB));% rms of sigma (signal+noise)
    B = rms(avgData.mtx(np,nC:nD));% rms of background
    S2=S^2; B2=B^2;                % convert rms to power
    R=(S2-B2)/B2;                  % ratio R = linear SNR
    if R>1                         % more signal than noise?
       SNR(1,n)=10*log10(R);       % compute SNR_dB
    else
       SNR(1,n)=0;                 % too much noise -> set SNR_dB to zero
    end % if
  end % for n
end % function

