clear all ; clc;
%format shorte
format short

%%%%%%%%%%%%%%%%
% scale factor truncated to 14 or 30 bits
% coeff truncated to 14 or 30 bits
%%%%%%%%%%%%%%%%


% frequencies are in units of Fs/2
% so cutoff=0.1 and Fs=8kHz means
% 400 Hz.
cutoff1 = 0.1;
cutoff2 = 0.12;
BPpoles = 4
f = fdesign.bandpass('N,F3db1,F3db2', BPpoles, cutoff1, cutoff2);
BPsos = design(f,'butter','FilterStructure','df1sos');
BPsos.sosMatrix
BPsos.ScaleValues

 cutoff = 0.005 ;
 LPpoles = 4 
f = fdesign.lowpass('N,F3db', LPpoles, cutoff);
LPsos = design(f,'butter');%,'FilterStructure','df1sos');
LPsos.sosMatrix
LPsos.ScaleValues

figure(1); clf;

%plot frequency response for the exact filter
[fresponse, ffreq] = freqz(LPsos, 5000);
plot(ffreq/pi,abs(fresponse), 'b', 'linewidth',3);
xlabel('normalized frequency'); ylabel('filter amplitude');
hold on

%plot frequency response for the truncated 14 filter
LPsos.ScaleValues = fix(LPsos.ScaleValues*2^14)/2^14;
LPsos.sosMatrix = fix(LPsos.sosMatrix*2^14)/2^14;
%return
[fresponse, ffreq] = freqz(LPsos, 5000);
plot(ffreq/pi,abs(fresponse), 'r', 'linewidth',2);
%xlabel('frequency'); ylabel('filter amplitude');
%legend ('exact','truncated 14 bits')

f = fdesign.lowpass('N,F3db', LPpoles, cutoff);
LPsos = design(f,'butter');%,'FilterStructure','df1sos');
%plot frequency response for the truncated 30 filter
LPsos.sosMatrix = fix(LPsos.sosMatrix*2^30)/2^30;
LPsos.ScaleValues = fix(LPsos.ScaleValues*2^30)/2^30;
%LPsos.ScaleValues = 2.^(floor(log2(LPsos.ScaleValues)))
[fresponse, ffreq] = freqz(LPsos, 5000);
plot(ffreq/pi,abs(fresponse), 'g', 'linewidth',2);
%xlabel('frequency'); ylabel('filter amplitude');
legend ('exact', 'truncated 14 bits', 'truncated 30 bits')
set(gca, 'xlim', [0 cutoff*2])
set(gca, 'ylim', [0 1.1])
title('LowPass')
%%%

figure(2); clf;

%plot frequency response for the exact filter
[fresponse, ffreq] = freqz(BPsos, 5000);
plot(ffreq/pi,abs(fresponse), 'b', 'linewidth',3);
xlabel('frequency'); ylabel('filter amplitude');
hold on
%plot frequency response for the truncated filter
BPsos.sosMatrix = fix(BPsos.sosMatrix*2^14)/2^14;
BPsos.ScaleValues = fix(BPsos.ScaleValues*2^14)/2^14;
[fresponse, ffreq] = freqz(BPsos, 5000);
plot(ffreq/pi,abs(fresponse), 'r', 'linewidth',2);
%xlabel('frequency'); ylabel('filter amplitude');
%legend ('exact','truncated 14 bits')
title('BandPass')

f = fdesign.bandpass('N,F3db1,F3db2', BPpoles, cutoff1, cutoff2);
BPsos = design(f,'butter','FilterStructure','df1sos');
%plot frequency response for the truncated 30 filter
BPsos.sosMatrix = fix(BPsos.sosMatrix*2^30)/2^30;
BPsos.ScaleValues = fix(BPsos.ScaleValues*2^30)/2^30;
[fresponse, ffreq] = freqz(BPsos, 5000);
plot(ffreq/pi,abs(fresponse), 'g', 'linewidth',2);
xlabel('normalized frequency'); ylabel('filter amplitude');
legend ('exact', 'truncated 14 bits', 'truncated 30 bits')
set(gca, 'xlim', [0 cutoff2*2])
set(gca, 'ylim', [0 1.1])

