% Read data
function tb_nco_results(nbins)
fa = 100.0;
f = TEXTREAD('freq.txt')*1E-6

I_ud = TEXTREAD('q_ud.txt')';
I_d = TEXTREAD('q_d.txt')';
LFSR = TEXTREAD('lfsr.txt');

N= length(I_ud);
N_fft = min(16384, N);
N_fft2 = N_fft/2;

fft_y2 = 2/N_fft*abs(fft(I_ud(1:N_fft).*hann(N_fft)'));
fft_y3 = 2/N_fft*abs(fft(I_d(1:N_fft).*hann(N_fft)'));

[i, v] = get_maxpur(fft_y2, fa, f);
max_spur_freq = (i*fa/N_fft);
max_spur_value = 20*log10(v);

[i, v] = get_maxpur(fft_y3, fa, f);
max_ditherd_spur_freq = (i*fa/N_fft);
max_ditherd_spur_value = 20*log10(v);

% Output
close all;

subplot(2,1,1)
plot(fa/N_fft*(0:N_fft2),20*log10(fft_y2(1:N_fft2+1)), '-', fa/N_fft*(0:N_fft2), max_spur_value*ones(1,N_fft2+1), 'r-', [max_spur_freq], [max_spur_value], 'ro'); grid;
spur_legend = sprintf('Max. spur %.1fdB at %.1fMHz', max_spur_value, max_spur_freq);
legend('With dithering', spur_legend);
legend('No dithering', spur_legend);
title('Table');
ylabel('dB');
xlabel('f/MHz');
axis([0 fa/2 -140 0]);
subplot(2,1,2)
plot(fa/N_fft*(0:N_fft2),20*log10(fft_y3(1:N_fft2+1)), '-', fa/N_fft*(0:N_fft2), max_ditherd_spur_value*ones(1,N_fft2+1), 'r-', [max_ditherd_spur_freq], [max_ditherd_spur_value], 'ro'); grid;
spur_legend = sprintf('Max. spur %.1fdB at %.1fMHz', max_ditherd_spur_value, max_ditherd_spur_freq);
legend('With dithering', spur_legend);
title('Table');
ylabel('dB');
xlabel('f/MHz');
axis([0 fa/2 -140 0]);

figure;
hist(LFSR, nbins)

function [max_i, max_v] = get_maxpur(spec, fa, f)
max_v = 0;
max_i = 0;
for ii=1:fix(length(spec)/2+1),
	fi = ii*fa/length(spec);
	dfi = fi - f;
	if abs(dfi) > 0.05*f
		if spec(ii) > max_v
			max_v = spec(ii);
			max_i = ii;
		end
	end;
end;
