% Microsoft Access was giving me trouble, so we are using Excel as a
% database for now.
fname_CalibrationLog = '\\atlas.shore.mbari.org\ProjectLibrary\901805_Coastal_Biogeochemical_Sensing\nanoFET\CalibrationLog.xlsx';
% Read each worksheet as a table
GliderFETID = 'GliderFET007';

PTC = readtable(fname_CalibrationLog, 'Sheet', 'PTC');
% PTC = PTC(ismember(PTC.GliderFETID,GliderFETID),:); % Get only active sensor data

k0 = readtable(fname_CalibrationLog, 'Sheet', 'k0');
% k0 = k0(ismember(k0.GliderFETID,GliderFETID),:); % Get only data from active sensor
k0 = sortrows(k0, 'CalibrationDate', 'descend'); % Sort by CalibrationDate (most recent first)
[~, firstIdx] = unique(k0.GliderFETID, 'stable'); % Keep only the most recent entry
k0 = k0(firstIdx, :);

% Join tables on the common key column 'GliderFETID'
% Cal = join(PTC, k0, 'Keys', 'GliderFETID'); % Join PTC and k0 on 'GliderFETID'

%

data = readtable("NanoFETS\04_09_25_k0.csv");
data.pHin = NaN(size(data.Vrse));

%

% data = data(ismember(data.COM,'COM6'),:);
FETID = {'GliderFET006', 'GliderFET005', 'GliderFET007'};
COMPORT = {'COM4', 'COM5', 'COM6'}; % fets: 6, 5, 7
for i = 1:3
    idx_k0 = ismember(k0.GliderFETID,FETID(i));
    idx_PTC = ismember(PTC.GliderFETID,FETID(i));
    idx = ismember(data.COM,COMPORT(i));
    data.pHin(idx) = calc_pHext(data.Vrse(idx),data.Temperature(idx),data.Salinity(idx),k0.k0_seawater(idx_k0),PTC.k2F_P_C0(idx_PTC));
end

%

data.COM = categorical(data.COM);

%

gscatter(data.DateTime,data.pHin,data.COM)

%

%% FETS 8-11

%

data = readtable("NanoFETS\04_24_25_k0.csv");
data.pHin = NaN(size(data.Vrse));

%

% data = data(ismember(data.COM,'COM6'),:);
FETID = {'GliderFET008', 'GliderFET009', 'GliderFET010', 'GliderFET011'};
COMPORT = {'COM3', 'COM4', 'COM5', 'COM6'};
for i = 1:4
    idx_k0 = ismember(k0.GliderFETID,string(FETID(i)));
    idx_PTC = ismember(PTC.GliderFETID,string(FETID(i)));
    idx = ismember(data.COM,COMPORT(i));
    data.pHin(idx) = calc_pHext(data.Vrse(idx),data.Temperature(idx),data.Salinity(idx),k0.k0_seawater(idx_k0),PTC.k2F_P_C0(idx_PTC));
end

%

data.COM = categorical(data.COM);

%

gscatter(data.DateTime,data.pHin,data.COM)

%

% FETS 13 - 16

%

data = readtable("NanoFETS\04_24_25_k0.csv");
data.pHin = NaN(size(data.Vrse));

%

% data = data(ismember(data.COM,'COM6'),:);
FETID = {'GliderFET013', 'GliderFET014', 'GliderFET015', 'GliderFET016'};
COMPORT = {'COM3', 'COM4', 'COM5', 'COM6'};
for i = 1:4
    idx_k0 = ismember(k0.GliderFETID,string(FETID(i)));
    idx_PTC = ismember(PTC.GliderFETID,string(FETID(i)));
    idx = ismember(data.COM,COMPORT(i));
    data.pHin(idx) = calc_pHext(data.Vrse(idx),data.Temperature(idx),data.Salinity(idx),k0.k0_seawater(idx_k0),PTC.k2F_P_C0(idx_PTC));
end

%

data.COM = categorical(data.COM);

%

gscatter(data.DateTime,data.pHin,data.COM)