% Matt Montag
% EEN 540 Homework 3 
% Problem 1: Filling a Tube With Water

fs = 8000; %sample rate
s = 5; %seconds duration
t = 1:1/fs:s; %time
c = 350; %m/s
l = 17.5; %length of tube (cm)

noiz = randn(1, fs*s);
noiz = noiz * .9 / max(abs(noiz)); % normalize
wavwrite(noiz,fs,'noise.wav');

%% Simulate stochastic water drop impulse

% noizamp = zeros(1, fs*s);
% dropfreq = 60; %drops per sec
% droplength = 800; %drop envelope duration in samples
% pt = -droplength/2:1:droplength/2-1;
% for i=0:dropfreq*s
% 	pulse = tripuls(pt, droplength, -.95);
% 	pos = mod(floor(rand * fs * s), fs*s - droplength - 1);
% 	noizamp(pos:pos+droplength-1) = noizamp(pos:pos+droplength-1)+pulse;
% end
% noiz = noiz .* noizamp;

%% Simulate tube as a delay line
i = 1;
echoindex = 1;
signal = zeros(1, fs*s);
for dist = l/100 : -l/100/fs/s : 1/fs % dist = length of tube
	echoindex = i - (fs * 2 * dist / c); % fractional delay
	if(echoindex > 1)
		p1 = noiz(floor(echoindex)); p2 = noiz(ceil(echoindex));
		frac = echoindex - floor(echoindex);
		sum = p1 * (1-frac) + p2 * frac; % interpolate samples
		noiz(i) = noiz(i) - sum/1.5; % simulate radiation loss
	end
	i = i+1;
end

noiz = noiz * .9 / max(abs(noiz)); % normalize
soundsc(noiz,fs);
wavwrite(noiz,fs,'tubenoise.wav');