%o2.m

clear;
raw = '2016Jul12';
path =    sprintf('../%s/raw',raw);
outfile = sprintf('../%s/parsed/CPF%sO2.mat',raw,raw);
o2_raw_file = sprintf('../%s/parsed/CPF%sO2_RAW.txt',raw,raw);

fileList = dir(path);
fileList = fileList(~[fileList.isdir]); %remove directories
[junk, sortorder] = sort([fileList.datenum]);
fileList = fileList(sortorder); %list is now in ascending date order
numfiles = numel(fileList);
%In = cell(numfiles,1);
optodeIndex=1;
o2FID = fopen(o2_raw_file,'w');


for fileno = 1:numfiles
   fp = sprintf('%s/%s',path,fileList(fileno).name);
   fprintf('Processing %s\n',fp);
   inFID = fopen(fp);
   %get the header line
   inString = fgets(inFID);
    
    while ~feof(inFID)
        inString = fgets(inFID);
        inFields = strsplit(inString, '\t', 'CollapseDelimiters', false);
        
    if ( strcmp(inFields{5}, 'Optode Message') && strncmp(inFields{4},'Ascend',6) ) 
        if(strfind(inFields{16}, '4330') > 0)
            optodeFields = strsplit(inFields{16}, ',', 'CollapseDelimiters', false);
             optodeDate(optodeIndex, :) = inFields{2};
             optodeTime(optodeIndex, :) = inFields{3};
             optodeDateTimeNum(optodeIndex) = datenum(strcat(inFields{2}, 'T', inFields{3}));
%             optodeState{optodeIndex} = inFields{4};
%             optodeComment{optodeIndex} = inFields{5};
            optodeDepth(optodeIndex) = -str2double(inFields{6});
            optodeO2Conc(optodeIndex) = str2double(optodeFields{4});
            optodeAirSat(optodeIndex) = str2double(optodeFields{6});
            optodeTemp(optodeIndex) = str2double(optodeFields{8});
%             optodeCalPhase(optodeIndex) = str2double(optodeFields{11});
%             optodeTCPhase(optodeIndex) = str2double(optodeFields{13});
%             optodeC1RPh(optodeIndex) = str2double(optodeFields{15});
%             optodeC2RPh(optodeIndex) = str2double(optodeFields{17});
%             optodeC1Amp(optodeIndex) = str2double(optodeFields{19});
%             optodeC2Amp(optodeIndex) = str2double(optodeFields{21});
%             optodeRawTemp(optodeIndex) = str2double(optodeFields{23});
            
             fprintf(o2FID, '%s,%f %f\n', ...
                 inFields{16},optodeDepth(optodeIndex),optodeDateTimeNum(optodeIndex));
            
            optodeIndex = optodeIndex + 1;
        end
    end
         
    end %end inFID parse
    fclose(inFID);
end %for fileno

save(outfile);
fclose(o2FID);