FormatSpec = '%d';
PointsNum = 500;
N = 1;
R = 1;
B = 16;
M = 1;

Bmax = ceil(log2(((R*M)^N)/R)+B);

x = 1:1:PointsNum;
xDecim = 1:1:PointsNum/R;
Fs = 50;
ff = 0:1/PointsNum*2:1-1/PointsNum*2;

Cw = 18;
N=65;

Bfir = Cw + ceil(log2(N));

ReadInDataId = fopen('C:/S5243_FFT_REPO/src/src/Sim/InputSignal.txt','r');
InDataSignal = fscanf(ReadInDataId,FormatSpec);
fclose(ReadInDataId);

ReadFilteredDataId = fopen('C:/S5243_FFT_REPO/src/src/Sim/FilteredData.txt','r');
FilteredData = fscanf(ReadFilteredDataId,FormatSpec);
fclose(ReadFilteredDataId);

ReadFilterCoefsId = fopen('C:\S5243_FFT_REPO\src\src\Sim\CorrFilterCoefs.txt','r');
FilterCoefs = fscanf(ReadFilterCoefsId,FormatSpec);
fclose(ReadFilterCoefsId);


InDataFft = fft(InDataSignal);
InDataFft = InDataFft(1:PointsNum/2);

FilteredDataPNum    =   PointsNum/R;

FilteredDataFft = fft(FilteredData);
FilteredDataFft = FilteredDataFft(1:FilteredDataPNum/2);

CicResp = 20*log10(abs(FilteredDataFft));
CicResp = CicResp - max(CicResp);

Freqs = (Fs*(1:(PointsNum/2))/PointsNum);
FreqsDecim = Fs/R*(1:(FilteredDataPNum/2))/FilteredDataPNum;
NormFreqs = FreqsDecim/Fs;

FirResponce = 20 * log10(abs(fft(FilterCoefs, FilteredDataPNum)));
FirResponce = FirResponce(1:FilteredDataPNum/2);
FirResponce = FirResponce-max(FirResponce);

CicComp = CicResp + FirResponce;
CicComp = CicComp - max(CicComp);

figure('name','CIC/FIR Frequency Response', 'Numbertitle', 'off')
plot(FreqsDecim, FirResponce, '-.', 'LineWidth', 2, 'Color',[0 0 1]);
hold on;

plot(FreqsDecim, CicComp, '--', 'LineWidth', 2, 'Color',[0.2 0.5 0]);
hold on;

plot(FreqsDecim, CicResp, '-', 'LineWidth', 2, 'Color',[1 0 0]);
hold on;

title([{'CIC, Comp. FIR and Result'};{sprintf('Filter Order = %i',N)}]);
xlabel ('Freq (\pi x rad / samples)');
ylabel ('Magnitude (dB)');
legend('Comp. FIR','Sum Response','CIC filter','location','northeast');
grid on;


Hcic = abs((sin(pi*M*R*ff) ./ sin(pi*ff))).^N;
Hcicdb = 20 * log10(abs(Hcic));
Hcicdb = Hcicdb - max(Hcicdb);
HcicdbCut = Hcicdb(1:PointsNum/2);


figure('name','Cic Calc and Cic Real', 'Numbertitle', 'off')
plot(FreqsDecim,HcicdbCut, '-.', 'LineWidth', 2, 'Color',[0 0 1]);
hold on;

plot(FreqsDecim,CicResp, '--', 'LineWidth', 2, 'Color',[0.2 0.5 0]);
hold on;

title([{'CIC calc, CIC real'};{sprintf('Filter Order = %i',N)}]);
xlabel ('Freq (\pi x rad / samples)');
ylabel ('Magnitude (dB)');
legend('CIC calc','CIC real','location','northeast');
grid on;

figure(1)
plot(FreqsDecim,HcicdbCut, '-.', 'LineWidth', 2, 'Color',[0 0 1]);

figure(2)
plot(FreqsDecim,CicResp, '-.', 'LineWidth', 2, 'Color',[0 0 1]);















