%in+iir_out with 8 intp
clc;clear;close all
% addpath("/data/work/thfu/TailCorr/script_m");
data_source = 'matlab';
file_path = "/home/thfu/work/TailCorr/sim/TailCorr_en/";
rng('shuffle');

if strcmp(data_source, 'matlab')
    in = floor(cat(1,zeros(4,1),3000*randn(4*2500+4,1)));
    for i = 0:3
        filename = strcat(file_path, "in", num2str(i), "_matlab.dat");
        subset = in(i+1:4:end);
        fileID = fopen(filename, 'w');
        fprintf(fileID, '%d\n', subset);
        fclose(fileID);
    end
    in = [in; zeros(6e4,1)];
    system('make all');
elseif strcmp(data_source, 'verdi')
    system('make all');    
    in = [];
    for i = 0:3
        filename = strcat(file_path, "in", num2str(i), ".dat");
        in_data = importdata(filename);
        if isempty(in)
            N = length(in_data);
            in = zeros(4*N, 1);
        end
        in(i+1:4:end) = in_data;
    end    
else
end


cs_wave = [];
for i = 0:7
    filename = strcat(file_path, "dout", num2str(i), ".dat");
    dout_data = importdata(filename);
    if isempty(cs_wave)
        N = length(dout_data);
        cs_wave = zeros(8*N, 1);
    end
    cs_wave(i+1:8:end) = dout_data;
end

A   =  [0.025 0.015*1 0.0002*1 0];
tau = -[1/250 1/650 1/1600 0];
fs  = 2e9;

coef_len = length(A);
for i = 1:coef_len
    b(i) = exp(1e9/fs/(1-A(i))*tau(i));
    a(i) = A(i)/1/(1-A(i))*exp(1e9/fs/(1-A(i))/2*tau(i));  
    h_ideal(:,i) = filter(a(i),[1 -b(i)],diff(in));
end
len_in = length(in);
len_h_ideal = length(h_ideal);
in = [in; zeros(1, len_h_ideal - len_in + 1)'];
wave_float = in(2:end)+ sum(h_ideal,2);

wave_float_len = length(wave_float);
wave_float_8 = interp1(1:wave_float_len,wave_float,1:1/8:(wave_float_len+1-1/8),'linear')';

[wave_float_A,cs_wave_A,Delay] = alignsignals(wave_float,cs_wave);
N = min(length(wave_float),length(cs_wave_A));
figure()
diff_plot(wave_float_A, cs_wave_A,'float','verdi',[0 N]);

%% Test of iir filter with no intp

[wave_float_A,wave_verdi_A,Delay] = alignsignals(wave_float,wave_verdi);
N = min(length(wave_float_A),length(wave_verdi_A));
figure()
diff_plot(wave_float_A, wave_verdi_A,'float','verdi',[0 N]);
%%
signalAnalyzer(wave_float,wave_verdi,'SampleRate',1);
%%

a_fix = round(a*2^31);
ab_fix  = round(a.*b*2^31);
ab2_fix = round(a.*b.^2*2^31);
ab3_fix = round(a.*b.^3*2^31);
ab4_fix = round(a.*b.^4*2^31);
ab5_fix = round(a.*b.^5*2^31);
ab6_fix = round(a.*b.^6*2^31);
ab7_fix = round(a.*b.^7*2^31);
b8_fix  = round(b.^8*2^31);

a_hex = dec2hex(a_fix,8);

a_bin = dec2bin(a_fix,32);

fprintf('a_fix is %d\n',a_fix);
fprintf('ab_fix is %d\n',ab_fix);
fprintf('ab2_fix is %d\n', ab2_fix);
fprintf('ab3_fix is %d\n', ab3_fix);
fprintf('ab4_fix is %d\n', ab4_fix);
fprintf('ab5_fix is %d\n', ab5_fix);
fprintf('ab6_fix is %d\n', ab6_fix);
fprintf('ab7_fix is %d\n', ab7_fix);
fprintf('b8_fix is %d\n',b8_fix);

