function table = import_l5(filename, startRow, endRow)
%IMPORT_L5 Import numeric data from a text file as column vectors.
%   table = IMPORT_L5(FILENAME) Reads data from text file FILENAME for the default
%   selection.
%
%   TABLE = IMPORT_L5(FILENAME, STARTROW, ENDROW) Reads data from rows STARTROW
%   through ENDROW of text file FILENAME.
%
% Example:
%   TABLE = import_l5('RPCICA150317T04_000_L5_MOMENT.TAB');
%   TABLE = import_l5('RPCICA150317T04_000_L5_MOMENT.TAB', 1, 16384);
%

%% Initialize variables.
delimiter = ',';
if nargin<=2
    startRow = 1;
    endRow = inf;
end

%% Format string for each line of text:
%   column1: text (%s) iontime
%   column2: double (%f) delta_t
%   column3: double (%s) quality flag
%   column4: double (%f) mode
%   column5: double (%f) noise_reduction
%   column6: double (%f) mtable
%   column7: double (%f) pacc
%   column8: double (%f) azimuth
%   column9: double (%f) elev
%   column10: double (%f) mass

%   column11-column18: double (%f) ionspectra 8 levels
% or
%   column11-column42: double (%f) ionspectra 32 levels
% or
%   column11-column106: double (%f) ionspectra 96 levels
%
% For more information, see the TEXTSCAN documentation.
formatSpec = ['%s' repmat('%f', 1, 7) '%q%[^\n\r]'];

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this code. If
% an error occurs for a different file, try regenerating the code from the
% Import Tool.
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'EmptyValue' ,NaN,'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
for block=2:length(startRow)
    frewind(fileID);
    dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'EmptyValue' ,NaN,'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
    for col=1:length(dataArray)
        dataArray{col} = [dataArray{col};dataArrayBlock{col}];
    end
end

%% Close the text file.
fclose(fileID);

%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for unimportable
% data, select unimportable cells in a file and regenerate the script.

%% Allocate imported array to column variable names
table.time = datenum(dataArray{1}, 'yyyy-mm-ddTHH:MM:SS.FFF');
table.mass = dataArray{2};
table.charge = dataArray{3};
table.density =  dataArray{4};
table.density(table.density >= 9.999e99) = NaN;
table.v = [dataArray{5} dataArray{6} dataArray{7}];
table.duration = dataArray{8};
table.quality = dataArray{9};

