% test different FIR filter quantizations
% DRB 10-Nov-2008 for ECE4703

% FDATOOL CODE TO MAKE A LOWPASS FILTER
N = 40;             % Order
F = [0 0.5 0.6 1];  % Frequency Vector
A = [10 10 0 0];    % Amplitude Vector
W = [1 1];          % Weight Vector
b  = firls(N, F, A, W);

% MY CODE
N = 16;                                   % number of bits in fixed point representation
M = 12;                                   % number of fractional bits
disp(['Maximum absolute filter coefficient       = ', num2str(max(abs(b)))]);
min_nonfrac_bits = ceil(log2(max(abs(b))));
disp(['Recommended number of non-fractional bits = ' num2str(min_nonfrac_bits)]);
disp(['Recommended number of fractional bits     = ' num2str(N-1-min_nonfrac_bits)]);

% plot frequency responses for a particular choice of N and M
Fs = 44100;
h = b;                                      % unquantized filter coefficients
hq = fir_coeff_quantizer(h,N,M);
[H,f] = freqz(h,1,1024,Fs);      % ideal frequency response
[Hq,fq] = freqz(hq,1,1024,Fs); % frequency response of quantized filter
plot(f/1e3,20*log10(abs(H)),fq/1e3,20*log10(abs(Hq)),'Linewidth',2);
legend('unquantized filter',['quantized filter with N=' num2str(N) ' M=' num2str(M)]);
xlabel('freq (kHz)');
ylabel('magnitude response (dB)');
grid on