%% Function to implement spatial sigma-delta ADC
% X - input, psi - steering angle, d -  antenna spacing (in wavelengths)
% b - quantization voltage level
% c - clipper level

function Y = sigma_delta_ADC(X, psi, d, b)

    [M N] = size(X);
    angle_rad = 2*pi*d*sin((psi*pi/180));
    c = b*(2 - abs(cos(angle_rad)) - abs(sin(angle_rad))); 
    X_c = L_c(X,c); % clipped output X_c =   L_c(X)

    
    W = exp((1i*angle_rad)); 
    Y = zeros(M,N);
    err = zeros(M,N);
    Y(1,:) = b.*sgn(X_c(1,:));
    err(1,:) = W.*(X_c(1,:) - Y(1,:));
    for i = 2:M
        Y(i,:) = b.*sgn( X_c(i,:) + err(i-1,:));
        err(i,:) = W.*((X_c(i,:) + err(i-1,:) - Y(i,:)));
    end

end

% Amplitude limiter

function X_c = L_c(X,lev)

    [M N] = size(X);

    % Input clipping

    X_r = real(X);
    X_i = imag(X);

    for i=1:M
        for j=1:N
            if(abs(X_r(i,j))>lev)
                X_r(i,j) = lev*sign((X_r(i,j)));
            end
            if(abs(X_i(i,j))>lev)
                X_i(i,j) = lev*sign((X_i(i,j)));
            end
        end
    end

    X_c = X_r + (1j).*X_i;  % amplitude limited signal

end


% 1-bit quantizer

function x = sgn(y)

    x_re = sign(real(y));
    x_im = sign(imag(y));
    for i = 1:length(y)
        if(x_re(i) >= 0)
            x_re(i) = 1;
        end
        if(x_im(i) >= 0)
            x_im(i) = 1;
        end
    end

    x = x_re + (1i)*x_im;
end