% Matlab Fixed-Point FIR filter demo part 2
% Simulate FIR filter and look at range of variables
% DRB 11-Nov-2013
% For ECE4703
% =================================================================
% User parameters below
% =================================================================
M = 10;         % FIR filter order 
Nh = 8;         % number of total bits for filter coefficients
Mh = 7;         % number of fractional bits for filter coefficients 
Nx = 16;        % number of total bits for filter coefficients
Mx = 15;        % number of fractional bits for filter coefficients 
N = 100;        % length of input signal
a = 0.9;        % fractoion of full-scale for input signal 
% =================================================================

% design FIR filter
h = firls(M,[0 .1 .2 .5]*2,[1 1 0 0]);  % lowpass (full precision)
hq = sfi(h,Nh,Mh);                      % quantized coefficients 

% generate random input signal
x = a*(2*rand(1,N)-1);
xq = sfi(x,Nx,Mx);                      % quantized inputs 

% allocate space for output
y = zeros(1,length(x));

% set up numeric scope
hscope = NumericTypeScope;

% Override datatype to capture the true range in floating point.
fp = fipref;
initialDTOSetting = fp.DataTypeOverride;
fp.DataTypeOverride = 'TrueDoubles';

% do FIR filtering
for n=1:N,
    for m=0:M, % h has M+1 coefficients
        if (n-m)>0,
            y(n) = y(n)+hq(m+1)*xq(n-m); % direct convolution
            step(hscope,y(n));
        end
    end
end

% Reset the original setting of data type Override.
fp.DataTypeOverride = initialDTOSetting;