function d = parse_PTchamber_file(PTfile)

% CHANGES:
% 03/17/22 - JP - added code block to test for older file format (i.e
%     DF207)and change a couple header column names in the header line
% 11/23/22 - JP modifed seach for info structure data to deal with new SBE
%     raw data dir
% 01/06/2023 - JP added a 3rd date sting format variant to deal with Yui's
% most recent file format


% *************************************************************************
% % TESTING
% dirs.data = 'C:\Users\jplant\Documents\MATLAB\Apps\pH_Calibration\test data\';
% %fn        = 'DF#306&VL#306_chB-201104.csv';
% fn        = 'GDF6_initial_cal.csv';
% dirs.data = 'C:\temp\';
% % % %fn        = 'DF#313&VL#313_chB-210308.csv';
% % % fn        = 'DF#314&VL#314_chA-210318.csv';
% %fn        = 'DF#317&VL#317_chB-210325.csv'
% fn        = 'DF#309&VL#309_chA-210218.csv';
% PTfile    = [dirs.data,fn];
%PTfile    = 'C:\temp\DF#207&VL#207chC-170630peekV3.csv';
%PTfile    = 'C:\temp\DF#297&VL#297_chA-200928.csv';

%PTfile    = 'C:\temp\chanA_SBE11372_LPH_030322.csv';
%PTfile    = 'C:\temp\chanA_SBE T114_0207122.csv';
%PTfile    = 'C:\temp\chanA_SBE11372_LPH_030322.csv';
%PTfile    = 'C:\temp\chanA_GDF020_031622.csv';
%PTfile    = 'C:\temp\chanA_GDF_016_021822.csv';

%PTfile    = 'C:\temp\DF#12028&VL#11932_chE-20220811.csv'; %SBS FILE from Charlie
%PTfile    = 'C:\temp\DF#378&VL#378_chA-221109.csv'; %mbari file
%PTfile    = 'C:\temp\DF#11779&VL#11819_chF-20220721.csv'; %SBE from charlie
%PTfile    = 'C:\temp\DF#12115&VL#12006_chD-20220830.csv'; %SBE from charlie
%PTfile    = '\\atlas\chem\DuraFET\CALIBRATION\K2_SBE_PTChamber_data\DF#12115&VL#12006_chD-20220830.csv'; %SBE from charlie

%PTfile    = 'C:\temp\DF371_123122_chC_jp.csv'; % Yui's now PT file with added columns

% *************************************************************************


% GET DF SN FROM FILE NAME - THIS ASSUMES A CONSISTENT PATTERN & THAT THE
% FILE IS NAMED CORRECTELY
tmp = regexp(PTfile, filesep,'split');
fn = tmp{end};
fd = regexprep(PTfile,fn,'');

% GET SN FIRST
sn_filt_exp = '(?<=DF\#*\_*)\d+|(?<=SBE\s*)([A-Z]*\d+)'; % this should get # from DF,GDF,SBE
%DF_SN = regexp(PTfile,sn_filt_exp,'once','match');
DF_SN = regexp(fn,sn_filt_exp,'once','match');

% GET CHANNEL
channel_filt_str = '(?<=\_*ch(an)*)[A-E]{1}';
%DF_CH = regexp(PTfile, channel_filt_str,'once','match');
DF_CH = regexp(fn, channel_filt_str,'once','match');

%GET SENSOR TYPE
type_filt_str = 'GDF|DF|SBE';
%DF_TYPE = regexp(PTfile, type_filt_str,'once','match');
DF_TYPE = regexp(fn, type_filt_str,'once','match');

clear tmp




% *************************************************************************
% PARSE DATA FILE
fid = fopen(PTfile);

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

% FIND HEADER LINE
tline = ' ';
while ischar(tline)
    if regexp(tline,'^Labview','once')
        break
    end
    tline = fgetl(fid);
end
hdr = regexp(tline,',','split');

