function G = geoidd(lat1,lng1,lat2,lng2)

% function G = geoidd(lat1,lng1,lat2,lng2)
% Calculates the geodetic distance in degrees (G) between two points
% (P1(lat1,lng2),P2(lat2,lng2).
% Latitude range: -90N to 90N
% Longitude range: 0E to 360E
% cp from KQ 5.5.00

if(lat1==lat2 & lng1==lng2);G=0;
else
   lat1 = lat1/180*pi;
   lng1 = lng1/180*pi;
   lat2 = lat2/180*pi;
   lng2 = lng2/180*pi;

   x1 = cos(lat1).*cos(lng1);
   y1 = cos(lat1).*sin(lng1);
   z1 = sin(lat1);
   x2 = cos(lat2).*cos(lng2);
   y2 = cos(lat2).*sin(lng2);
   z2 = sin(lat2);
   Arg = x1.*x2 + y1.*y2 + z1.*z2;
   G = acos(Arg)*180/pi;

% Where P1(i) = P2(i), then G(i) := 0 (sometimes gives NaN)
% Also check for antipodes... (sometimes give NaN)
   i = find(Arg > 1.0); G(i) = 0.0;
   i = find(Arg < -1.0); G(i) = 180.0;

% Check for values of G less than 0 and greater than 180,
% and adjust accordingly to be in range of 0 to 180.
   i = find(G < 0.0); G(i) = -1.0*G(i);
   i = find(G > 180.0); G(i) = 360.0 - G(i);
end
