clear; format compact; format short; clc; cla;

%% zadani -----------------------------------------------------------------
cm = load('cov_mat.txt'); % kvariancni matice
ss = load('sour.txt'); % seznam souradnic

%% reseni -----------------------------------------------------------------
d0 = diag(cm,0);
d1 = diag(cm,1);
varx = d0(1:2:end);
vary = d0(2:2:end);
cov = d1(1:2:end);
c = sqrt( (varx-vary).^2 + 4*cov.^2 );
a = sqrt( 0.5*(varx+vary+c) );
b = sqrt( 0.5*(varx+vary-c) );
alfa = atan2( 2*cov, varx-vary )/2;
alfa(alfa<0) = alfa(alfa<0)+pi;

% output table ------------------------------------------------------------
out_matrix = [ ss(:,1),a,b,alfa*200/pi ];
fprintf( '  c.b.   a    b   uhel\n----------------------\n')
fprintf( '% 5.0f % 4.1f % 4.1f % 6.1f\n', out_matrix' )

%% GRAF -------------------------------------------------------------------
hold on;

%% elipsy
Q = 5; % zvetseni elips v tisicich
[x,y] = elipsa(a,b);

% konfidencni elipsy chyb
q = Q*repmat(2.45,size(x,1));
[Xk,Yk] = trn(x,y,q,alfa,ss(:,2),ss(:,3));

P = pi*a.*b;
colors = hsv( 10*ceil(max(P)) );
for i = 1:length(P)
    j = round(P(i)*10); % index pro barvy
    if( j==0 ) color = colors(1,:);
    else color = colors( j,: );
    end
    patch(Xk(i,:)',Yk(i,:)', color );
end

% stredni elipsy chyb
q = Q*repmat(1,size(x,1));
[Xs,Ys] = trn(x,y,q,alfa,ss(:,2),ss(:,3));
plot(Xs',Ys','black')

%% body
plot( ss(:,2),ss(:,3),'LineStyle','none', ...
                      'Marker','o', ...
                      'MarkerEdgeColor',[0.75 0.75 1] )
set( gca,'XAxisLocation','top','YAxisLocation','right', ...
         'XDir','reverse','YDir','reverse', ...
         'XLim',[960 1255],'YLim',[4850 5020], ...
         'DataAspectRatio',[1 1 1] );

% popis bodu
shift_x = -7;
shift_y = 0;
for i=1:size(ss,1)
    h_text = text( ss(i,2)+shift_x, ss(i,3)+shift_y, sprintf('%.0f',ss(i,1)) );
    set( h_text,'FontWeight','bold' );
end








