function[pitchvalue,pitcherror,isHarm]=pitchDetection(r,N, ...
SR,nPeaks,iftloc,iftval)
% function[pitchvalue,pitcherror,isHarm]= ...
% pitchDetection(r,N,SR,nPeaks,iftloc,iftval)
%
%==> pitch detection function, using the Two-Way Mismatch
% algorithm (see TWM.m)
%
% data:
% r: FFT magnitude
% N: size of the FFT
% SR: sampling rate
% nPeaks: number of peaks tracked
% iftloc, iftval: location (bin) and magnitude of the peak
%--- harmonicity evaluation of the signal
highenergy = sum(r(round(5000/SR*N):N/2)); % 5000 Hz to SR/2 Hz
lowenergy = sum(r(round(50/SR*N):round(2000/SR*N)));
% 50 Hz to 2000 Hz
isHarm = max(0,(highenergy/lowenergy < 0.6));
if (isHarm==1) %-- 2-way mismatch pitch estimation when harmonic
npitchpeaks = min(50,nPeaks);
[pitchvalue,pitcherror] = ...
TWM(iftloc(1:npitchpeaks),iftval(1:npitchpeaks),N,SR);
else
pitchvalue = 0;
pitcherror = 0;
end;
%--- in case of two much pitch error,
% signal supposed to be inhamonic
isHarm = min (isHarm,(pitcherror<=1.5));