function y = bipolaradc(x,Vfs,N)
%bipolaradc Bipolar analog-to-digital converter (ADC)
%   X = bipolaradc(X,VFS,N) simulates the quantization and saturation
%   errors introduced by an N-bit ADC with full scale voltage of VFS to
%   input X and returns the quantized and saturated output Y. The output
%   levels are -VFS:LSB:VFS-LSB, where LSB=VFS/2^(N-1).
%
%   See also comm.AGC, iqimbal.

%   Copyright 2020-2023 The MathWorks, Inc.

%#codegen

validateattributes(Vfs, {'numeric'}, ...
  {'scalar','finite','positive','nonnan'}, mfilename,'VFS')
validateattributes(N, {'numeric'}, ...
  {'scalar','finite','positive','nonnan'}, mfilename,'N')

LSB = Vfs / 2^(N-1);
MAX = Vfs - LSB;
MIN = -Vfs;

yI = LSB * round(real(x)/LSB);
yQ = LSB * round(imag(x)/LSB);
yI(yI>MAX) = MAX;
yQ(yQ>MAX) = MAX;
yI(yI<MIN) = MIN;
yQ(yQ<MIN) = MIN;

y = yI + 1i*yQ;
end
