clc;
clear;

%% read audio data (amplitude vector of the signal)
data = mydataread('Aretha Franklin - Think.wav');

%% histogram calculation
[num, bin] = hist(data);

%% histogram plot
subplot(1,2,1);
hist(data);
axis([-1 1 0 3*10^6]);
xlabel('Amplitude bins');
ylabel('Frequency');

%% Uniform distribution fit
hist_mean = mean(num);
subplot(1,2,2);
plot(bin, hist_mean*ones(length(bin)), 'k-', [bin(1) bin(1)], [0 hist_mean], 'k-', [bin(length(bin)) bin(length(bin))], [0 hist_mean], 'k-');
hold on;

%% Triangular distribution fit
plot([bin(1) mean([bin(1) bin(length(bin))])], [0 2*hist_mean], 'r-', [mean([bin(1) bin(length(bin))]) bin(length(bin))], [2*hist_mean 0], 'r-');

%% Gaussian distribution fit
% If we have Matlab Statistics Toolbox installed, we can simply use
% histfit() to get accurate Gaussian fit curve
[sigma,mu,A] = mygaussfit(bin, num, 0);
x = bin(1):0.01:bin(length(bin));
y = A * exp(-(x-mu).^2/(2*sigma^2));
plot(x, y, 'b-');
axis([-1 1 0 3*10^6]);
xlabel('Amplitude');
ylabel('Frequency');
% legend('Uniform distribution fit', 'Triangular distribution fit', 'Gaussian distribution fit');
