% [data, variablename] = loadHitachiText(filename)
%   filename: the name of the file you want to load.  This file has to be
%   the text file (.csv file) you export from Hitachi ETG-4000 NIRS
%   data: a matrix containing the data in file
%   variablename: a cellarray containing the names of each column
%
%   filename: the file name (.csv file) you export from Hitachi software
%   data: the data in matrix
%   variablename: the name for each column of data
%
% Xu Cui, 2007/9/12
% modified: 2017/3/16, some data contains invalid timestamp, take care of
% it

function [data, variablename] = loadHitachiText(filename)

fid1 = fopen(filename, 'rt');
fid2 = fopen('temp.cui', 'wt');

timedata = [];
startData = 0;
while 1
    tline = fgetl(fid1);
    if ~ischar(tline), break, end
    if(strcmp(tline, 'Data'))
        tline0 = fgetl(fid1);
        variablename = strread(tline0,'%s','delimiter',',');
        timeindex = find(strcmp(variablename,'Time'));
        startData = 1;
        continue;
    end
    
    if(startData==1)
        fprintf(fid2, '%s\n', tline);
        tmp = strread(tline,'%s','delimiter',',');
        tmp2 = time2double(tmp{timeindex});
        if isempty( tmp2 )
            timedata = [timedata; 0];
        else
            timedata = [timedata; tmp2];
        end        
    end
end

fclose(fid1);
fclose(fid2);

data = load('temp.cui');
data(:, timeindex) = timedata;


if length(variablename) ~= size(data,2)
    warning('The number of columns in data and in heading are different.');
end

delete('temp.cui');

return;