% Daniel Jacobson
% MATH 447 Project 5 (Audio Compression)
% Problem 3 code
% inputs: x, list of frequencies (Hz)
%         len, length in seconds of tone
%         b, quantization bits
%         name, string identifier for files
% outputs: plays three frequency chord, then compresses the tone using
%          prob2codec (MDCT with windowing function on overlaps), then
%          plays compressed tone, plots a small section of original vs
%          decoded signal, and returns root mean squared error
function rmse = question3(x, len, bits)
orig = zeros(1,len*2^13);
for i=1:length(x)
    % stepped chord
    orig = orig + (((1:len*2^13)/2^13) > ((i-1)*(len-0.5)/(length(x)+1))) .* (0.3*cos((1:len*2^13)*2*pi*x(i)/2^13));
    %orig = orig + cos((1:len*2^13)*2*pi*x(i)/2^13);
end
orig = 0.3 * orig / max(abs(orig));
decoded = prob2codec(orig, 32, bits);

audiowrite(strcat('prob3-', num2str(bits), '.wav'), horzcat(orig, zeros(1,2048), decoded, zeros(1,2048), (orig-decoded)*4), 2^13);

a=1;b=200;
from_end = (a:b) + len*2^13 - b;
plot(a:b, orig(from_end), a:b, decoded(from_end), a:b, orig(from_end)-decoded(from_end),'LineWidth',2);
ylim([-0.32 0.32]);
legend('Original', 'Decoded', 'Error');
title(strcat(strcat('Chord after MDCT with Windowing Function, n = 32, b = ', num2str(bits))));
print(strcat('prob3-',  num2str(bits)), '-dpng');

rmse = sqrt(sum((orig-decoded).^2)/(len*2^13));