function y = distort(x, window, overlap, distfn)
% y = distort(x, window, overlap, distfn)
%takes in an input x, distorts it, output is y
%window is a column vector that windows the output of each fft block
%the size of each window determines the length of the fft
%overlap is the overlapping factor between each window
%  in other words the number of windows occuring after this window that
%  will overlap.
%distfn is the distortion function to apply to each frame.
%it should take in the magnitude of frequencies vector and return the
%distorted magnitude of frequencies vector.
%The code is based on my shiftpitch function

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 ));
    
    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);
    
    %At this point we should apply our distortion effect
    %We are interested only in half of the fft and will recreate
    %the vector later to use ifft.
    fprime = mag(2:ceil((winsize/2) + .5));%our fft magnitudes
    f2prime = distfn(fprime);    
    %end distortion effect
    
    %recreate a symmetric vector for ifft to result in a real signal
    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);
    
    
    %select phases somehow.
    %ideas: relate to phases of input/random phases/hardcoded phases as 0
    %or j.
    %for a short enough window the phase should not affect what we hear
    %we do, however, need to make sure that interferance does not occur
    %between windows.
    
    b = real(ifft(f2)) .* window;
    y(start:stop) = b;
end