%% init
clc;
clear all;
close all;

fc = 1e6;
fvz = 8.82e6;
fm = 2e3;
t = (0:1/fvz:510/fm);
Um = cos(2*pi*fm*t);
phase = (0:(2*pi/(1e6)):2*pi);
LUTcos = cos(phase);
clear phase;

accumulator = 50000;

signal_length = 2240000;
out(1:signal_length) = 0;
out_sig(1:signal_length) = 0;
out_rect(1:signal_length) = 0;
out_rectsig(1:signal_length) = 0;

%% local osc

for i=2:signal_length
    accumulator = round( accumulator + (113378/2+100) + 1);
    if (accumulator>length(LUTcos))
        accumulator = accumulator - length(LUTcos);
    end
    
    out(i) = 10* LUTcos(accumulator);
end

counter2(1:signal_length+1) = 0;
count = 0;
counter = 0;
accumulator = 0;
memory_aux = 0;
error = 1;

%% signal osc
 for i = 2:signal_length
      
        counter2(i)= count;
        accumulator = round( accumulator + (113378/2-counter)+ 1);
        if (accumulator>length(LUTcos))
            accumulator = accumulator - length(LUTcos);
        end    
        if (accumulator<0)
            accumulator = length(LUTcos) - accumulator;    
        end

        out_sig(i) = 10* LUTcos(accumulator);
                  
        if(out(i)>=0)
            out_rect(i) = 1;
        else
            out_rect(i) = -1;
        end

        if (out_rect(i)>out_rect(i-1))
            count = count - 1;
        end

        if(out_sig(i)>=0)
            out_rectsig(i) = 1;
        else
            out_rectsig(i) = -1;
        end

        if (out_rectsig(i)>out_rectsig(i-1))
            count =  count + 1;
        end
        
        aux = count*1e-2;
        counter = count*10 + (aux + memory_aux);
        memory_aux = aux;
        
 end
 
%% plots   

figure(1)
subplot(2,1,1);
plot(t(1:200),out(1:200),'r');          
hold on;
plot(t(1:200),out_sig(1:200),'b');
hold off;

subplot(2,1,2);
plot(t(length(out_sig)-200:length(out_sig)),out(length(out_sig)-200:length(out_sig)),'r');
hold on;
plot(t(length(out_sig)-200:length(out_sig)),out_sig(length(out_sig)-200:length(out_sig)),'b');
hold off;

figure(2)
plot(t(1:length(out_sig)+1),counter2(1:length(out_sig)+1));

figure(3)
plot(t(1:length(out_sig)),out(1:length(out_sig))-out_sig(1:length(out_sig)));



