%% Get the names of all files in the directory
folder = 'C:\Users\bwerb\Documents\thoon_ww\ncfiles';
fileList = dir(folder);
fileNames = {fileList.name};
fileNames = fileNames(~ismember(fileNames, {'.', '..'}));

%% Loop through to get the k0 for each nc file
n = length(fileNames);
for i = 1:n
    file = char(fileNames(i));
    [ww] = readncTHOON(file,0); % file, don't save
    %% Estimating pH using CanyonB NN algorithm
    
    gtime = repmat(ww.Datenum,height(ww.Depth),1); % All dimensions must agree
    lat = repmat(ww.Latitude,height(ww.Depth),1);
    lon = repmat(ww.Longitude,height(ww.Depth),1);
    pres = ww.Pressure;
    temp = ww.Temperature;
    psal = ww.Practical_Salinity;
    doxy = ww.Dissolved_Oxygen;
    
    CanyonB_pH = CANYONB(gtime,lat,lon,pres,temp,psal,doxy,'pH'); % insitu total scale
    
    % % Convert from CANYONB pH insitu to spec pH insitu using Carter et al 2018 Eq. 1
    % CanyonB_pH_insitu_spec = CanyonB_pH.pH + (CanyonB_pH.pH*0.0404 - 0.3168);
    % not sure if this is necessary
    
    %% Recalculate k0 with pH estimated w/ CanyonB from deep upwelled water 
    k0_gdf5 = -1.4214; % Lab calibration
    k2_gdf5 = -9.66638e-04; % Lab calibration

    % Averaging the 20 deepest measurements because ww doesn't always
    % complete a full profile cycle
    % Vext = mean(ww.pH_voltage(1:20,:),"all",'omitmissing');
    % TC = mean(ww.Temperature(1:20,:),"all",'omitmissing');
    % sal = mean(ww.Practical_Salinity(1:20,:),"all",'omitmissing');
    % pH_insitu = mean(CanyonB_pH.pH(1:20,:),"all",'omitmissing'); % Estimated pH_insitu with CanyonB NN

    Vext = ww.pH_voltage;
    TC = ww.Temperature;
    sal = ww.Practical_Salinity;
    pH_insitu = CanyonB_pH.pH; % Estimated pH_insitu with CanyonB NN
    [k0, Eo_ext_insitu] = calc_k0_ext(Vext, TC, sal, pH_insitu, k2_gdf5); % Bresnahan et al. 2014
    ww.k0_adj = k0;

    % k0_new(i) = mean(k0,'omitmissing');
    % disp(['k0 new: ', num2str(k0_new) ', k0 old: ', num2str(k0_gdf5)])
end
