function [spec_pH, spec_T, CTD_T, CTD_Sal, vrse] = processSprayCalibration(specdata, spraydata)
% Automatically calculate mean values from spray test tank calibration and parse data from spec pH. 
% Ben Werb | bwerb@mbari.org | 4/11/2024    
%% spec pH
    % Read the table from the spec pH text file
    specpH = readtable(specdata);

    % Filter out rows where the 'Comments' column contains 'junk'
    filteredSpecpH = specpH(~contains(specpH.Comments, 'junk'), :);

    % Select the first row from the filtered data
    firstRow = filteredSpecpH(1, :);

    % Extract the pH value
    spec_pH = firstRow.pH_tot;
    spec_T = firstRow.Temp_used;

    [indices, selectedLines] = indexLinesWithPattern(spraydata, 'Z_1>');
    data = cellstr(selectedLines);
    data = data(~contains(data,'SBE'));

    for i = 1:height(data)
        data(i,1:3) = strsplit(char(data(i)),'  ');
    end

    data = str2double(data);
    mn = mean(data);

    CTD_T = mn(1,2);
    CTD_Sal = mn(1,3);

    
    [indices, selectedLines] = indexLinesWithPattern(spraydata, 'A_1>');
    vrsedata = cellstr(selectedLines);
    vrsedata = vrsedata(contains(vrsedata,'ch = '));
    
    for i = 1:height(vrsedata)
        vrsedata(i,1:9) = strsplit(char(vrsedata(i)),'\t');
    end
    
    vrse = str2double(vrsedata(:,4)); % 4 is vrse, 5 is vrse std. date, time imports as datetime (1 col not 2)
    vrse = mean(vrse);
end

function [indices, selectedLines] = indexLinesWithPattern(filename, pattern)
    % Read the file into a cell array of strings
    fileContent = readlines(filename);
    
    % Initialize output variables
    indices = [];
    selectedLines = {};
    
    % Loop through each line to find the pattern
    for i = 1:length(fileContent)
        % Check if the line contains the pattern
        if contains(fileContent(i), pattern)
            % Store the index
            indices(end+1) = i;
            % Select the line with the pattern and the next four lines
            selectedBlock = fileContent(i+1:min(i+1, end));
            % Append the selected block to the output cell array
            selectedLines = [selectedLines; selectedBlock];
        end
    end
end