% dnl and inl plots from sine wave data
% input vector y should contain the unbinned signal (integer numbers)

% Boris Murmann, 2002

function dnl_inl(y);

details = 0;            % set to 1 to plot intermediate results

% histogram boundaries
minbin=min(y);
maxbin=max(y);
numbins=maxbin-minbin+1;

% histogram
h= hist(y, minbin:maxbin);
if (details)
  figure(2);
  plot(minbin:maxbin, h);
  title('Raw Histogram of ADC Output');
end

% cumulative histogram
ch= cumsum(h);

% transition levels
T = -cos(pi*ch/sum(h));
if (details)
  figure(3);
  plot(minbin:maxbin, T);
  title('Transitiion Levels');
end

% linearized histogram
hlin = T(2:end) - T(1:end-1);
if (details)
  figure(4);
  plot(minbin+1:maxbin, hlin);
  title('Linearized Histogram');
end

% truncate at least first and last bin, more if input did not clip ADC
trunc=2;
hlin_trunc = hlin(1+trunc:end-trunc);

% calculate lsb size and dnl
lsb= sum(hlin_trunc) / (length(hlin_trunc));
dnl= [0 hlin_trunc/lsb-1];
misscodes = length(find(dnl<-0.9));

% calculate inl
inl= cumsum(dnl);

% plot
figure(1);
subplot(2,1,1)
plot(minbin+trunc:maxbin-trunc, dnl);
xlabel('code');
ylabel('DNL [LSB]');
title(['DNL = +',num2str(max(dnl),2),' / ',num2str(min(dnl),2),' LSB,  ', num2str(misscodes), ' missing codes (DNL<-0.9)'])
subplot(2,1,2)
plot(minbin+trunc:maxbin-trunc, inl);
xlabel('code');
ylabel('INL [LSB]');
title(['INL = +',num2str(max(inl),2),' / ',num2str(min(inl),2),' LSB '])






