% TEST_One_vs_Many.m
%
% Compares the k2 pressure corrected f(P) of a particular GDF run versus
% the same parameters of a subset of GDF runs
%
% USER MUST ENTER VARIABLES TO EXTRACT
%
% Ben Davis 
% 05/15/2022
%
clear
close all

addpath(genpath(pwd));
% ================== USER INPUTS =======================================

% Enter variable names as displayed in .mat file
% e.g. Var1 = 'variable';
Var1 = 'g';
Var2 = 'iPdecrease';
Var3 = 'iPincrease';

% ==================================================================

%% Selecting the dataset
% Select the "One" calibration run to compare

fprintf(['Select the calibration run to compare (One).',...
        '\nMust be in Performances directory in GDF Production\n'])

% Select .mat file
[fname_one, pathname_one] = uigetfile('*.mat',...
               'Select a .mat file from the Performances directory to compare (One)',...
               '\\atlas\Chem\DuraFET\GDF Production\Performances\');
fpath_one = [pathname_one,fname_one];

% Loading variables
myVars = {Var1,Var2,Var3};
O = load(fpath_one, myVars{:});

% Getting time elapsed for "one"
te = datenum(O.g.DT(1));
te = datenum(O.g.DT) - te;

% Writing specific table using these variables

% f(P) k2 pressure corrected and corrected data for decreasing pressure in
% table T: pressure, f(P) k2 corr, temperature, f(P) normal,
T_one = [O.g.pres(O.iPdecrease), O.g.fp_k2variable(O.iPdecrease), O.g.TC(O.iPdecrease), O.g.fP(O.iPdecrease), te(O.iPdecrease)];

O.pres = linspace(1,2000)';

O.p1 = polyfit(T_one(:,1),T_one(:,2),7); % seventh degree, 6th order default
O.fP1 = polyval(O.p1,O.pres);


% % title of plot
% title_one = fname_one(1:end-4);

%% Switch Cases

many = input(['\n',...
              'Enter a number to select what',...
              '\ndataset to plot against (1-5):',...
              '\nNote: 3-5 do not work in this version',...
              '\n1 --- AE',...
              '\n2 --- New Gaskets from AE',...
              '\n3 --- Prunella Manufactured GDFs',...
              '\n4 --- Machined Corners',...
              '\n5 --- Broached Corners',...
              '\n---OR---',...
              '\n6 --- Select your own dataset\n',...
              '\n']);

switch many
        case 1
            title_many = 14;
            disp('AE Sensors')
        case 2
            title_many = 15;
            disp('AE with New Gaskets')
        case 3
            title_many = 'Prunella Manufactured GDFs';
            disp(title_many)
        case 4
            title_many = 'Machined Corners';
            disp(title_many)
        case 5
            title_many  = 'Broached Corners';
            disp(title_many)
        case 6
            disp('Select your own .mat files')
            % Select .mat file
            % Prompt the user to select multiple files
            [fileName, pathName, filterIndex] = uigetfile('*.*', 'Select files from Data directory', ...
                '\\atlas\Chem\DuraFET\GDF Production\Data\mat Files\', ...
                'MultiSelect', 'on');
            
            % Check if the user clicked 'Cancel'
            if isequal(fileName, 0)
                disp('User canceled file selection.');
                return;
            end
            
            % If only one file is selected, uigetfile returns a char instead of a cell array
            if ischar(fileName)
                % Convert to a cell array for consistency
                fileName = {fileName};
            end
            
            % Display selected file names and path
            disp('Selected files:');
            disp(fileName);
            disp('Selected path:');
            disp(pathName);
    otherwise
            disp('Select a number between 1-6 ya filthy scallywag')
end

while many < 1 || many > 6 || round(many) ~= many
    many = input(['\n',...
              'Enter a number to select what',...
              '\ndataset to plot against (1-5):',...
              '\nNote: 3-5 do not work in this version',...
              '\n1 --- AE',...
              '\n2 --- New Gaskets from AE',...
              '\n3 --- Prunella Manufactured GDFs',...
              '\n4 --- Machined Corners',...
              '\n5 --- Broached Corners',...
              '\n---OR---',...
              '\n6 --- Select your own dataset\n',...
              '\n']);
    switch many
        case 1
            title_many = 14;
            disp('AE Sensors')
        case 2
            title_many = 15;
            disp('AE with New Gaskets')
        case 3
            title_many = 'Prunella Manufactured GDFs';
            disp(title_many)
        case 4
            title_many = 'Machined Corners';
            disp(title_many)
        case 5
            title_many  = 'Broached Corners';
            disp(title_many)
        case 6
            disp('Select your own .mat files')
                        % Select .mat file
            % Prompt the user to select multiple files
            [fileName, pathName, filterIndex] = uigetfile('*.*', 'Select files from Data directory', ...
                '\\atlas\Chem\DuraFET\GDF Production\Data\mat Files\', ...
                'MultiSelect', 'on');
            
            % Check if the user clicked 'Cancel'
            if isequal(fileName, 0)
                disp('User canceled file selection.');
                return;
            end
            
            % If only one file is selected, uigetfile returns a char instead of a cell array
            if ischar(fileName)
                % Convert to a cell array for consistency
                fileName = {fileName};
            end
            
            % Display selected file names and path
            disp('Selected files:');
            disp(fileName);
            disp('Selected path:');
            disp(pathName);
        otherwise
            disp('Select a number between 1-6 ya filthy scallywag')
    end
end

%% Importing the "Many" Data
% Either personally selected files or predetermined Testlog subsets

if many == 6
    % Pre-allocation
    M.fP = zeros(100,length(fileName));
    for i = 1:length(fileName)
        T_many(i) = load([pathName,char(fileName(i))], myVars{:});
        M.pM = polyfit(T_many(i).g.pres(T_many(i).iPdecrease),T_many(i).g.fp_k2variable(T_many(i).iPdecrease),7);
        M.fP(:,i) = polyval(M.pM,O.pres);
    end
else
    % Paths to extract the test log data and .mat files from the
    % upload_pTC_cal.m script
    M.path = '\\atlas\Chem\DuraFET\GDF Production\Performances\';
    M.testlog_path = '\\atlas\Chem\DuraFET\GDF Production\Test Log\Test Log.xlsx';
    % Copying Files
    copyfile(M.testlog_path,pwd);
    % Reading the manually updated Test Log
    M.testlog = readtable('Test Log.xlsx','PreserveVariableNames',true); 
    
    % TEST CODE NEXT 6 LINES
    % Sorting through test log and taking out any that are not what was
    % selected. 'AE' is test case
    % ind = M.testlog.AE;
    % ind(isnan(ind)) = 0; ind = logical(ind);
    % M.list_SN = M.testlog.SN(ind); 
    % M.list_FN = M.testlog.NameOfFolder(ind);
    
    % To do this for an input number, make INPUT string tied to number that
    % corresponds to column. The use:
    ind = M.testlog(:,title_many); ind = table2array(ind);
    ind(isnan(ind)) = 0; ind = logical(ind);
    M.list_SN = M.testlog.SN(ind); 
    M.list_FN = M.testlog.NameOfFolder(ind);
    
    % Pre-allocation
    M.fP = zeros(100,height(M.list_SN));
    for i = 1:height(M.list_SN)
        T_many(i) = load([M.path,char(M.list_SN(i)),'\',char(M.list_FN(i)),'\',char(M.list_FN(i)),'.mat'], myVars{:});
        M.pM = polyfit(T_many(i).g.pres(T_many(i).iPdecrease),T_many(i).g.fp_k2variable(T_many(i).iPdecrease),7);
        M.fP(:,i) = polyval(M.pM,O.pres);
    end
end

%% Calculation for the "Many" Data

mX   = median(M.fP,2,'omitnan')';
sX   = std(M.fP,[],2,'omitnan')';

bot_many = mX - 1.*sX; % 1 sigma bottom boundary
top_many = mX + 1.*sX; % 1 sigma top boundary


%% Plotting

figure(1);
   % Plotting the shaded region
    inBetweenRegionX = [1:20.2:2020, 2000:-20.19:1];
    inBetweenRegionY = [top_many, fliplr(bot_many)];
    % Display the area first so it will be in the background.
    fill(inBetweenRegionX, inBetweenRegionY, [0.9290 0.6940 0.1250]); alpha(0.25);
    hold on; box on; grid on;
    plot(O.pres,top_many,'LineWidth',2,'Color',[0.9290 0.5940 0.1250]); hold on;
    plot(O.pres,bot_many,'LineWidth',2,'Color',[0.9290 0.5940 0.1250]); hold on;
%     plot(O.pres,mX,'LineWidth',3.5,'Color',[0.25 0.65 0.55]); hold on;  
    plot(O.pres,O.fP1, 'o','MarkerEdgeColor',[0.8500 0.3250 0.0980],'MarkerSize',12,'MarkerFaceColor',[0.815 0.5 0.5]);
    ylabel('f(P,k_2(P),T) [mV]','FontSize',18);
    xlim([0 2100]);
    xlabel('Pressure [dBar]','FontSize',18);
    title('f(P) Comparisons');
    subtitle('Comparing the fits of "One" run vs. "Many"')
    f.ax = gca; f.ax.Color = [0.9 0.9 0.9];
    f.ax.FontSize = 16; f.ax.FontWeight = 'Bold';
    O.l = legend('"Many" Data','1 Standard Dev Bounds','','"One" Calibration Run');
    set(O.l,'Interpreter','none');

figure(2);
   % Plotting the shaded region
    inBetweenRegionX = [1:20.2:2020, 2000:-20.19:1];
    inBetweenRegionY = [top_many, fliplr(bot_many)];
    % Display the area first so it will be in the background.
    fill(inBetweenRegionX, inBetweenRegionY, [0.15 0.65 0.75]); alpha(0.25);
    hold on; box on; grid on;
    plot(O.pres,top_many,'LineWidth',2,'Color',[0.25 0.65 0.55]); hold on;
    plot(O.pres,bot_many,'LineWidth',2,'Color',[0.25 0.65 0.55]); hold on;
%     plot(O.pres,mX,'LineWidth',3.5,'Color',[0.25 0.65 0.55]); hold on;  
    plot(T_one(:,1),T_one(:,2), 'o','MarkerEdgeColor',[0.8500 0.3250 0.0980],'MarkerSize',12,'MarkerFaceColor',[0.815 0.5 0.5]);
    ylabel('f(P,k_2(P),T) [mV]','FontSize',18);
    xlim([0 2100]);
    xlabel('Pressure [dBar]','FontSize',18);
    title('f(P) Comparisons');
    subtitle('Raw data of "One" run vs. "Many"')
    f.ax = gca; f.ax.Color = [0.9 0.9 0.9];
    f.ax.FontSize = 16; f.ax.FontWeight = 'Bold';
    O.l = legend('"Many" Data','1 Standard Dev Bounds','','"One" Calibration Run');
    set(O.l,'Interpreter','none');

%% Josh's Plot Code (not needed)
% figure(2)
P = O.pres;
fillX  = [[mX-1*sX;flipud(mX+1*sX)],[P';flipud(P')]];


% p(i) = plot(O.fP1, mX, P', '-', ...
%                     'Color', 'g', 'LineWidth',1);
% 
% FX = patch(O.fp1', fillX(:,1), fillX(:,2), 'g');
% plot( mX, P', '-', ...
%                     'Color', 'g', 'LineWidth',1);
% % 
% FX = patch( fillX(:,1), fillX(:,2), 'g');
% FX.FaceAlpha = 0.1';
% FX.LineStyle = 'none';
