function [Sbin,fbin] = binavespec(freq,S,N,Nf)
% Function for bin-averaging spectra to logarithmically evenly spaced bins
% INPUT:  freq = frequency vector (Hz)
%         S = spectra
%         N = amount of bins
%         Nf = amount of spectra values in the beginning (low frequencies) over which bin-averaging is not done
% OUTPUT: Sbin = bin-averaged spectra
%         fbin = frequency vector
%
% Used in Peltola et al. (2021): "The high frequency response correction 
% of eddy covariance fluxes. Part 1: an experimental approach and its 
% interdependence with the time-lag estimation" submitted to Atmospheric 
% Measurement Techniques.
%
% O. Peltola (09/2020)
% olli.peltola@fmi.fi

    freq3 = [freq(2:Nf+1)' logspace(log10(freq(Nf+2)),log10(freq(end)),N+1)]';
    freq2 = [freq3(1:end-1) freq3(2:end)];
    Sbin = NaN(size(freq2,1),1);                    
    for j=1:size(freq2,1)
        Sbin(j) = nanmean(S(freq>=freq2(j,1) & freq<=freq2(j,2)));
    end
    fbin = mean(freq2,2);

end

