function [dir, incl] = cartsphere(n, e, d, type)
% CARTSPHERE Calculates planar or linear spherical information from direction cosines.
%   [TREND, PLUNGE] = CARTSPHERE(N, E, D, 1) returns the trend and plunge of a line
%   described by the input N, E, and D direction cosines.
%
%   [STRIKE, DIP] = CARTSPHERE(N, E, D, 2) returns the strike and dip of a plane
%   whose pole is described by the input N, E, and D direction cosines.
%
%   Angles are returned in degrees, with strike and dip given according to right-hand
%   rule.
%

% Correct any negative plunges
n(d < 0) = -n(d < 0);
e(d < 0) = -e(d < 0);
d = abs(d);

% Calculate plunge
incl = atan2(d, sqrt(n.^2+e.^2))*180/pi;

% Calculate trend
dir = atan2(e, n)*180/pi;

% Correct any negative trends
dir(dir < 0) = dir(dir < 0) + 360;

% If necessary, calculate plane strike and dip from pole trend and plunge
if type == 1
   return
elseif type == 2
   incl = 90 - incl;
   dir = dir + 90;
   % Correct any strikes greater than 360
   dir(dir >= 360) = dir(dir >= 360) - 360;
else
   error('Specify TYPE = 1 for lines or TYPE = 2 for planes.')
end
