clear
close all

addpath(genpath('Data'));
addpath(genpath('Functions'));
addpath(genpath('Objects'));

load garazs_2025_2.mat
load hrtfSet.mat
fs = 1 / mean(diff(t));
h = h(1:3*fs,:);

%%
N = 3;
rmic = 0.1;
micArray = spherical_design('File','firthenmike.dat',rmic);

rls = mean(hrtfArray.Phi0(:,3));

Nf = 4096;
[~, HHOA] = get_hoa_filters( rmic, rls, N, fs, Nf );
[~, H_reg] = get_regularization_filters( N, Nf, fs, [90,680,1650,2600]'*(0.042/rmic) );
freq = (0:Nf-1)'/Nf*fs;

HHOA = HHOA.*H_reg;
hHOA = ifft(HHOA,[],1,'symmetric');

virtualArray = spherical_design('Design',1302,'T',rls);
Ymx = virtualArray.get_SH_mx;


[ x_ls, theta_ls, N_dummy ] = get_loudspeaker_layout( 1, [0 0 0], '5.1');

%[ls_groups, ~] = findLsTriplets([hrtfArray.Phi0(:,1) hrtfArray.Phi0(:,2) ]*180/pi);
[ls_groups, ~] = findLsTriplets([theta_ls(:,1), pi/2-theta_ls(:,2) ]*180/pi);
layoutInvMtx = invertLsMtx([theta_ls(:,1) pi/2-theta_ls(:,2) ]*180/pi, ls_groups);
gains3D = vbap([virtualArray.Phi0(:,1) virtualArray.Phi0(:,2)]*180/pi, ls_groups, layoutInvMtx);

D_vbap =  4*pi/size(virtualArray.x0,1)*gains3D'*Ymx;
%%
Psi_mic = micArray.SHT('pinv',h,N);

Psi_HOA  = zeros(size(Psi_mic));
for n = 0 : N
    for m = -n:n
        Psi_HOA(:,n^2+n+m+1) = conv( Psi_mic(:,n^2+n+m+1), hHOA(:,n+1),'same');
    end
end
%%
hLs = (D_vbap*Psi_HOA')';

%%
[input,fs_in] = audioread("Data\soundSamples\GitL.wav");

%[input,fs_in] = audioread("Data\soundSamples\guns_14.mp3");
%input = input(1:3*fs,1);
[p,q] = rat(fs/fs_in);
input = resample(input,p,q);
%% LS output
for n = 1 : size(hLs,2)
    n
    sLs(:,n) = conv(hLs(:,n),input);
end
% Binaural output
sVLsL = [];
sVLsL = [];
for n = 1 : size(hLs,2)
    n
    sVLsL(:,n) = conv(hLs(:,n),squeeze(hrtfData(n,1,:)));
    sVLsR(:,n) = conv(hLs(:,n),squeeze(hrtfData(n,2,:)));
end
sVLsL = sum(sVLsL,2);
sVLsR = sum(sVLsR,2);
% 
output_hrtf = [conv(input,sVLsL),conv(input,sVLsR)];
%output = sLs(:,1:5)+0.2*mean(sLs(:,6:7),2);
%%
%soundsc(0.075*output,fs);