function [d] = gcdist(X,Y,flag)
% GCDIST Great circle distance (km) between to lon,lat points (in degrees)
%
%     d = gcdist(X,Y) where X and Y are two (lon,lat) points 
%     If flag=0 or not set, includes effect of eccentricity of sphere (ecc=0.081082).
%     flag=1 is for a perfect sphere. 
%

if ndims(X) ~= 2  error('Data X must be vector or 2-D array.'); end
if ndims(Y) ~= 2  error('Data Y must be vector or 2-D array.'); end
if nargin < 3 flag=0; end

if flag 
  ecc=0;
else
  ecc = 0.081082; % Eccentricity
end

eqrad = 6378; % km Equatorial radius (surface to center distance)
        
lon1=X(1)*pi/180; % longitude 
lat1=X(2)*pi/180; % latitude 
lon2=Y(1)*pi/180; % longitude 
lat2=Y(2)*pi/180; % latitude 

rad = eqrad * sqrt(1 - ecc^2) / (1 - ecc^2 * (sin(lat1))^2); %radius of curvature
dlon = lon2 - lon1;
dlat = lat2 - lat1;

a = (sin(dlat/2)).^2 + cos(lat1).*cos(lat2).*(sin(dlon/2)).^2;
b = 2 * atan2( sqrt(a),sqrt(1-a) );

d = rad.*b;