function [secid,date1,exdate,cp_flag,strike_price,best_bid,best_offer,volume,open_interest,impl_volatility,delta,optionid,index_flag,issuer,exercise_style] = importfile(filename, startRow, endRow)
%IMPORTFILE Import numeric data from a text file as column vectors.
%   [SECID,DATE1,EXDATE,CP_FLAG,STRIKE_PRICE,BEST_BID,BEST_OFFER,VOLUME,OPEN_INTEREST,IMPL_VOLATILITY,DELTA,OPTIONID,INDEX_FLAG,ISSUER,EXERCISE_STYLE]
%   = IMPORTFILE(FILENAME) Reads data from text file FILENAME for the
%   default selection.
%
%   [SECID,DATE1,EXDATE,CP_FLAG,STRIKE_PRICE,BEST_BID,BEST_OFFER,VOLUME,OPEN_INTEREST,IMPL_VOLATILITY,DELTA,OPTIONID,INDEX_FLAG,ISSUER,EXERCISE_STYLE]
%   = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows STARTROW
%   through ENDROW of text file FILENAME.
%
% Example:
%   [secid,date1,exdate,cp_flag,strike_price,best_bid,best_offer,volume,open_interest,impl_volatility,delta,optionid,index_flag,issuer,exercise_style] = importfile('option_prices.csv',2, 7385063);
%
%    See also TEXTSCAN.

% Auto-generated by MATLAB on 2016/06/08 18:41:57

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

%% Read columns of data as strings:
% For more information, see the TEXTSCAN documentation.
formatSpec = '%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%[^\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, 'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
for block=2:length(startRow)
    frewind(fileID);
    dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, '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);

%% Convert the contents of columns containing numeric strings to numbers.
% Replace non-numeric strings with NaN.
raw = repmat({''},length(dataArray{1}),length(dataArray)-1);
for col=1:length(dataArray)-1
    raw(1:length(dataArray{col}),col) = dataArray{col};
end
numericData = NaN(size(dataArray{1},1),size(dataArray,2));

for col=[1,5,6,7,8,9,10,11,12,13,14]
    % Converts strings in the input cell array to numbers. Replaced non-numeric
    % strings with NaN.
    rawData = dataArray{col};
    for row=1:size(rawData, 1);
        % Create a regular expression to detect and remove non-numeric prefixes and
        % suffixes.
        regexstr = '(?<prefix>.*?)(?<numbers>([-]*(\d+[\,]*)+[\.]{0,1}\d*[eEdD]{0,1}[-+]*\d*[i]{0,1})|([-]*(\d+[\,]*)*[\.]{1,1}\d+[eEdD]{0,1}[-+]*\d*[i]{0,1}))(?<suffix>.*)';
        try
            result = regexp(rawData{row}, regexstr, 'names');
            numbers = result.numbers;
            
            % Detected commas in non-thousand locations.
            invalidThousandsSeparator = false;
            if any(numbers==',');
                thousandsRegExp = '^\d+?(\,\d{3})*\.{0,1}\d*$';
                if isempty(regexp(numbers, thousandsRegExp, 'once'));
                    numbers = NaN;
                    invalidThousandsSeparator = true;
                end
            end
            % Convert numeric strings to numbers.
            if ~invalidThousandsSeparator;
                numbers = textscan(strrep(numbers, ',', ''), '%f');
                numericData(row, col) = numbers{1};
                raw{row, col} = numbers{1};
            end
        catch me
        end
    end
end

dateFormatIndex = 1;
blankDates = cell(1,size(raw,2));
anyBlankDates = false(size(raw,1),1);
invalidDates = cell(1,size(raw,2));
anyInvalidDates = false(size(raw,1),1);
for col=[2,3]% Convert the contents of columns with dates to MATLAB datetimes using date format string.
    try
        dates{col} = datetime(dataArray{col}, 'Format', 'MM/dd/yyyy', 'InputFormat', 'MM/dd/yyyy'); %#ok<SAGROW>
    catch
        try
            % Handle dates surrounded by quotes
            dataArray{col} = cellfun(@(x) x(2:end-1), dataArray{col}, 'UniformOutput', false);
            dates{col} = datetime(dataArray{col}, 'Format', 'MM/dd/yyyy', 'InputFormat', 'MM/dd/yyyy'); %%#ok<SAGROW>
        catch
            dates{col} = repmat(datetime([NaN NaN NaN]), size(dataArray{col})); %#ok<SAGROW>
        end
    end
    
    dateFormatIndex = dateFormatIndex + 1;
    blankDates{col} = cellfun(@isempty, dataArray{col});
    anyBlankDates = blankDates{col} | anyBlankDates;
    invalidDates{col} = isnan(dates{col}.Hour) - blankDates{col};
    anyInvalidDates = invalidDates{col} | anyInvalidDates;
end
dates = dates(:,[2,3]);
blankDates = blankDates(:,[2,3]);
invalidDates = invalidDates(:,[2,3]);

%% Split data into numeric and cell columns.
rawNumericColumns = raw(:, [1,5,6,7,8,9,10,11,12,13,14]);
rawCellColumns = raw(:, [4,15]);


%% Replace non-numeric cells with NaN
R = cellfun(@(x) ~isnumeric(x) && ~islogical(x),rawNumericColumns); % Find non-numeric cells
rawNumericColumns(R) = {NaN}; % Replace non-numeric cells

%% Allocate imported array to column variable names
secid = cell2mat(rawNumericColumns(:, 1));
date1 = dates{:, 1};
exdate = dates{:, 2};
cp_flag = rawCellColumns(:, 1);
strike_price = cell2mat(rawNumericColumns(:, 2));
best_bid = cell2mat(rawNumericColumns(:, 3));
best_offer = cell2mat(rawNumericColumns(:, 4));
volume = cell2mat(rawNumericColumns(:, 5));
open_interest = cell2mat(rawNumericColumns(:, 6));
impl_volatility = cell2mat(rawNumericColumns(:, 7));
delta = cell2mat(rawNumericColumns(:, 8));
optionid = cell2mat(rawNumericColumns(:, 9));
index_flag = cell2mat(rawNumericColumns(:, 10));
issuer = cell2mat(rawNumericColumns(:, 11));
exercise_style = rawCellColumns(:, 2);

% For code requiring serial dates (datenum) instead of datetime, uncomment
% the following line(s) below to return the imported dates as datenum(s).

% date1=datenum(date1);
% exdate=datenum(exdate);


