function signal = timeStretch(x, R, Fs, winLen, hopFactor)
% x - input signal audio
% R - scale factor of the time axis
% Fs - Sample Rate of the incoming signal
% winLen - the length of the Hanning Window and the FFT size 
% hopFactor - factor by which the Hanning Window moves. hopFactor +
% [Window Overlap] = 1
% This is the traditional way that pitch shifting is done with the phase
% vocoder.  A more efficient way that doesn't envolve resampling is using
% peak detection and is described in the paper by Jean Laroche and Marc
% Dolson (see the bibliography for more details)

if nargin < 4
    winLen = 1024; %1024 is good length for most waves.
    hopFactor = 1/4; %1/4 for best reconstruction
elseif nargin < 5
    hopFactor = 1/4; %1/4 for best reconstruction
end

% a 75% window overlap needed for a smooth reconstruction.
% the integer is equal to 1-x%=hopFactor, 50% - 75% overlap is optimal which
% gives the vocoder the ability to handle fractional time scaling shifts 
% (fractions of the hamming window)
hopSize = winLen*hopFactor;

% invert R since the pitch is inversely proportional to the time scale
% factor needed.  
R = 1/R;

% scale by a factor of 2/3 to adjust for the effects of the hamming window.
% Do not know the proof of this, it is borrowed from the phase vocoder
% created by professor Dan Ellis
scale = 2/3;

% encode the signal using stft (using a hann window)
X = scale*encode(x, winLen, hopSize);

% Calculate the new time axis
sizeX = size(X,2)-2;
time = 0:R:sizeX; %step by the time scale, R

% Interpolate and create the neccessary effect
Xint = interpolate(X, time, hopSize);

% turn back into a waveform, inverse window and fft
signal = decode(Xint, winLen, hopSize)';