function f0 = f0detection(mX, fs, ploc, pmag, ef0max, minf0, maxf0) 
% Fundamental frequency detection function 
% mX: magnitude spectrum, fs: sampling rate, ploc, pmag: peak loc and mag, 
% ef0max: maximim error allowed, minf0: minimum f0, maxf0: maximum f0 
% f0: fundamental frequency detected 
N = length(mX)*2;                                 % size of complex spectrum 
nPeaks = length(ploc);                           % number of peaks 
f0 = 0;                                           % initialize output 
if(nPeaks>3)                    % at least 3 peaks in spectrum for trying to find f0 
   nf0peaks = min(50,nPeaks);                     % use a maximum of 50 peaks 
   [f0,f0error] = TWM(ploc(1:nf0peaks),pmag(1:nf0peaks),N,fs,minf0,maxf0); 
   if (f0>0 && f0error>ef0max)                   % limit the possible error by ethreshold 
     f0 = 0; 
   end 
end; 
