%%
clear
close all
SOFAstart;
hrtf = SOFAload('FABIAN_HRIR_measured_HATO_0.sofa');
%hrtf = SOFAload('subject_003.sofa');
fs_hrtf = hrtf.Data.SamplingRate;
hrtfData = hrtf.Data.IR;
sourcePosition = hrtf.SourcePosition;
%
theta_L = [30,0];
theta_R = [330,0];
[~,ind_L] = min( sum(  (bsxfun(@minus, sourcePosition(:,1:2) ,mod(theta_L,360))).^2,2  ) );
hrtf_L = squeeze(hrtfData(ind_L,:,:));
[~,ind_R] = min( sum(  (bsxfun(@minus, sourcePosition(:,1:2) ,mod(theta_R,360))).^2,2  ) );
hrtf_R = squeeze(hrtfData(ind_R,:,:));

vL = [cosd(theta_L(1)) sind(theta_L(1))]';
vR = [cosd(theta_R(1)) sind(theta_R(1))]';

vT = [2 0.1]';
A = pinv([vL vR])*vT;
A = A/norm(A);

[in,fs_old] = audioread('gitL.wav');
in = resample(in,fs_hrtf,fs_old);
in = in(1:3*fs_hrtf);

output = [[conv(A(1)*in,hrtf_L(1,:)') + conv(A(2)*in,hrtf_R(1,:)')] ,...
          [conv(A(1)*in,hrtf_L(2,:)') + conv(A(2)*in,hrtf_R(2,:)')]];
