%% Two-Line Element Reader
% Author: Jack Naylor
% SID: 470354333

% Description:
% This function reads a text file of two-line elements and converts the
% values from a text based to a numerical format for a nominated object.

% Inputs:
% satName = string corresponding to name of satellite in tle file
% tleFile = text file containing TLE strings

% Outputs:
% satVals = 1x10 vector of orbital parameters
% epochTime = 1x2 vector of epoch year and days corresponding to TLE

%% Functions
function [satVals, epochTime] = tleRead(satName, tleFile)
    
    % Read the TLE file and split lines
    tle = fileread(tleFile);
    tle = splitlines(tle);
    
    % Find the index of the satellite name in the TLE file
    tleIndex = strfind(tle, satName);
    tleIndex = find(~cellfun(@isempty,tleIndex));
    
    % If satellite not found, default to error to prevent issues with
    % orbital simulation
    if isempty(tleIndex)
        error('SATELLITE NOT FOUND! CHECK SATELLITE NAME!')
    end
    
    % Retrieve both lines of the TLE and convert to character array
    tle = tle(tleIndex+1:tleIndex+2);
    line1 = char(tle(1));
    line2 = char(tle(2));
    
    % Retrieve mean motion derivative and BSTAR drag value from Line 1
    nDot = str2num(line1(34:43));
    nDotDot = sign(str2num([line1(45) '1']))*str2num(['0.' line1(46:50)])*10^(str2num(line1(51:52)));
    bSTAR = sign(str2num([line1(54) '1']))*str2num(['0.' line1(55:59)])*10^(str2num(line1(60:61)));
    
    % Retrieve orbital parameters from line 2
    i = str2num(line2(9:16));           % Inclination (deg)
    RAAN = str2num(line2(18:25));       % Right ascension of the ascending node (deg)
    e = str2num(['0.' line2(27:33)]);   % Eccentricity
    omega = str2num(line2(35:42));      % Argument of perigee (deg)
    M0 = str2num(line2(44:51));         % Mean anomaly at epoch (deg)
    n = str2num(line2(53:63));          % Mean motion (revs/day)
    revNum = str2num(line2(64:68));     % Revolution number corresponding to TLE
    
    % Concatenate values in to solution vector
    satVals = [e i RAAN omega n nDot nDotDot bSTAR M0 revNum];
    
    % Obtain epoch year and day corresponding to TLE
    epochYear = str2num(line1(19:20));
    epochDay = str2num(line1(21:32));
    epochTime = [epochYear epochDay];

end