len = 8;
[y, Fs] = audioread('(Heart).wav');
% ensure length multiple of 32 and max intensity of 0.3
y = 0.3 * y / max(abs(y));
y = y(1:32*floor(length(y)/32),1)';

decoded = prob1codec(y, 32, 2);
audiowrite('prob4-c1-2-mdct.wav', decoded, Fs);
audiowrite('prob4-c1-2-err.wav', y-decoded, Fs);
a=1;b=200;
from_mid = Fs * 2 + (a:b);
plot(a:b, y(from_mid), a:b, decoded(from_mid), a:b, y(from_mid)-decoded(from_mid),'LineWidth',2);
ylim([-0.32 0.32]);
legend('Original', 'Decoded', 'Error');
title('(Heart) sample after MDCT without Windowing, n = 32, b = 2');
print('prob4-fig1-2', '-dpng');
sqrt(sum((y-decoded).^2)/length(y))

decoded = prob1codec(y, 32, 4);
audiowrite('prob4-c1-4-mdct.wav', decoded, Fs);
audiowrite('prob4-c1-4-err.wav', y-decoded, Fs);
a=1;b=200;
from_mid = Fs * 2 + (a:b);
plot(a:b, y(from_mid), a:b, decoded(from_mid), a:b, y(from_mid)-decoded(from_mid),'LineWidth',2);
ylim([-0.32 0.32]);
legend('Original', 'Decoded', 'Error');
title('(Heart) sample after MDCT without Windowing, n = 32, b = 4');
print('prob4-fig1-4', '-dpng');
sqrt(sum((y-decoded).^2)/length(y))

decoded = prob2codec(y, 32, 2);
audiowrite('prob4-c2-2-mdct.wav', decoded, Fs);
audiowrite('prob4-c2-2-err.wav', y-decoded, Fs);
a=1;b=200;
from_mid = Fs * 2 + (a:b);
plot(a:b, y(from_mid), a:b, decoded(from_mid), a:b, y(from_mid)-decoded(from_mid),'LineWidth',2);
ylim([-0.32 0.32]);
legend('Original', 'Decoded', 'Error');
title('(Heart) sample after MDCT with Windowing Function, n = 32, b = 2');
print('prob4-fig2-2', '-dpng');
sqrt(sum((y-decoded).^2)/length(y))

decoded = prob2codec(y, 32, 4);
audiowrite('prob4-c2-4-mdct.wav', decoded, Fs);
audiowrite('prob4-c2-4-err.wav', y-decoded, Fs);
a=1;b=200;
from_mid = Fs * 2 + (a:b);
plot(a:b, y(from_mid), a:b, decoded(from_mid), a:b, y(from_mid)-decoded(from_mid),'LineWidth',2);
ylim([-0.32 0.32]);
legend('Original', 'Decoded', 'Error');
title('(Heart) sample after MDCT with Windowing Function, n = 32, b = 4');
print('prob4-fig2-4', '-dpng');
sqrt(sum((y-decoded).^2)/length(y))