
blocksize=2048;

args=argv();

if length(args) != 3
  printf('Usage: infile nframes outfile\n');
  printf('Remark: use nframes=-1 to read the full infile\n');
  exit(1)
end

[signal, samplerate, bits] = wavread(args{1});
signal = signal(:,1);

signallen = str2num(args{2});
if signallen < 0 || signallen > length(signal)
    signallen = length(signal);
end  

printf('read signal of length %d\n', length(signal));
printf('processing %d frames\n', signallen);

maxlevel=max(abs(signal))

output=[];

window=hanning(blocksize);

for start = 1:blocksize/2:signallen
    stop = start + blocksize - 1;

    block = zeros(blocksize,1);
    if stop > signallen
        stop = signallen;
    end
    block(1:stop - start + 1) = signal(start:stop);
    block = block .* window;
    freq_block = fft(block, blocksize)(1:blocksize / 2);

    % effect
    % for ex: freq_block(64:blocksize/2) = 0;

    block = real(ifft(freq_block, blocksize));
    if length(output) < start + blocksize - 1
        output(length(output) + 1: start + blocksize - 1) = 0;
    end
    output(start:start + blocksize - 1) += transpose(block);
end

output = transpose(output);

gain = maxlevel / max(abs(output));
printf('applying gain: %f\n', gain);
output = output * gain;

printf('writing output');
wavwrite(output, samplerate, bits, args{3});
