clear all
close all

opts = delimitedTextImportOptions("NumVariables", 30);

% Specify range and delimiter
opts.DataLines = [25, Inf];
opts.Delimiter = ",";

% Specify column names and types
%opts.VariableNames = ["LabviewDateTime", "ThermistorTemp", "BathTemp", "BathSetPoint", "PressuredBar", "MaxFlow", "FlowRate", "PumpVolume", "CRC", "ID", "DATETIME", "UTCSECS", "CTDDEPTH", "CTDTEMP", "CTDSALINITY", "SAMPLECOUNTER", "RESETCOUNTER", "ERRORCOUNTER", "HOUSINGTEMPERATURE", "HOUSINGHUMIDITY", "INPUTVOLTAGE", "INPUTCURRENT", "FOOBARPHVALUE", "BACKUPBATTERY", "VRSVOLTS", "VRSSTDDEV", "VKVOLTS", "VKSTDDEV", "IKAMPS", "IBAMPS"];
%opts.VariableNames = ["dtLV",   "thermTemp", "bathTemp", "bathSP", "pressureDBar", "maxFlow", "flowRate", "cycleNum", "pumpVolume", "CRC", "ID", "dateTime", "utcSecs", "ctdDepth", "ctdTemp", "ctdSalinity", "sampleCounter", "resetCounter", "errorCounter", "housingTemp", "housingHumidity", "inputVoltage", "inputCurrent", "foobarPHValue", "backupBattery", "vrsVolts", "vrsStdDev", "vkVolts", "vkStdDev", "ikAmps", "ibAmps"];
%opts.VariableTypes = ["datetime", "double", "double",   "double", "double",         "double", "double",     "double",   "double", "string", "categorical", "datetime", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double"];
%For the new VI with SetTemp, SetPressure and StepNum
opts.VariableNames = ["dtLV",   "thermTemp", "bathTemp", "bathSP", "pressureDBar", "maxFlow", "flowRate", "pumpVolume", "CRC", "ID", "dateTime", "utcSecs", "ctdDepth", "ctdTemp", "ctdSalinity", "sampleCounter", "resetCounter", "errorCounter", "housingTemp", "housingHumidity", "inputVoltage", "inputCurrent", "foobarPHValue", "backupBattery", "vrsVolts", "vrsStdDev", "vkVolts", "vkStdDev", "ikAmps", "ibAmps", "SetTemp", "SetPressure", "StepNum"];
opts.VariableTypes = ["datetime", "double", "double",   "double", "double",         "double", "double",    "double", "string", "categorical", "datetime", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double", "double"];

% Specify file level properties
opts.ExtraColumnsRule = "ignore";
opts.EmptyLineRule = "read";

% Specify variable properties
opts = setvaropts(opts, "CRC", "WhitespaceRule", "preserve");
opts = setvaropts(opts, ["CRC", "ID"], "EmptyFieldRule", "auto");
%opts = setvaropts(opts, "dtLV", "InputFormat", "MM/dd/uuuu hh:mm:ss aa");
%opts = setvaropts(opts, "dateTime", "InputFormat", "MM/dd/uuuu hh:mm:ss aa");

%% Process files
path = '\\atlas\ProjectLibrary\ChemSensors\GeneM\GDF pH Sensor\Data\Cal Data\Calcs\DataFiles\ProcessThese\';
fullPath = strcat(path, '*.csv');

dataFiles = dir(strcat(path, '*.csv'));
fileDatenums = dataFiles.date;
[sortedTime, i] = sort([dataFiles.datenum]);
sortedDataFileList = dataFiles(i);

[file, location] = uigetfile(fullPath);

%or i=1:length(dataFiles)
for i=1:1
    % Import the data
    %currentFile = strcat(path, sortedDataFileList(i).name);
    currentFile = strcat(location, file);
    disp("Processing: " + currentFile);
    dataTable{i} = readtable(currentFile, opts);

    % Create overview plot
    createOverviewPlot2(dataTable, currentFile, i);

    titleString = "Vrs vs Time " + currentFile;
    figure('name', titleString, 'NumberTitle', 'off');
    plot(dataTable{i}.dtLV, dataTable{i}.vrsVolts)
    title(titleString)

    % Separate out cycles
    [cycle{i}, numCycles] = getCyclesFromPressure2(dataTable, i);
    %
    % Waterfall plot
    plotPressureWaterfall(cycle{i}, numCycles)
    title(currentFile)

    pDecrV = [];
    pDecrP = [];
    pDecrT = [];

    pIncrV = [];
    pIncrP = [];
    pIncrT = [];

    fig1 = figure;
    title('Vrs lowPHold cycles vs Time')
    hold on
    fig2 = figure;
    title('Vrs lowPHold cycles vs Pressure')
    hold on
    fig3 = figure;
    title('Vrs Pincr cycles vs Time')
    hold on
    fig4 = figure;
    title('Vrs Pincr cycles vs Pressure')
    hold on
    fig5 = figure;
    title('Vrs highPHold cycles vs Time')
    hold on
    fig6 = figure;
    title('Vrs highPHold cycles vs Pressure')
    hold on
    fig7 = figure;
    title('Vrs Pdecr cycles vs Time')
    hold on
    fig8 = figure;
    title('Vrs Pdecr cycles vs Pressure')
    hold on

    polyOrderLowPHold = 1;
    polyOrderPIncr = 3;
    polyOrderHighPHold = 1;
    polyOrderPDecr = 3;

    for j=1:length(cycle{1,i})
        if(cycle{i}(j).cycleName(1) == "lowPHold")
            figure(fig1)
            plot(cycle{i}(j).dt,cycle{i}(j).vrsVolts, '+-');
            figure(fig2)
            plot(cycle{i}(j).pressureDBar, cycle{i}(j).vrsVolts, '+-');
        end

        if(cycle{i}(j).cycleName(1) == "pIncr")
            figure(fig3)
            plot(cycle{i}(j).vrsVolts, '+-');
            figure(fig4)
            plot(cycle{i}(j).pressureDBar, cycle{i}(j).vrsVolts, '+-');
            [cycle{i}(j).fitCoefPIncr, cycle{i}(j).sPIncr] = polyfit(cycle{i}(j).pressureDBar, cycle{i}(j).vrsVolts, polyOrderPIncr);
            [cycle{i}(j).fitValuesPIncr, cycle{i}(j).deltaPIncr] = polyval(cycle{i}(j).fitCoefPIncr, cycle{i}(j).pressureDBar, cycle{i}(j).sPIncr);
            plot(cycle{i}(j).pressureDBar, cycle{i}(j).fitValuesPIncr)
        end

        if(cycle{i}(j).cycleName(1)== "highPHold")
            figure(fig5)
            plot(cycle{i}(j).vrsVolts, '+-');
            figure(fig6)
            plot(cycle{i}(j).pressureDBar, cycle{i}(j).vrsVolts, '+-');
        end

        if(cycle{i}(j).cycleName(1) == "pDecr")
            figure(fig7)
            plot(cycle{i}(j).vrsVolts, '+-');
            figure(fig8)
            plot(cycle{i}(j).pressureDBar, cycle{i}(j).vrsVolts, '+-');
            [cycle{i}(j).fitCoefPIncr, cycle{i}(j).sPIncr] = polyfit(cycle{i}(j).pressureDBar, cycle{i}(j).vrsVolts, polyOrderPIncr);
            [cycle{i}(j).fitValuesPIncr, cycle{i}(j).deltaPIncr] = polyval(cycle{i}(j).fitCoefPIncr, cycle{i}(j).pressureDBar, cycle{i}(j).sPIncr);
            plot(cycle{i}(j).pressureDBar, cycle{i}(j).fitValuesPIncr)
        end
    end
 
end

