function [t,f0,pvx] = ptrack_getf0(d,sr)
% [t,f0,pvx] = ptrack_getf0(d,sr)
%    Run the get_f0 pitch tracker on the waveform d (at sampling
%    frequency sr).
%    Returns three 1D vectors.  
%      t is the sample times at which pitches are estimated 
%          (typically uniformly spaced every 0.010 sec).  
%      f0 is the corresponding pitch value in Hz (which can be 
%          zero for unvoiced frames). 
%      pvx is the corresponding probability of voicing for each
%          frame (between 0 and 1).  Generally, a threshold of 0.5
%          is the best guess for actual voiced-unvoiced threshold.
%    This is supposed to be a generic framework for pitch trackers,
%    but in this case we'll run get_f0 (as a binary).
% 2013-01-31 Dan Ellis dpwe@ee.columbia.edu

%persistent getf0
%if isempty(getf0)
%  [r,getf0] = system('which get_f0_dpwe');
%  if r ~= 0; error(getf0); end
%end
getf0dir = './get_f0_snd-v0_0/';
getf0 = [getf0dir, 'get_f0_snd.', computer('arch')];
getf0params = [getf0dir, 'get_f0_params'];

tmpfni = [tempname(),'.wav'];
wavwrite(d,sr,tmpfni);
tmpfno = [tempname(),'.txt'];

mysystem([getf0, ' -P ', getf0params, ' ',tmpfni, ' ', tmpfno]);

dat = textread(tmpfno);
% columns are pitch, pvx, rmsE, acg peak height
% pvx is always 0 or 1
%dt = 0.01;
%f0 = dat(:,1)';
%t = [0:length(f0)-1]*dt;
%pvx = dat(:,2)';

% New get_f0_snd outputs times too
t = dat(:,1)';
f0 = dat(:,2)';
pvx = dat(:,3)';
% ignore 4th (rms level) and 5th (max autoco peak) columns

system(['rm ',tmpfni]);
system(['rm ',tmpfno]);



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function w = mysystem(cmd)
% Run system command; report error; strip all but last line
[s,w] = system(cmd);
if s ~= 0 
  error(['unable to execute ',cmd,' (',w(1:end-1),')']);
end
% Keep just final line
w = w((1+max([0,findstr(w,10)])):end);
% Debug
%disp([cmd,' -> ','*',w,'*']);
