function Y = resample_in_parts(X, P, Q)
% Y = resample_in_parts(X, P, Q)
%      Y is returned as X resampled to a length P/Q * length of X.
%      This version processes in smaller blocks to save memory use.
% 2014-02-19 Dan Ellis dpwe@ee.columbia.edu

% P and Q are integers, so every block of Q samples from X delivers
% P samples to Y.
% Thus, we can divide X into exact multiples of Q, and it should
% all line up.

targetblock = 1e6;  % say

% How many blocks of Q can we do at once?
numQ = round(targetblock/Q);
numloops = ceil(length(X)/(numQ*Q));

done = 0;
Ydone = 0;
todo = length(X);
Y = zeros(ceil(length(X)*P/Q),1);

while todo > 0
  if done == 0; pad = 0; else pad = 1; end
  thistime = min((numQ+1)*Q, length(X)-done);
  nextX = X(done - pad*Q + [1:(thistime+pad*Q)]);
  Ypart = resample(nextX, P, Q);
  % Discard prepad
  Ypart = Ypart((pad*P+1):end);
  % Only keep the valid parts
  lYpart = min(length(Ypart), numQ*P);
  Y(Ydone + [1:lYpart]) = Ypart(1:lYpart);
  Ydone = Ydone + lYpart;
  % forget postpad when winding forward
  thistime = min(thistime, numQ*Q);
  done = done + thistime;
  todo = todo - thistime;
end
