% Matt Montag
% EEN 540 Project 1
% Phoneme Analysis

path = 'wav/';
words = ...
{'eve' 'it' 'hate' 'met' 'at' 'father' 'all' 'obey' 'foot' 'boot' ...
'up' 'bird' 'read' 'let' 'we' 'you' 'me' 'no' 'sing' 'pay' 'to' 'key' ...
'be' 'day' 'go' 'for' 'thin' 'see' 'she' 'vote' 'then' 'zoo' 'azure' ...
'he' 'hide' 'out' 'boy' 'new' 'chew' 'just'; ...
'i' 'I' 'e' 'E' '@' 'a' 'c' 'o' 'U' 'u' 'A' 'R' 'r' 'l' ... 
'w' 'y' 'm' 'n' 'G' 'p' 't' 'k' 'b' 'd' 'g' 'f' 'T' 's' ...
'S' 'v' 'D' 'z' 'Z' 'h' 'Y' 'W' 'O' 'JU' 'tS' 'J'};


for i=1:length(words)
	clf;
	Word = words{1,i};
	Phoneme = words{2,i};
	disp(Word);
	if(isempty(Word)) 
		continue; 
	end
	f1 = figure;
 	[wsignal,fs] = wavread([path Word '.wav']);
 	subplot(411);
	t = (0:length(wsignal)-1)/fs; % x-axis
 	plot(t,wsignal); axis tight; ylim([-1,1]); xlabel('Time');
	title([Word ' - /' Phoneme '/']); 
	if(exist([path Word '_p.wav'],'file'))
		disp('  Phoneme exists');
		[psignal,fs] = wavread([path Word '_p.wav']);
		% find segment (psignal) within larger signal (wsignal)
		chunk = 10;
		for j=1:size(wsignal)-size(psignal)
			if(wsignal(j:j+chunk) - psignal(1:chunk+1) == zeros(chunk+1,1))
				ix = j;
				disp(['  Found segment at ' num2str(ix)]);
				hold on;
				plot([j:j+size(psignal)-1]'/fs,psignal,'r'); hold off;
				break;
			end
		end
		
		subplot(423);
		t = (ix:ix+length(psignal)-1)/fs; % x-axis
		plot(t,psignal,'r'); axis tight; ylim([-1,1]);
	end
	if(exist([path Word '_s.wav'],'file'))
		disp('  Short phoneme exists');
	end
	
	%FFT
	Y = fft(psignal);
	Y = abs(Y(1:floor(length(Y)/2)));
	dbY = 20*log10(Y);
	dbY = dbY - max(dbY);
	%Y = Y-max(max(Y));
	F = linspace(0,fs/2,length( Y /2))';
	subplot(424); plot( F,dbY);
	xlabel('Frequency'); ylabel('dB');
	% smooth spectral envelope via linear prediction 
	p=fs/1000 + 4;				%p = fs/kHz + 4
	[a,g]=lpc( psignal ,p);		%linear predictive coding coefficients
	lspec=freqz(g,a, F ,fs);	%linear spectrum
	hold on; plot( F ,20*log10(abs(lspec)), 'k'); hold off;
	%narrowband spectrogram 
	N=512;
	subplot(413), spectrogram(wsignal,hamming(N),round(0.97*N),N,fs,'yaxis');
	%wideband spectrogram 
	subplot(414), spectrogram(wsignal,hamming(N/4),round(0.9*N/4),N,fs,'yaxis');
	f2 = figure;
	set(f2,'position',[0 0 600 300]);
	spectrogram(wsignal,hamming(N/4),round(0.9*N/4),N,fs,'yaxis');
	title([Word ' - /' Phoneme '/ - waterfall plot']);
	view(45,30);
	
% 	figure(f1);
% 	export_fig image.png -native; 
% 	movefile('image.png', [Word '-yap.png']);
% 	
% 	figure(f2);
% 	export_fig image.png -native; 
% 	movefile('image.png', [Word '-waterfall.png']);

	saveas(f1,Word,'png');
	saveas(f2,[Word '-waterfall'],'png');
%	break;
	close all;
end

