%%
clear
close all
SOFAstart;
hrtf = SOFAload('FABIAN_HRIR_measured_HATO_0.sofa');
%hrtf = SOFAload('subject_003.sofa');
fs = 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,:,:));

[in,fs_old] = audioread('gitL.wav');
in = resample(in,fs,fs_old);
in = in(1:3*fs);
outL = in;
t = (0:length(in)-1)'/fs;

dt = -2e-4;
outR = interp1(t,in,t-dt,'linear','extrap');

output = [conv(outL,hrtf_L(1,:)')+conv(outR,hrtf_R(1,:)') ,...
          conv(outL,hrtf_L(2,:)')+conv(outR,hrtf_R(2,:)')];
