%polarizationModel1 TR 38.901 Section 7.3.2 polarization Model-1
%  A_prime_fn: linear antenna radiation power pattern function 
%              A = A_prime_fn(theta_prime,phi_prime)
% theta_prime: zenith angle in LCS
% phi_prime  : azimuth angle in LCS
% zeta       : polarization slant angle

%   Copyright 2017-2020 The MathWorks, Inc.

%#codegen

function F = polarizationModel1(A_prime_fn,theta_prime,phi_prime,zeta)
    
    % Zenith field component as a function of LCS angles
    F_theta_prime_prime = sqrt(A_prime_fn(theta_prime,phi_prime));
    
    % Rotation matrix elements cos(Psi) and sin(Psi) for an angular
    % displacement of Psi due to the orientation of the LCS w.r.t. the GCS
    den = sqrt(1 - ((cosd(zeta).*cosd(theta_prime)) - (sind(zeta).*sind(phi_prime).*sind(theta_prime))).^2);
    cosPsi = ((cosd(zeta).*sind(theta_prime)) + (sind(zeta).*sind(phi_prime).*cosd(theta_prime))) ./ den;
    sinPsi = (sind(zeta).*cosd(phi_prime)) ./ den;
    
    % Assume vertical polarization in cases where the transformation
    % degenerates, this is, when theta_prime is near zeta or 180-zeta and
    % phi_prime is near -90 or 90, respectively. When zeta = 0/180, any
    % value of phi_prime makes the transformation degenerate. The threshold
    % (10^-5) is the upper bound of the magnitude error outside a region of
    % radius ~10^-4 degrees around the singularity. Within that region, the
    % polarization angle error can be arbitrary.
    degen = isnan(cosPsi) | isnan(sinPsi) | ( abs(hypot(sinPsi,cosPsi) - 1) > 1e-5 );
    if any(degen(:))
        cosPsi(degen) = 1;
        sinPsi(degen) = 0;
    end
    
    % Equation 7.3-3 evaluated with F_phi_prime_prime = 0
    F = [F_theta_prime_prime.*cosPsi; F_theta_prime_prime.*sinPsi];  
    
end
