function d = parse_k0_SW_file(k0SW_file)


% *************************************************************************
% % TESTING
% dirs.data = 'C:\Users\jplant\Documents\MATLAB\Apps\pH_Calibration\test data\';
% fn        = 'MSC0904_DURA_2.dat';
% fn        = 'MSC0904_DURA.dat';

% dirs.data = 'C:\temp\';
% fn        = 'MSC0951_DURA_2.dat';
% %fn        = 'MSC0951_DURA.dat';
% 
% k0SW_file = [dirs.data,fn];


% *************************************************************************
% GET MSC FROM FILE NAME - THIS ASSUMES A CONSISTENT PATTERN & THAT THE
% FILE IS NAMED CORRECTELY
MSC = regexp(k0SW_file,'(?<=MSC)\d+','once','match');

% GET FILE NAME FROM PATH TOO
tmp = regexp(k0SW_file,'\','split');
fn  = tmp{end};
fd  = regexprep(k0SW_file,fn,'');
clear tmp

% DEFAULT HEADER IN CASE HDR LINES MISSING IN TXT FILE
hdr ={'CRC','ID','DATE TIME','UTC SECS','CTD DEPTH','CTD TEMP', ...
    'CTD SALINITY','SAMPLE COUNTER','POR COUNTER','DURA_ERROR COUNTER', ...
    'HOUSING TEMPERATURE','HOUSING HUMIDITY','INPUT VOLTAGE',...
    'INPUT CURRENT','FOOBAR PH VALUE','BACKUP BATTERY','VRS VOLTS',...
    'VRS STDDEV','VK VOLTS','VK STDDEV','IK AMPS','IB AMPS'};
% *************************************************************************
% PARSE DATA FILE
fid = fopen(k0SW_file);

if fid == -1
    disp(['Could not open: ',k0SW_file])
    d.data = [];
    d.hdr = {};
    return
end

% FIND HEADER LINE
tline = ' ';
while ischar(tline)
    if regexp(tline,'^CRC','once')
        tline = regexprep(tline,', ',',');
        hdr = regexp(tline,',','split');
        break
    elseif regexp(tline,'^0x','once')
        disp('No headerline found before date lines - using default header');
        frewind(fid)
        break
    end
    tline = fgetl(fid);
end

% BUILD DATA FORMAT STRING FROM HEADER LINE
dfmt =[];
hdr_flag = ones(size(hdr));
for i = 1:size(hdr,2)
    if regexp(hdr{i},'^DATE')
        dfmt = [dfmt,'%s'];
    elseif regexp(hdr{i},['^CRC|^ID|^UTC|POR COUNTER$|POR COUNTER$|', ...
            'ERROR COUNTER|^FOO'])
        dfmt = [dfmt,'%*s'];
        hdr_flag(i) = 0;
    else
        dfmt = [dfmt,'%f'];
    end
end
tmp = textscan(fid, dfmt,'Delimiter',',','CommentStyle','H');
hdr = hdr(logical(hdr_flag));

fclose(fid);


% ************************************************************************
% PUT CELL DATA INTO DATA MATRIX
iSDN  = find(strcmp(hdr,'DATE TIME') == 1);
SDN   = datenum(tmp{1,iSDN},'mm/dd/yyyy HH:MM:SS');
tmp{1,iSDN} = SDN;

data = cell2mat(tmp);
d.hdr = hdr;
d.data = data;

d.info.SourceDir  = fd;
d.info.SourceFile = fn;
d.info.MSC     = MSC;

clearvars -except d





