lut_size=32768;
dac_bits=12;
dac_bias = 2^(dac_bits-1);
dac_ampl = 2^(dac_bits-1) - 1;
acc_frac=32;

n_sub_taps = 512;
    
lut_real=cos(linspace(0, 2*pi * lut_size/(lut_size + 1), lut_size)) .* dac_ampl

lut = round(lut_real);

for i = 1:lut_size
    
    
    ni = i+1;
    if(ni > lut_size)
        ni=1;
    end

    x0 = 2 * pi * (i-1) / lut_size;
    x1 = 2 * pi * i / lut_size;
    
    
    sub = cos(linspace(x0, x1, n_sub_taps)).*dac_ampl;

    for j=1+1:n_sub_taps-1
        if(abs(sub(j) - sub(1)) >= abs(sub(n_sub_taps)-sub(j)))
            break
        end
    end
    offs(i)= j / n_sub_taps * (2^acc_frac);

end







fs=500e6;
fout=11.1111e6;

tune_res = 0.01;

acc_bits=acc_frac + log2(lut_size);
acc_max = 2^acc_bits;
acc = 0;

nsamples = 32768;
y=zeros(nsamples,1);
y2=zeros(nsamples,1);
delta = round((lut_size * fout/fs) * (2^acc_frac))


for i =1:nsamples
    
    idx = floor(acc / (2^acc_frac)) + 1;
    fb = floor(mod(acc, 2^acc_frac));
    
    
    if(idx > lut_size)
        idx = idx - lut_size;
    end
    
    if(fb < offs(idx))
        yt=lut(idx);
    elseif(idx == lut_size) 
        yt=lut(1);
    else
        yt=lut(idx+1);
    end
    
        
        y(i)= yt + randi([0, 1],1,1);
        y2(i) = round(cos(2*pi*(acc/(2^acc_frac))) * dac_ampl);
    
    acc = acc + delta;
    if (acc >= acc_max) 
        acc = acc - acc_max;
    end
end


%y=y+randi([-1,1],nsamples,1)
f = 20*log10(abs(fft(y.*hanning(nsamples))));
f2 = 20*log10(abs(fft(y2.*hanning(nsamples))));

plot(f - max(f));
hold on;
plot(f2 - max(f2),'r-');
hold off;
grid on;
length(y)
length(hanning(nsamples))

length(y)





