%CPR decoder Airborne position

% DF17
% TC 9 10 11 12 13 14 15 16 17 18

%Source : Tesi Simon - Dekodovanie 1090 ES
%Preklad do Matlabu by Martin Zach

%input = message field 112bit hexadecimal

%Volat funkci stylem: [Rlat,Rlon]=CPR_Air_decoder('8D40622B58C3A15698D6FDA4B222')

function [Rlat,Rlon]=fce_DF17_TC9_22_krom19_CPR_Air_decoder(MSG_112_hex)

format long

% MSG_112_hex='8D40622B58C3A15698D6FDA4B222';

A=MSG_112_hex(9:22);

B=hexToBinaryVector(A,56);
CPR_TYPE=B(22);
CPR_LAT=B(23:39);
CPR_LONG=B(40:56);
CPR_LAT_dec=polyval(CPR_LAT,2);
CPR_LONG_dec=polyval(CPR_LONG,2);

latS=50.0804889; % Referencni zemepisna sirka
lonS=14.3956972; % Referencni zemepisna delka

NZ=15; % Pocet sektoru
i=polyval(CPR_TYPE,2); % Formát CPR odd/even

Nb=17; %Pocet bitu zpravy - Airborne 17 / surface 19

XZ=CPR_LONG_dec;
YZ=CPR_LAT_dec;

%------------------------------Zemepisna sirka-----------------------------

Dlat=360/(4*NZ-i);

j1=latS/Dlat;
j2=0.5+(mod(latS,Dlat))/Dlat-YZ/(2^Nb);
j=floor(j1)+floor(j2);

Rlat=Dlat*(j+YZ/(2^Nb));

%------------------------------Zemepisna delka-----------------------------

NL_Rlat1=1-(1-cos(pi/(2*NZ)))/((cos((pi/180)*abs(Rlat)))^2);
NL_Rlat2=acos(NL_Rlat1);
NL_Rlat3=NL_Rlat2^(-1);
NL_Rlat4=NL_Rlat3*2*pi;
NL_Rlat=floor(NL_Rlat4);

NL_Rlat_Dlon=NL_Rlat-i;

if NL_Rlat_Dlon>0
    
    Dlon=360/NL_Rlat_Dlon;
    
elseif NL_Rlat_Dlon==0
    
    Dlon=360;
    
end

m1=lonS/Dlon;
m2=0.5+(mod(lonS,Dlon))/Dlon-XZ/(2^Nb);
m=floor(m1)+floor(m2);

Rlon=Dlon*(m+XZ/(2^Nb));

end