% Read data
function tb_results()
%fa = 100.0;
fa = TEXTREAD('fa.txt')/1E6
R = TEXTREAD('ratio.txt');
N = TEXTREAD('nstages.txt');;
M = 1;
fa_dec = fa/R
N_pfir = 63;

I_out_dec = TEXTREAD('i_dec.txt')';
Q_out_dec = TEXTREAD('q_dec.txt')';
I_out_fir = TEXTREAD('i_fir.txt')';
Q_out_fir = TEXTREAD('q_fir.txt')';

N_dec = length(I_out_dec)-2*N_pfir;
N_fft_dec = N_dec
N_fft2_dec = N_fft_dec/2;

N_fir = length(I_out_fir)-2*N_pfir;
N_fft_fir = N_fir
N_fft2_fir = N_fft_fir/2;

fft_y2_fir = 2/N_fft_fir*abs(fft(I_out_fir(2*N_pfir+1:N_fft_fir+2*N_pfir).*hann(N_fft_fir)'));

fft_y2_dec = 2/N_fft_dec*abs(fft(I_out_dec(2*N_pfir+1:N_fft_dec+2*N_pfir).*hann(N_fft_dec)'));

f = (1:N_fft_dec)/N_fft_dec;
g = (R*M)^N;
H = abs(sin(pi*M.*f)./sin(pi.*f/R)).^N;

[v, j] = max(fft_y2_dec(1:N_fft2_dec/2))
H = v*H/H(j);

wavwrite(0.5*[I_out_dec' Q_out_dec'], 16000, 16, 'iq.wav');
wavwrite(0.5*[I_out_fir' Q_out_fir'], 8000, 16, 'iq_cfir.wav');

% Output
close all;

plot(1:length(I_out_dec), I_out_dec, 1:length(Q_out_dec), Q_out_dec); grid;

figure;
cic_plot(M, N, R);

figure;
subplot(2,1,1)
plot(fa/(R*N_fft_dec)*(0:N_fft2_dec),20*log10(fft_y2_dec(1:N_fft2_dec+1)), '-', fa/(R*N_fft_dec)*(0:N_fft2_dec),20*log10(H(1:N_fft2_dec+1)), 'r-');
legend('CIC', 'Droop');
xlabel('MHz');
grid;
subplot(2,1,2)
plot(fa/(2*R*N_fft_fir)*(0:N_fft2_fir),20*log10(fft_y2_fir(1:N_fft2_fir+1)), '-');
legend('CFIR');
xlabel('MHz');
grid;

