function [data] = fast_textread (filename,cols,lastHeaderLine,varNameTrue)

% Reads whitespace delimited text files of any length.  Allows for header
% lines and variable names at the beginning of the file.  Must know the
% number of data columns.  If no variable name line is given, assigns
% generic variable names of the form 'var1', 'var2', etc.  Returns a
% structure containing header lines in the cell array data.header.
% Variables are returned in separate fields, data.varName1, etc.

% ** DOES NOT CHECK FOR ERRORS IN INPUT PARAMETERS ** You must know the
% number of columns and header lines.  The variable names, if present, must
% be one line only, immediately after the header lines and immediately
% before the data lines.

% usage:    [data] = fast_textread('myData.txt',20,2,1)
%
% where:        - myData.txt = data file in the current directory
%               - myData.txt has 20 columns of numbers to load
%               - there are 2 rows of header text
%               - there is a line of variable names (after header)
%
%           [data] = fast_textread('myData2.txt',10,0,0)
%
%               - file myData2.txt has 10 columns and no header or variable
%                   name information.
% BWB 11/20/05

fid = fopen(filename);

data = struct;  %initialize structure

% Header, if it exists, is above column labels line
if lastHeaderLine > 0
    for i = 1:lastHeaderLine
        HeaderLine = textscan(fid,'%[^\n]',1);
        data.header(i) = HeaderLine;
    end
end

% Assume column labels are in a single row, just above data rows
if varNameTrue ~= 0    % read one line if varNameTrue is not zero
    
    % Read whole line and parse into cell array - # labels unknown
    colLabels = textscan(fid,'%[^\n]',1);
    colLabelStr = char(colLabels{1});
    VarNameArray = ParseSentence(colLabelStr); % make array of variable names
    
    if size(VarNameArray)~=cols
        error ('Error: # cols not equal to number of column labels');
    end
else
    for i = 1:cols
        VarNameArray(i) = {strcat('var',int2str(i))}; % make variable names
    end
end

% prepare format string for numeric data
fmtStr = '';
for i = 1:cols
    fmtStr = strcat('%n', fmtStr);
end

% Get the data
data.dataArray = textscan(fid,fmtStr,'TreatAsEmpty','******');

% Copy data from array into individual fields
for i = 1:cols
   name = VarNameArray{i};               % get name of requested variable
   column = data.dataArray{i};          % copy out column of data
   data = setfield(data, name, column);   % add column to structure
end

% Kill dataArray field
data = rmfield(data, 'dataArray');

fclose(fid);

% END
