function resample_and_offset(infile, outfile, a, b)
% resample_and_offset(infile, outfile, a, b)
%   Resample and offset an audio file by specified parameters.
%   You can think of it as where in the output the input point goes
%     t_input  = (1+a) * t_output + b
%   Or equivalently:
%     t_output = (t_input - b) / (1+a)
%   so if a > 0, the file gets sped up, and the output is shorter
%   than input.
%   Equivalent to sox:
%    b < 0 : sox infile outfile speed <1+a> delay <-b/(1+a)>
%    b > 0 : sox infile outfile speed <1+a> trim <b/(1+a)>
%   Note: sox applies delay separately from speed, i.e. input time
%   0 occurs at output time <del> regardless of speed
%   Trim is applied *before* speed, so trimming off 0.5 sec, then
%   scaling by 0.99 loses 0.5 sec of original sound, or 0.505 of
%   what sound would have been after scaling.
% 2013-12-19 Dan Ellis dpwe@ee.columbia.edu Fixed to properly match sox

% adapted from deskew.m
% re-read targ
[dr,sr] = audioread(infile,0,0,max(0,b));
if b < 0
  % prepad silence
  dr = [zeros(round((-b)*sr),size(dr,2));dr];
  % note: this silence will be stretched by (1+a) below, so use the
  % original pad
end
  
% Apply time scaling via resampling
% Find p/q s.t. p/q ~= a
% approx 1 part in 1/(a-1)
p0 = floor(1/abs(a));
if p0 < 2^15
  % exhaustive search for pair of integers closest to desired rate
  p = p0:(2^15);
  q = round(p./(1+a));
  er = (1 + a - p./q); 
  [ee,xx] = min(abs(er));
  disp(['Resampling ratio: ',sprintf('%d/%d=%.6f',p(xx),q(xx),p(xx)/q(xx))]);
  for i = 1:size(dr,2)
    dmr(:,i) = resample(dr(:,i),q(xx),p(xx));
  end
  dr = dmr;
end
audiowrite(dr,sr,outfile);
