%Program 11.1 Audio codec
%input: vector x of input signal
%Program 11.1 Audio codec
%input: vector x of input signal
%output: vector out of output signal
%Example usage: out=simplecodec(cos((1:2^(13))*2*pi*256/2^(13)));
%               example signal is 1/2 sec. pure tone of frequency f = 256
function output=mysimplecodec(x,Fs,waittime,b, original_file_name, new_file_name, input_output_graph_filename)
len=length(x);
n=2^5;                                % length of window
nw=floor(len/n);                      % number of length n windows in x
x=x(1:n*nw);                          % cut x to integer number of n windows
%Fs=2^(13);                            % Fs=sampling rate
%b=4; 
L=1;                           % b = quantization bits, [-L,L] amplitude range
q=2*L/(2^b-1);                        % q used for b bits on interval [-L, L]
h_matrix = [];
for j=1:2*n
    h_matrix(j) = (sqrt(2)*sin(((j-(1/2))*pi)/(2*n)));
end
for i=1:n                             % form the MDCT matrix
  for j=1:2*n
    M(i,j)= cos((i-1+1/2)*(j-1+1/2+n/2)*pi/n);
  end
end
M=sqrt(2/n)*M;
N=M';                                 % inverse MDCT
%x=cos((1:T*Fs)*2*pi*64*f/Fs);         % test signal
%x=x+cos((1:4096)*2*pi*64*5/Fs); 
%x=x+cos((1:4096)*2*pi*64*6/Fs);
x=0.3*x/max(abs(x));                  % normalize signal to max amplitude = 0.3
sound(x,Fs)                           % Matlab's sound command
audiowrite(original_file_name, x,Fs)
out=[];
for k=1:nw-1                          % loop over l ength 2n windows
  x0=x(1+(k-1)*n:2*n+(k-1)*n)';
  x0 = (h_matrix' .* x0);
  %test_length = length(x0);
  y0=M*x0;
  y1=round(y0/q);                     % transform components quantized
% Storage/transmission of file occurs here  
  y2=y1*q;                            % transform components dequantized
  w(:,k)=N*y2;                        % invert the MDCT
  last_h_matrix = h_matrix(n+1:2*n)';
  first_h_matrix = h_matrix(1:n)';
  if(k>1)
      w2=w(n+1:2*n,k-1);w3=w(1:n,k);
      w2 = last_h_matrix .* w2;
      w3 = first_h_matrix .* w3;
      out=[out;(w2+w3)/2];          % collect the reconstructed signal
  end                                 % (of length 2n less than length of x)
end
pause(waittime)
sound(out,Fs)   % play the reconstructed tone
%output = (out-x).^2;
%output = sqrt(mean(output(:)));
audiowrite(new_file_name, out,Fs)
output = RMSE(out, x, n);
t = 1:n*5;
subx = x(n*100+1:n*105);
subout = out(n*99+1:n*104);
figure(1)
plot(t,subx,'b-')
hold on
plot(t,subout,'r-')
hold off
ylabel('frequency')
xlabel('time')
title('input and output sound graph')
saveas(gcf, input_output_graph_filename)
%figure(2)
%label('frequency')
%xlabel('time')
%title('output sound graph')
%saveas(gcf, output_graph_filename)
pause(waittime)