%% Spec pH casts
c01 = readSpec_SBB25("C:\Users\bwerb\Documents\SBB25\pH_QC\20251023_DP_M1_29625c01_QC");
c02 = readSpec_SBB25("C:\Users\bwerb\Documents\SBB25\pH_QC\20251024_DP_29725C02_QC");
c03 = readSpec_SBB25("C:\Users\bwerb\Documents\SBB25\pH_QC\20251025_DP_29725c03_QC");
c04 = readSpec_SBB25("C:\Users\bwerb\Documents\SBB25\pH_QC\20251025_DP_29725c04_QC");
c05 = readSpec_SBB25("C:\Users\bwerb\Documents\SBB25\pH_QC\20251025_DP_29725c05_QC");
c06 = readSpec_SBB25("C:\Users\bwerb\Documents\SBB25\pH_QC\20251025_DP_29725c06_QC");
c07 = readSpec_SBB25("C:\Users\bwerb\Documents\SBB25\pH_QC\20251026_DP_29825c07_QC");
% Apply to all casts c01-c07
% Direct approach without eval
c01_bottleNums = regexp(c01.Comments, '_(\d+)', 'tokens', 'once');
c01.Bottle = cellfun(@(x) str2double(x{1}), c01_bottleNums);

c02_bottleNums = regexp(c02.Comments, '_(\d+)', 'tokens', 'once');
c02.Bottle = cellfun(@(x) str2double(x{1}), c02_bottleNums);

c03_bottleNums = regexp(c03.Comments, '_(\d+)', 'tokens', 'once');
c03.Bottle = cellfun(@(x) str2double(x{1}), c03_bottleNums);

c04_bottleNums = regexp(c04.Comments, '_(\d+)', 'tokens', 'once');
c04.Bottle = cellfun(@(x) str2double(x{1}), c04_bottleNums);

c05_bottleNums = regexp(c05.Comments, '_(\d+)', 'tokens', 'once');
c05.Bottle = cellfun(@(x) str2double(x{1}), c05_bottleNums);

c06_bottleNums = regexp(c06.Comments, '_(\d+)', 'tokens', 'once');
c06.Bottle = cellfun(@(x) str2double(x{1}), c06_bottleNums);

c07_bottleNums = regexp(c07.Comments, '_(\d+)', 'tokens', 'once');
c07.Bottle = cellfun(@(x) str2double(x{1}), c07_bottleNums);

disp('Added Bottle column to c01-c07');
%% CTD bottle casts
% Get list of .btl files
btl_files = dir('CTD Data/*.btl');
file_names = {btl_files.name};

% Read files 1-7
c01_btl = readbtl(fullfile('CTD Data', file_names{1}));
c02_btl = readbtl(fullfile('CTD Data', file_names{2}));
c03_btl = readbtl(fullfile('CTD Data', file_names{3}));
c04_btl = readbtl(fullfile('CTD Data', file_names{4}));
c05_btl = readbtl(fullfile('CTD Data', file_names{5}));
c06_btl = readbtl(fullfile('CTD Data', file_names{6}));
c07_btl = readbtl(fullfile('CTD Data', file_names{7}));
%% Join
% Join all casts with their btl data
for i = 1:7
    cast_name = sprintf('c%02d', i);
    btl_name = sprintf('c%02d_btl', i);
    
    % Get variables from workspace
    cast_data = evalin('base', cast_name);
    btl_data = evalin('base', btl_name);
    
    % Join on Bottle column
    cast_data = join(cast_data, btl_data, 'Keys', 'Bottle');
    % cast_data = cast_data(:,{"Comments",'Bottle','PrDM','Sbeox0ML_L','Salinity','pH_tot','Sal00','SigmaE00',})
    % Save back
    assignin('base', cast_name, cast_data);
    writetable(cast_data,fullfile('files_csv',[cast_name,'.csv']))
    fprintf('Joined %s with %s - now %d columns\n', cast_name, btl_name, width(cast_data));
end