function [gpsWeek,gpsSec] = datetime2gps(T)
% datetime2gps : Convert times expressed as unzoned Matlab datetimes to times
%                expressed in GPS week and GPS seconds of week.
%       
%
% INPUTS
%
% T -------------- N-by-1 vector of time points expressed as unzoned Matlab
%                  datetimes.
%
%
% OUTPUTS
%
% gpsWeek -------- N-by-1 vector of unambiguous GPS week numbers, where zero
%                  corresponds to 00:00:00 on the morning of 6 January, 1980.
%                  By unambiguous is meant the full week count since the 1980
%                  reference time (no rollover at 1024 weeks).
%
% gpsSec --------- N-by-1 vector of times of week expressed as GPS seconds
%                  elapsed since 00:00:00 Sunday morning, with sub-0.2-ns
%                  resolution.
%
%+------------------------------------------------------------------------------+
% References:
%
%
% Author:  Todd Humphreys
%+==============================================================================+

%% Ensure that input is a vector of unzoned datetime objects
if(~isdatetime(T))
  error('Input must be a vector of datetime objects');
end
if(~isempty(T.TimeZone))
  error('Input datetime(s) must be unzoned');
end
nT = length(T);

%% Perform conversion
Tsec = T.Second;
T.Second = zeros(nT,1);
Tref = datetime(1980,1,6,0,0,0);
% Note that because T and Tref are unzoned, this difference ignores leap
% seconds, which is the desired behavior.
dT = T(:) - Tref;
gpsWeek = floor(days(dT)/7);
% Fractional seconds are added separately to preserve resolution
gpsSec = seconds(dT - days(gpsWeek*7)) + Tsec;
