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


fName = 'test_pw.dat';             % file name
rmic = 0.1;
micArray = spherical_design('File','firthenmike.dat',rmic);
%micArray = spherical_design('Design',482,'T',rmic);

fig = figure;
hp = micArray.plot_voronoi;
hold on
C = colormap('parula');
%%
fs = 48000;
inputIndices = 1:size(micArray.x0,1);
blockSize = 4096;

numChannels = length(inputIndices);
fid = fopen(fName, 'wb');
fwrite(fid, numChannels, 'uint');
fwrite(fid, inputIndices, 'uint');
fwrite(fid, blockSize, 'uint');

%%
thetaPw = [pi/2,pi/2];

f0 = 1000;
N  = 30;
SphMx = getSpherHarmMx(pi/2-micArray.Phi0(:,2),micArray.Phi0(:,1),N,'real');
Amn = getSpherHarmMx(thetaPw(1),thetaPw(2),N,'real');
Nf = blockSize;
[~, Hrad] = get_pw_scat_filters( rmic, N, fs, Nf );
h = ifft(Hrad,[],1,'symmetric');
filter_scat = radial_filter_bank(N,h,blockSize);

%%

cnt = 0;
try
    while true
        t = (0:blockSize-1)'/fs + cnt*blockSize/fs;
        cnt = cnt+1;
        s_in = sin(2*pi*f0*t);
        s_in = randn(length(t),1);
        psiIn = s_in.*Amn;
        psiTotal = filter_scat.filter(psiIn);
        data = (SphMx*psiTotal');

        M = max(max(abs(data)));
        for i = 1 : size(micArray.x0,1)
            set(hp(i), 'FaceColor', C(floor(255/M*max(abs(data(i,:)))),:));
        end

        drawnow();
        fwrite(fid, data, 'float');         % write data into file
    end
catch E
end

fclose(fid);
