function y = shiftpitch(x, shamt, window, overlap)
% y = shiftpitch(x, shamt, window, overlap)
% x is the input signal- column vector
% shamt is the shift amount.  1 = no shift, 2 = shift sharp 1 octave, .5 =
% shift flat one octave.
% window is the windowing function to apply before fft
% overlap is the percent overlap factor.  example: overlap = 4: 2 adjacent
% windows overlap by %75
% note that the length of window must be a multiple of overlap.
% y is the resulting signal

n = length(x);
winsize = length(window);
blocksize = (winsize / overlap);

%since this is intended to be a realtime effect, we will 'cut off' the end.
%numblocks is the number of blocks we perform an fft on.
%this discards any block that is less than blocksize, and then discards
%blocks so that we stop when window no longer fits across our data.
numblocks = floor(n / blocksize) - overlap + 1;
y = zeros(blocksize * numblocks, 1);

for i = 1:numblocks
    start = (blocksize*(i-1)) + 1;
    stop = (blocksize*( i-1 + overlap ));
    %thought on windowing, because we are adding arbitrary frequencies,
    %where do we want to apply the window?  We may end up with very high
    %frequencies in the final result.  Do we need to apply window at the
    %end?
    a = x( start : stop ) .* ones(winsize, 1); %current sample to do fft on
    f = fft(a); %frequency domain magnitude
    phase = angle(f);
    mag = abs(f);
    
    %next we need to shift- as a start we will just keep all of the phases
    %as 0.  We will round to the closest frequency as a first attempt
    %f2 = zeros(1, winsize); %x was purely real, only need to do on half
    %and then fix up before using ifft
    f2prime = zeros(floor(winsize/2), 1);
    fprime = mag(2: ceil( (winsize / 2) + .5));
    for k = 1:length(fprime)
        bin = round(k * shamt);
        if (bin >= 1 && bin <= length(fprime) )
            f2prime(bin) = f2prime(bin) + fprime(k);
        end
    end
    %size(fprime)
    fflip = flipud(f2prime);
    if (mod(length(fprime), 2) == 0)
        fflip = fflip(2:length(fflip));
    end
    f2 = [mag(1); f2prime; fflip];
    f2 = f2 .* exp(j .* phase);
    
    b = real(ifft(f2)) .* window;
    y(start:stop) = b;
end