clear
close all
addpath(genpath('Data'));
addpath(genpath('Functions'));
addpath(genpath('Objects'));

fs = 48000;
blockSize = .3*fs;
freq = (0:blockSize-1)'/blockSize*fs;
omega = 2*pi*freq;
c = 343;
k = omega/c;
t = (0:blockSize-1)'/fs;

N = 3;

rmic = 0.1;
micArray = spherical_design('Design',26,'T',rmic);
micArray.set_dummy_ixs([25;26]);

h_inv_scat = get_inv_scat_filters( rmic, N, fs, blockSize );
filter_inv_scat = radial_filter_bank(N,h_inv_scat,blockSize);
%%
fig =  figure('units','normalized','outerposition',[0 0 1 1]);

hp = micArray.plot_voronoi;
C = colormap('parula');

%%
outputDevice = audioDeviceWriter;
set(outputDevice,'SampleRate',fs);
set(outputDevice,'BufferSize',blockSize);
%%

%fName = 'fifi.dat';             % file name
%fid = fopen(fName, 'r');

%% Start acquisition
numChannels = 24;
inputIndices = 1:numChannels;

mcdmex('open', '10.0.0.4', inputIndices-1, 5*fs);
mcdmex('start');

%numChannels = fread(fid, 1,'uint');
%inputIndices = fread(fid, numChannels,'uint');
%dataTotal = zeros(blockSize,numChannels+2);
n = 0;
try
    while true
        n = n+1;
        data = mcdmex('read', blockSize)';
        status = mcdmex('status');
        disp(status);

     %   data = fread(fid, [numChannels, blockSize], 'float')';

        data = micArray.interpolate_dummy_nodes(data);
        dataTotal((n-1)*blockSize+1:n*blockSize,:) = data;

        drms = 20*log10(rms(data, 1)/2e-5);
        lims = [10 70];
        cidx = (drms - lims(1)) / diff(lims);
        cidx = floor(max(min(cidx, 1), 0) * 255) + 1;
        for i = 1 : 26
            set(hp(i), 'FaceColor', C(cidx(i),:));
        end
        drawnow();

    end
catch E
end

mcdmex('stop');
mcdmex('close');
%fclose(fid);