function [tbase, f0t, pvt] = pt_wrap(d, sr, outfile, dt, ptfn, rf0, verbose)
% pt_wrap(infile, outfile, dt, ptfn, rf0, verbose)
% pt_wrap(inlist, outlist, dt, ptfn, rf0, verbose)
% pt_wrap(d, sr, outfile, dt, ptfn, rf0, verbose)
%   Wrapper for generic pitch track functions.
%   Writes a pitch track for audio waveform in <infile> to 3-col
%   ascii file <outfile>, with each row [time f0_Hz p_vx].
%   Samples are regularly spaced every dt sec, possibly 
%   linearly interpolated from raw pitch track.
%   ptfn gives core pitch tracker, called as:
%   [t,f0,pvx] = ptfn(d,sr).
%   <rf0>, if present and nonzero, invokes the restore_f0 command
%   that attempts to replace missing fundamentals via a nonlinear
%   operation, e.g. for telephone band speech.
% 2013-02-02 Dan Ellis dpwe@ee.columbia.edu

if nargin < 2;  sr = []; end
if nargin < 3;  outfile = []; end
if nargin < 4;  dt = []; end
if nargin < 5;  ptfn = []; end
if nargin < 6;  rf0 = []; end
if nargin < 7;  verbose = []; end

if iscell(d)
  % shift/arrange input args
  inlist = d;
  outlist = sr;
  verbose = rf0;
  rf0 = ptfn;
  ptfn = dt;
  dt = outfile;

  if length(verbose) == 0; verbose = 0; end
  
  % recurse
  nin = length(inlist);
  tott = 0;
  tstart = tic;
  for i = 1:nin
    if verbose
      disp(['Running ', func2str(ptfn), ' on ', inlist{i}, ' ...']);
    end
    [tbase{i},f0t{i},pvt{i}] = pt_wrap(inlist{i}, outlist{i}, ...
                                       dt, ptfn, rf0);
    tott = tott + tbase{i}(end);
  end
  clocktime = toc(tstart);
  if verbose
    disp([num2str(nin),' files (', num2str(tott), ...
          ' sec) processed in ',sprintf('%.1f',clocktime),' sec', ...
          ' = ',sprintf('%.3f',clocktime/tott),' x RT']);
  end

else

  % regular (single-file) call
  
  infile = [];
  if ischar(d)
    % We were passed a file name instead of data
    % shift args down
    verbose = rf0;
    rf0 = ptfn;
    ptfn = dt;
    dt = outfile;
    outfile = sr;
    % and the infile is
    infile = d;
  end

  if ~isempty(infile)
    targetsr = 8000;
    forcemono = 1;
    [d,sr] = audioread(infile,targetsr,forcemono);
  end

  % maybe run restoref0
  if length(rf0) > 0 && rf0 > 0
    d = restore_f0(d,sr);
  end
  
  % actual defaults
  if isempty(dt);  dt = 0.010; end
  if isempty(ptfn);  ptfn = @ptrack_wu; end

  [tt,f0,pvx] = ptfn(d,sr);

  f0(find(isnan(f0))) = 0;
  pvx(find(isnan(pvx))) = 0;

  % Propagate voicing decision to pitch values (if not already...)
  f0(find(pvx < 0.5)) = 0;

  % interpolate
  maxt = max(tt);
  tbase = 0:dt:maxt;

  f0t = interp1(tt,f0,tbase,'nearest');
  pvt = interp1(tt,pvx,tbase,'nearest');

  if ~isempty(outfile)
    % write output file
    pt_write(outfile, tbase, f0t, pvt);
  end

end
