clear all
close all
clc

NperPeriod = 360*900;  

n = 0:NperPeriod-1;
sinTable = round((2^17/2-1) * sin(2*pi/NperPeriod .* (n)));
% sin table


fout = 80; %Hz
% fout = 4593; %Hz
fs = 68e3;

NumOfSamp = 1*68e3+1;

precisionHelp = 2^16;

dn = NperPeriod *(1/fs)/(1/fout);

% intdn = round(dn*precisionHelp)
intdn = round((fout*precisionHelp*NperPeriod)/fs )

intdnNew = round((fout2*precisionHelp*NperPeriod)/fs );

intNtime = zeros(NumOfSamp,1);
dblNtime = zeros(NumOfSamp,1);

intNtime(1) = 0;
dblNtime(1) = 0;

for i = 2:NumOfSamp
    intNtime(i,1) = intNtime(i-1,1) + intdn;
    dblNtime(i,1) = dblNtime(i-1,1) + dn;


end

sinTableIndexP = zeros(NumOfSamp,1);
sinTableIndex = zeros(NumOfSamp,1);

% sinTableIndexP(1) = 2^20;
% sinTableIndexP(1) = 1000;

for i = 2:NumOfSamp
    intNtime(i,1) = intNtime(i-1,1) + intdn;
    
    sinTableIndexP(i) = sinTableIndexP(i-1) + intdn;
    
    if ((sinTableIndexP(i)/precisionHelp - NperPeriod + 2) >= (0) )
        
%         sinTableIndexP(i) = ((sinTableIndexP(i)/2^16) - NperPeriod)*2^16;
        if (sinTableIndexP(i) < (NperPeriod*precisionHelp + 100))
            sinTableIndexP(i) = 0;
        else
            sinTableIndexP(i) = sinTableIndexP(i) - (NperPeriod*precisionHelp);
        end
    end
    
    tmpIndex = floor(sinTableIndexP(i)/precisionHelp);
    sinTableIndex(i) = tmpIndex;
    
    
end

figure(7)
plot(sinTableIndex);        %index progress
figure(8)
plot(sinTableIndexP);


n = 1:NumOfSamp;

error = zeros(NumOfSamp,1);
sinFromTable = zeros(NumOfSamp,1);
sinFromFunc = zeros(NumOfSamp,1);

errorIndex = zeros(NumOfSamp,1);
for i = 1:NumOfSamp
    error(i) = (sinTable(1+sinTableIndex(i)) - (2^17/2-1)*sin(2*pi/NperPeriod*(dblNtime(i))) );% ./ sinTable(dblIndex);
    
    sinFromTable(i) = sinTable(1+sinTableIndex(i));
    sinFromFunc(i) = (2^17/2-1)*sin(2*pi*fout*(i-1)*1/fs);
    
    err1 = (floor(intNtime(i)/precisionHelp));
    err2 = dblNtime(i);
    errorIndex(i) = (err1 - err2);
end

% figure(10)
% plot((n-1)*1/fs,sinFromTable,(n-1)*1/fs,sinFromFunc)
error = sinFromTable - sinFromFunc;

intNtime(end)
figure(2)
plot((n-1)*1/fs,error,'blue','LineWidth',2)
% title('Odchylka funkční hodnoty sinus vypočteného z tabulky oproti přesné hodnotě')
xlabel('t [s]')
ylabel('y_t_a_b (index) - y_f_c_e(n.T_v_z) [-]')
grid on


y = sinTable( 1+sinTableIndex);
figure(3)
plot((n-1)*1/fs,y);
hold on
grid on

figure(4)
plot(n,errorIndex)
title('Odchylka indexu( v oboru N) oproti presne hodnotě')
grid on

