%{

Matt Montag
University of Miami
EEN502 Project 2

Experimenting with HRTF and Loudspeaker Arrays
Using the UC Davis CIPIC HRTF database, subject 17.

%}
clear all; clc;
c = 345;                        % speed of sound - m/s
fs = 44100;                      % sample rate - 1/s

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PART A %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

T = 8;							% total time (sec)
t = 1/fs:1/fs:T;				% time vector
hrir_length = 200;				% impulse length (samples)
hrir_index = 9999;
% wav = wavread('c:\reason\god vox (fade).wav');
signal = randn(fs*T,1);

load hrir_final.mat;

segments = 100;
segment_dur = fs*T/segments;

% allocate stereo signal for convolution sum length = A + B - 1
output = zeros(fs*T + hrir_length - 1,2);

for segment=0:segments-1
	azim = segment*360/segments;
	%clc;
	% convert azimuth-first to elevation-first coordinate
	if azim > 270
		azim = azim - 360;
		elev = 0;
	elseif azim > 90
		azim = 180 - azim;
		elev = 180;
	else 
		azim = azim;
		elev = 0;
	end;
	azim = -1*azim;
	
	% check if this position is closer to a different HRIR sample point
	if hrir_index ~= getNearestUCDindex(azim,elev);
		hrir_index = getNearestUCDindex(azim,elev);
		hl = getNearestUCDpulse(azim,elev,hrir_l);
		hr = getNearestUCDpulse(azim,elev,hrir_r);
	end;

	sampstart = segment * size(signal,1)/segments + 1;
	sampend = (segment+1) * size(signal,1)/segments;
	
	output(sampstart:sampend+hrir_length-1,1) = ...
		output(sampstart:sampend+hrir_length-1,1) + ...
		conv(hl,signal(sampstart:sampend));
	output(sampstart:sampend+hrir_length-1,2) = ...
		output(sampstart:sampend+hrir_length-1,2) + ...
		conv(hr,signal(sampstart:sampend));
end;

plot(output);
output = .9.*output/max(max(abs(output)));
wavwrite(output,fs,16,'partA_prob1.wav');
soundsc(output,fs);