clear;

%% Arrangement
n_mic = 48;                 % Number of microphones
d_mic = 6e-2;               % Distance between microphones [m]

n_arm = n_mic / 4;          % Number of microphones in one arm

% Position of the microphones
x_mic = [ ...
    [-((0:n_arm-1).'+0.5)*d_mic, zeros(n_arm,1), zeros(n_arm,1)];
    [zeros(n_arm,1), ((0:n_arm-1).'+0.5)*d_mic, zeros(n_arm,1)];
    [((0:n_arm-1).'+0.5)*d_mic, zeros(n_arm,1), zeros(n_arm,1)];
    [zeros(n_arm,1), -((0:n_arm-1).'+0.5)*d_mic, zeros(n_arm,1)];
];

% Source position
x_src = [3 1 -5];

%% Plot the arrangement
figure;
plot3(x_mic(:,1), x_mic(:,2), x_mic(:,3), 'ro');
hold on
plot3(x_src(:,1), x_src(:,2), x_src(:,3), 'b*');
axis equal;
%% Compute the received signal
fs = 48000;                 % Sampling frequency [Hz]
f0 = 2000;                  % Source frequency [Hz]
c = 343;                    % Speed of sound [m/s]
T_sim = 0.1;                % Simulated time [s]
n_samp = round(T_sim*fs);   % Number of samples [-]

% Time scale
t = (0 : n_samp-1).' / fs;
% Relative position of source and microphones [m]
dist = bsxfun(@minus, x_mic, x_src);
% Distance between source and microphones [m]
dist = sqrt(dot(dist, dist, 2));
% Time delay for each microphone [s]
delays = dist/c;

% Signal emitted by the source
p_src = sin(2*pi*f0*t);

% Create the received signal
p_rec = zeros(n_samp, n_mic);
for i_mic = 1 : n_mic
    p_rec(:, i_mic) = interp1(t, ...
        p_src, t - delays(i_mic), 'linear', 0);
end

%% Plot the received signal
figure;
plot(t, p_rec);
xlabel('Time [s]');
ylabel('Microphone signals [-]');
%% Compute acoustical focusing
x_foc = [2, 4, -5];         % Focal point

% Compute distance between focal point and microphones
dist = bsxfun(@minus, x_mic, x_foc);
dist = sqrt(dot(dist, dist, 2));
% Time delays
delays = dist/c;

% Compensate for the delays in focusing
p_foc = zeros(n_samp, 1);
for i_mic = 1 : n_mic
    p_foc = p_foc + interp1(t, p_rec(:, i_mic), ...
        t + delays(i_mic), 'linear', 0);
end
p_foc = p_foc / n_mic;

%% Plot the focused signal
figure;
plot(t, p_foc);
xlabel('Time [s]');
ylabel('Focused signal [-]');
