function Analyzexfet(sensorfile,specpHfile,CTDfile,savefigs)
% Analyze pH measured by xfet boards and lab calculated pH.
% sensorfile: xfet data is generated by the board and typically follows
% the format yyyymmdd.txt
% specpHfile: lab generated spec pH measurements.
% CTDfile: CTD data taken from the wet lab download from
% http://pubdata.mlml.calstate.edu/mlml_last/seawater/
% Written by Ben Werb 2/29/24. Many of functions and code taken...
% from Joe Warren and Jacki Long.

DataStart(sensorfile); % edits the file to be readable by matlab
MetaStart(sensorfile);
SensorData = readdata('datafile.txt'); % reads xfets and creates struct
MetaData = readmeta('metafile.txt');
delete('datafile.txt') % removes file created by DataStart
delete('metafile.txt') % removes file created by DataStart
SpecpHData = readspecpH(specpHfile); 
CTD = readCTD(CTDfile);

[~, iCTD, idata] = intersect(CTD.utc_time,SensorData.SampTime1);
SensorData = SensorData(idata,:);
CTD = CTD(iCTD,:);
[~ ,~ , ispec] = intersect(CTD.utc_time,SpecpHData.DateTime);
SpecpHData = SpecpHData(ispec,:);
% Explore sensor data
EDA(SensorData)
WarmUpTime(SensorData)
Compare(SensorData)

% Calculate pH Insitu
pH_insitu = spec_pH_insitu(SpecpHData);

% Calculate sensor pH measurements
spH = pH_insitu(SpecpHData.QC);

k0_1 = nan(length(SensorData.Vrse1),2);
for i = 1:length(SpecpHData.pH_tot(SpecpHData.QC))
    [k0_1(:,i), ~] = calc_k0_ext(SensorData.Vrse1, CTD.temp,...
        CTD.sal, spH(i), 'UseDefaultk2');
end
k0_1 = mean(k0_1,'all');

[pHext_tot1, pHext_free1] = calc_dfet_pHext_k0(SensorData.Vrse1,...
    CTD.temp, CTD.sal, k0_1, 'UseDefaultk2'); 
%%
k0_2 = nan(length(SensorData.Vrse2),2);
for i = 1:length(SpecpHData.pH_tot(SpecpHData.QC))
    [k0_2(:,i), ~] = calc_k0_ext(SensorData.Vrse2, CTD.temp,...
        CTD.sal, spH(i), 'UseDefaultk2');
end
k0_2 = mean(k0_2,'all');

[pHext_tot2, pHext_free2] = calc_dfet_pHext_k0(SensorData.Vrse2,...
    CTD.temp, CTD.sal, k0_2, 'UseDefaultk2'); % 

% Plot sensor pH and specto pH
pH = pHPlots(SensorData, SpecpHData, pHext_tot1, pHext_tot2);

if ismember(savefigs,'savefigs')
    print(mfet,['mfetEDA',sensorfile(1:end-4)],'-dpdf','-fillpage')
    print(nano,['nanoEDA',sensorfile(1:end-4)],'-dpdf','-fillpage')
    print(Comp, ['Compare',sensorfile(1:end-4)],'-dpdf','-fillpage')
    print(pH, ['pHPlots',sensorfile(1:end-4)],'-dpdf','-fillpage')
end
end