clear;

%%
fs = 48000;
input_indices = 1:24;
num_channels = numel(input_indices);
blockSize = .2*fs;
t = (0 : blockSize-1) / fs;
n_max_blocks = 3;
fifo = BlockBuffer(blockSize, num_channels, n_max_blocks);

%% initialize figure
data = zeros(num_channels, blockSize);
figure;
subplot(2,1,1);
h1 = plot(t, data');
xlabel('Time [s]');
ylabel('Pressure [Pa]');
subplot(2,1,2);
h2 = plot(t, sum(data, 1));
xlabel('Time [s]');
ylabel('Pressure [Pa]');

%% open connection to MCDrec
mcdmex('open', '10.0.0.4', input_indices-1, 5*fs);

%% Start acquisition
mcdmex('start');

delays = zeros(num_channels, 1);
delays = delays - min(delays);

%% Processing loop
try
    while true
        data = mcdmex('read', blockSize);
        status = mcdmex('status');

        fifo.push(data');
        p = fifo.getBlocks();

        disp(status(:)');

        x = zeros(blockSize, 1);
        for c = 1 : num_channels
            t0 = (-blockSize : 2*blockSize-1)';
            p0 = p(1:3*blockSize,c);
            ti = (0:blockSize-1)' - delays(c)*fs;
            x = x + interp1(t0, p0, ti, 'linear');
        end

        for c = 1 : num_channels
            set(h1(c), 'yData', p(blockSize + (1:blockSize), c));
        end
        set(h2, 'yData', x);

        drawnow();
    end
catch E
end

%% Stop acquisition
mcdmex('stop');

%% Close connection
mcdmex('close');