% BUILD DATA FORMAT STRING FROM HEADER LINE
dfmt =[];
hdr_flag = ones(size(hdr));
for i = 1:size(hdr,2)
    if regexp(hdr{i},'^Lab|^DATE')
        dfmt = [dfmt,'%s'];
    elseif regexp(hdr{i},'CRC|^ID|^UTC|^CTD|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));

t1 = ~cellfun(@isempty,regexp(tmp{1,1},'^Labview','once'));


if sum(t1) > 0
    disp('Multiple header lines detected - scanning line by line')
        frewind(fid);
    tline = ' ';
    ct = 0;
    tmp1 = cell(2e4,size(hdr,2));
    tmp = cell(1,size(hdr,2));
    while ischar(tline)
        if regexp(tline,'^\d+/','once')
            ct = ct+1;
            tmp1(ct,:) = textscan(tline, dfmt,'Delimiter',',','CommentStyle','H');
        end
        tline = fgetl(fid);
    end
    tmp1 = tmp1(1:ct,:);
    
    % NOW MAKE SHAPE SIMILAR to TEXTSCAN(fid) output
    for i = 1: size(hdr,2)
        if regexp(hdr{i},'^Lab|^DATE')
            tmp{i} = cellfun(@cellstr,tmp1(:,i));
        else
            tmp{i} = cell2mat(tmp1(:,i));
        end
    end
end

fclose(fid);

% ************************************************************************
% PUT CELL DATA INTO DATA MATRIX

% CHECK DATE/TIME FORMAT BEFORE CONVERTING - A COUPLE FLAVORS
iLV_SDN  = find(strcmp(hdr,'Labview Date/Time') == 1);
iDT_SDN  = find(strcmp(hdr,'DATE TIME') == 1);

% look for year in date string to confirm valid date string
tg_LV_SDN = ~cellfun(@isempty, regexp(tmp{1,iLV_SDN},'\d{4}','once'));
tg_DT_SDN = ~cellfun(@isempty, regexp(tmp{1,iDT_SDN},'\d{4}','once'));

if sum(~tg_LV_SDN) > 0
    fprintf(['WARNING: Improper Labview Date/Time string(s) detected. ', ...
        'Posibly a bad data line(s) in input file\n']);
end
if sum(~tg_DT_SDN) > 0
    fprintf(['WARNING: Improper DATE TIME string(s) detected. Posibly a bad ', ...
        'data line(s) in input file\n']);
end

LABV_SDN = ones(size(tg_LV_SDN)) * NaN; % predim incase bad SDN strings
DT_SDN   = LABV_SDN;

if regexp(tmp{1,iLV_SDN}{1},'AM|PM','once')
    LABV_SDN(tg_LV_SDN) = datenum(tmp{1,iLV_SDN}(tg_LV_SDN),'mm/dd/yyyy HH:MM:SS AM');
else
    LABV_SDN(tg_LV_SDN) = datenum(tmp{1,iLV_SDN}(tg_LV_SDN),'mm/dd/yyyy HH:MM');
end
tmp{1,1} = LABV_SDN;

iDT_SDN  = find(strcmp(hdr,'DATE TIME') == 1);
if regexp(tmp{1,iDT_SDN}{1},'AM|PM','once')
    DT_SDN(tg_DT_SDN)   = datenum(tmp{1,iDT_SDN}(tg_DT_SDN),'mm/dd/yyyy HH:MM:SS AM');
elseif regexp(tmp{1,iDT_SDN}{1},'\d+/\d+/\d{4} \d{2}:\d{2}:\d{2}','once')
    DT_SDN(tg_DT_SDN)   = datenum(tmp{1,iDT_SDN}(tg_DT_SDN),'mm/dd/yyyy HH:MM:SS');
else
    DT_SDN(tg_DT_SDN)   = datenum(tmp{1,iDT_SDN}(tg_DT_SDN),'mm/dd/yyyy HH:MM');
end
tmp{1,iDT_SDN} = DT_SDN;
data = cell2mat(tmp);

% Remove any NaN date rows ( these wher bad date strings set = NaN)
tnan = isnan(data(:,iLV_SDN)) | isnan(data(:,iDT_SDN));
data = data(~tnan,:);

% CHECK FOR OLDER LABVIEW FILE FORMAT (i.e DF207) 
% Just needed to change the name of a coiuple of the header names
if sum(strcmp(hdr,'Max Flow'),2) == 0
    hdr = regexprep(hdr,' Pressure','Pressure (dBar)');
    hdr = regexprep(hdr,' Bath Temp','Bath Temp');
%     iP  = find(strcmp(hdr,'Pressure (dBar)') ==1);
%     hdr = [hdr(1:iP), 'Max Flow' 'Flow Rate' 'Pump Volume',hdr(iP+1:end)];
%     data = [data(:,1:iP), data(:,1)+NaN*[1 1 1], data(:,iP+1:end)];
end


d.hdr = hdr;
d.data = data;
d.info.SourceDir  = fd;
d.info.SourceFile = fn;
d.info.DF_SN      = DF_SN;
d.info.DF_CH      = DF_CH;
d.info.DF_TYPE    = DF_TYPE;

clearvars -except d





