function [DLT_result,R_matrix,DET] = DLT(AGrid)

% Prima linearni transformace - viz kniha Close Range photogrammetry, str.
% 212-213 - jedna se o linearizovany primy vypocet linearnich nebo
% linearizovanych parametru kamery

%VYPOCET PARAMETRU DLT

for i=1:size(AGrid,1)                                                       %sestaveni DLT matice

    A(2*i-1,1) = AGrid(i,2);
    A(2*i-1,2) = AGrid(i,3);
    A(2*i-1,3)=AGrid(i,4);
    A(2*i-1,4)=1;
    A(2*i-1,5)=0;
    A(2*i-1,6)=0;
    A(2*i-1,7)=0;
    A(2*i-1,8)=0;
    A(2*i-1,9)=-AGrid(i,5)*AGrid(i,2);
    A(2*i-1,10)=-AGrid(i,5)*AGrid(i,3);
    A(2*i-1,11)=-AGrid(i,5)*AGrid(i,4);

    A(2*i,1)=0;
    A(2*i,2)=0;
    A(2*i,3)=0;
    A(2*i,4)=0;
    A(2*i,5)=AGrid(i,2);
    A(2*i,6)=AGrid(i,3);
    A(2*i,7)=AGrid(i,4);
    A(2*i,8)=1;
    A(2*i,9)=-AGrid(i,6)*AGrid(i,2);
    A(2*i,10)=-AGrid(i,6)*AGrid(i,3);
    A(2*i,11)=-AGrid(i,6)*AGrid(i,4);
   
    xy(2*i-1)=AGrid(i,5);
    xy(2*i)=AGrid(i,6);
    
end    

xy = xy.';
 
L = A\xy;                                                                   %vypocet DLT

%VYPOCET PARAMETRU KAMERY

Lvst = -1/sqrt(L(9)^2+L(10)^2+L(11)^2);                                     %pomocny parametr

x0_cam = Lvst^2*(L(1)*L(9)+L(2)*L(10)+L(3)*L(11));                          %principalni bod
y0_cam = Lvst^2*(L(5)*L(9)+L(6)*L(10)+L(7)*L(11));

cx = sqrt((Lvst^2)*(L(1)^2+L(2)^2+L(3)^2)-x0_cam^2);                        %ohniskova vzdalenost ve smeru osy x a y
cy = sqrt(Lvst^2*(L(5)^2+L(6)^2+L(7)^2)-y0_cam^2);

r11 = -(Lvst*(x0_cam*L(9)-L(1)))/cx;                                        %prvky matice rotace
r12 = -(Lvst*(y0_cam*L(9)-L(5)))/cy;
r13 = -Lvst*L(9);
r21 = -(Lvst*(x0_cam*L(10)-L(2)))/cx;
r22 = -(Lvst*(y0_cam*L(10)-L(6)))/cy;
r23 = -Lvst*L(10);
r31 = -(Lvst*(x0_cam*L(11)-L(3)))/cx;
r32 = -(Lvst*(y0_cam*L(11)-L(7)))/cy;
r33 = -Lvst*L(11);

R_matrix=[r11 r12 r13;r21 r22 r23;r31 r32 r33];

L2 = [L(1) L(2) L(3);                                                       %pomocne matice
    L(5) L(6) L(7);
    L(9) L(10) L(11)];                                                                           
L3 = [L(4);L(8);1];

T_vector = -inv(L2)*L3;                                                     %vypocet polohy stredu promitani od pocatku s.s X0,Y0,Z0

Vzd = [0];

DET = round(det(R_matrix));                                                 %vypocet determinantu matice rotace - jestlize je zaporny, nejedna se o matici rotace ale o matici zrcadleni, takova matice nelze prevest na Eulerovy uhly

R_matrix = DET*R_matrix;

%VYPOCET UHLU Z MATICE ROTACE

Angles = Mat2Eul(R_matrix);                                                 %vypocet uhlu

Omega = Angles(1);
Fi = Angles(2);
Kapa = Angles(3);

DLT_result=[Vzd;T_vector(1);T_vector(2); T_vector(3);Omega;Fi;Kapa;x0_cam;y0_cam;cx;cy];
                                                                            %zapis vysledku
end

