clear;
TIME = 10;
SIZE = 1024;
FS = 48000;
KEY ='A'; % not used
OCTAVES = 8;
HOP = SIZE/4;

[pitchesHz, majHz, minHz] = precalculateNotes(OCTAVES, KEY);

phi = zeros(SIZE/2,1);
psi = zeros(SIZE/2,1);
buffer_in_1 = zeros(HOP,1);
buffer_in_2 = zeros(HOP,1);
buffer_in_3 = zeros(HOP,1);
buffer_in_4 = zeros(HOP,1);
buffer_out_1 = zeros(HOP,1);
buffer_out_2 = zeros(HOP,1);
buffer_out_3 = zeros(HOP,1);
buffer_out_4 = zeros(HOP,1);

deviceReader = audioDeviceReader(FS, HOP, 'Driver', 'ASIO', 'Device', ...
'Focusrite USB ASIO');
deviceWriter = audioDeviceWriter('SampleRate', FS, 'BufferSize', HOP, ...
'Driver', 'ASIO', 'Device', 'Focusrite USB ASIO');                                
fileWriter = dsp.AudioFileWriter('output.wav','SampleRate',deviceReader.SampleRate);
fileWriter2 = dsp.AudioFileWriter('input.wav','SampleRate',deviceReader.SampleRate);
tic
while toc < TIME*10
    buffer_in_1 = buffer_in_2;
    buffer_in_2 = buffer_in_3;
    buffer_in_3 = buffer_in_4;
    buffer_in_4 = deviceReader();
    
    toProcSignal = [buffer_in_1;buffer_in_2;buffer_in_3;buffer_in_4];

    [procSignal,phi,psi] = autotune(toProcSignal, phi, psi, minHz, FS);
    
    reproducSignal = buffer_out_1;
    deviceWriter(reproducSignal);
    fileWriter(reproducSignal);
    fileWriter2(buffer_in_1);
    
    buffer_out_1 = buffer_out_2 + procSignal(1:HOP);
    buffer_out_2 = buffer_out_3 + procSignal(HOP+1:2*HOP);
    buffer_out_3 = buffer_out_4 + procSignal(2*HOP+1:3*HOP);
    buffer_out_4 = procSignal(3*HOP+1:SIZE);
end

release(deviceReader);
release(deviceWriter);
release(fileWriter);
