function signal = pitchShift(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.  For low sample rates a lower WinLen may be used
    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;

% encode the signal using stft (using a hann window)
X = 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)';

% resample at factor of the pitch shift R to correct for the number of
% samples added or removed during the time scale process.  Since R was 
% inverted above, it is divided instead of multiplied
signal = RESAMPLE(signal,Fs,floor(Fs/R));

% the resampling process does bring in a slight distortion to the signal
% but it not noticeable.