clear all
close all

startingDir = '//atlas.shore.mbari.org/ProjectLibrary/CPF/Data/CPF003/TankTests/2021Mar09/';
fileList = ls([startingDir,'*.eng']);
numFiles = size(fileList, 1);

%% Variable names
post2021Feb26 = true;
if(post2021Feb26 == true)
varNames = {'stx', 'date', 'time', 	'state', 	'comment', 	...
    'pressure', 'bellowsPos', ...
    'pumpVolts', 	'pumpMilliAmps', 	'pumpJoules', ...
    'hotelVolts', 	'hotelMilliAmps', 	'hotelJoules', ...
    'CTDTemp', 	'CTDSal', 	...
    'RawPress', 	'LPFPress', 'LPFVel', 	'diffVel', 	'diff2Vel', 'slopeOfLPFPress', 	'CTDSamplePeriod', ...
    'LPS331Press', 	'LPS311Temp', 	'SHT21Humid', 	'SHT21Temp', ...
    'pidSP', 	'pidPV', 	'pidY1',	'pidY2', 'pidI', 	'pid_v', 'pid_u', 'pid_uCPS', 'pid_h',  ...
    'FLBB', 'Topt', 'Tphase', 'Rphase', 'NO3', 'pH_Vrs', 'OCR', 'GPS', 'IridModem', 'MSC'};
varTypes = {'string', 'string', 'string', 'string', 'string', ...
    'double', 'double', ...
    'double', 'double','double',  ...
    'double', 'double','double',  ...
    'string', 'string', ...
    'double', 'double','double', 'double', 'double','double', 'double', ...
    'double', 'double','double', 'double', ...
    'double', 'double','double', 'double', 'double', 'double', 'double','double', 'double', ...
    'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string'};

else
varNames = {'stx', 'date', 'time', 	'state', 	'comment', 	'pressure', 'bellowsPos', ...
    'pumpVolts', 	'pumpMAmps', 	'pumpJoules', ...
    'hotelVolts', 	'hotelMAmps', 	'hotelJoules', ...
    'CTDTemp', 	'CTDSal', 	'RawPress', 	'LPFPress', 'LPFVel', 	'diffVel', 	'diff2Vel', 'slopeOfLPFPress', 	'CTDSamplePeriod', ...
    'LPS331Press', 	'LPS311Temp', 	'SHT21Humid', 	'SHT21Temp', ...
    'PID_SP', 	'PID_PV', 	'PID_Y1',	'PID_Y2', 'PID_I', 	'PID_v', 'PID_u', 'PID_uCPS', 'PID_h',  ...
    'FLBB', 'Topt', 'Tphase', 'Rphase', 'NO3', 'pH_Vrs', 'OCR', 'GPS', 'IridModem', 'MSC'};
varTypes = {'string', 'string', 'string', 'string', 'string', ...
    'double', 'double', ...
    'double', 'double','double',  ...
    'double', 'double','double',  ...
    'string', 'string', ...
    'double', 'double','double', 'double', 'double','double', 'double', ...
    'double', 'double','double', 'double', ...
    'double', 'double','double', 'double', 'double', 'double', 'double','double', 'double', ...
    'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string', 'string'};

    dateIndex = 2;
    timeIndex = 3;
    stateIndex = 4;
    commentIndex = 5;
    pressureIndex = 6;
    bellowsPosIndex = 7;
    pumpVoltsIndex = 8;
    pumpAmpsIndex = 9;
    pumpJoulesIndex = 10;
    hotelVoltsIndex = 11;
    hotelAmpsIndex = 12;
    hotelJoulesIndex = 13;
    ctdIndex = 15;
    rawPressureIndex = 16;
    InternalPressureIndex = 23;
    IPTemperatureIndex = 20;
    HumidityIndex = 21;
    HumidityTemperatureIndex = 22;
    pumpSpeedIndex = 30;
    gpsIndex = 39;
    iridiumIndex = 40;
end

%% Process files
figX = 0.05;
figXIncr = 0.01;
figY = 0.3;
figYIncr = -0.02;

for fileNum = 1:numFiles
    %% Open and read file
    if(fileNum == 5)
        plotEachProfile = true;
    else
        plotEachProfile = false;
    end
    
    fullFileName = [startingDir fileList(fileNum,:)];
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Importing Filename: ' fullFileName 'file number: ' int2str(fileNum) ' of ' int2str(length(fileList))]);
     
    opts = delimitedTextImportOptions('VariableNames', varNames, 'VariableTypes', varTypes, 'Delimiter', '\t');
    tableData = readtable(fullFileName, opts);
  
    if(width(tableData) > length(varNames))
        fprintf('[ERROR] table width is greater than 45 columns\r\n')
        for i=width(tableData):-1:46
            tableData(:,i) = [];
        end
    end

    profile(fileNum).fileName = fullFileName;
    
    %% Process date/time
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing date/time ...']);
   
    dt = tableData.date + tableData.time;
    DT = datetime(dt, 'InputFormat', 'dd-MMM-yyyyHH:mm:ss.SSS');
    DT.Format='yyyyMMMdd HH:mm:ss';

    %% Process pressure
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing pressure ...']);
    notNaN = ~isnan(tableData.pressure);
    profile(fileNum).pressure = tableData.pressure(notNaN);
    profile(fileNum).pressureDT = DT(notNaN);

    %% Process bellows position
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing bellows position ...']);
    notNaN = ~isnan(tableData.bellowsPos);
    profile(fileNum).bellowsPosition = tableData.bellowsPos(notNaN);
    profile(fileNum).bellowsPositionDT = DT(notNaN);
 
    %% Find glide on
    glideOnFind = strfind(tableData.comment, 'glide on');
    glideOnMsgIndexes = find(isempty(glideOnFind) == 0);
   
    
    %% Find glide off
 
    
    %% Plot pressure and bellows position
    if plotEachProfile
        fig = figure('Name',fullFileName,'NumberTitle','off');
        fig.Units = 'normalized';
        fig.Position = [figX figY 0.6 0.6];
        figX = figX + figXIncr;
        figY = figY + figYIncr;
        
        hAx = subplot(3,1,1);
        yyaxis left
        plot(profile(fileNum).bellowsPositionDT, profile(fileNum).bellowsPosition);
        ylabel('Bellows Position (%IB Full)');
        yyaxis right
        plot(profile(fileNum).pressureDT, profile(fileNum).pressure);
        ylabel('Pressure (dBar)');
        hold on;
        
        plotstateTransitions(tableData, DT);
        
%         if length(glideOnMsgIndexes) > 0
%             plot(glideOntime, glideOnDepth, 'gO')
%             text(glideOntime, glideOnDepth, 'glide on');
%         end
%         glideOnMsgIndexes = [];
%         if length(glideOffMsgIndexes) > 0
%             plot(glideOfftime, glideOffDepth, 'rX')
%             text(glideOfftime, glideOffDepth, 'glide off');
%         end
%         glideOffMsgIndexes = [];
        hold off;
    end
    
    %% Process pump speed
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing pump speed ...']);
    
    if(~ismissing(tableData.pid_uCPS(1)))
        notNaN = ~isnan(tableData.pid_uCPS);
        profile(fileNum).pumpSpeed = tableData.pid_uCPS(notNaN);
        profile(fileNum).pumpSpeedDT = DT(notNaN);
        
        if plotEachProfile
            hAx = subplot(3,1,2);
            yyaxis left
            plot(profile(fileNum).pumpSpeedDT, profile(fileNum).pumpSpeed);
            ylabel('Pump Speed (cps)');
            yyaxis right
            plot(profile(fileNum).pressureDT, profile(fileNum).pressure);
            ylabel('Pressure (dBar)');
            hold on;
            
            plotstateTransitions(tableData, DT);
        end
    end
    
    
    %% Process pressure and humidity
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing internal pressure and humidity ...']);
    notNaN = ~isnan(tableData.LPS331Press);
    profile(fileNum).intPressure = tableData.LPS331Press(notNaN);
    profile(fileNum).intPressureDT = DT(notNaN);
 
    notNaN = ~isnan(tableData.SHT21Humid);
    profile(fileNum).humidity = tableData.SHT21Humid(notNaN);
    profile(fileNum).humidityDT = DT(notNaN);
    
    if plotEachProfile
        hAx = subplot(3,1,3);
        yyaxis left
        plot(profile(fileNum).intPressureDT, profile(fileNum).intPressure);
        ylabel('Internal Pressure (mBar)');
        yyaxis right
        plot(profile(fileNum).humidityDT, profile(fileNum).humidity);
        ylabel('Humidity (%RH)');
        hold on;
        
        plotstateTransitions(tableData, DT);
    end
    
    %% Process pump power
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Calculating Pump Power ...']);

    notNaN = ~isnan(tableData.pumpVolts);
    profile(fileNum).pumpVolts = tableData.pumpVolts(notNaN);
    profile(fileNum).pumpVoltsDT = DT(notNaN);
    
    notNaN = ~isnan(tableData.pumpMilliAmps);
    profile(fileNum).pumpAmps = tableData.pumpMilliAmps(notNaN) / 1000.0;
    profile(fileNum).pumpAmpsDT = DT(notNaN);

    vecLength = min(length(profile(fileNum).pumpAmpsDT), length(profile(fileNum).pumpVoltsDT));
    profile(fileNum).pumpPower = profile(fileNum).pumpVolts(1:vecLength) .* profile(fileNum).pumpAmps(1:vecLength);
    profile(fileNum).pumpPowerDT = profile(fileNum).pumpVoltsDT(1:vecLength);
 
        
    if plotEachProfile
        fig = figure('Name',fullFileName,'NumberTitle','off');
        fig.Units = 'normalized';
        fig.Position = [figX figY 0.6 0.6];
        figX = figX + figXIncr;
        figY = figY + figYIncr;

        hAx = subplot(4,1,1);  % Auto-fitted to the figure.
        yyaxis left
        plot(profile(fileNum).pumpVoltsDT, profile(fileNum).pumpVolts);
        ylabel('Pump Volts');
        yyaxis right
        plot(profile(fileNum).pumpAmpsDT, profile(fileNum).pumpAmps);
        ylabel('Pump Amps');
        hold on;
        
        plotstateTransitions(tableData, DT)
    end
    
    fprintf('%s\t', [datestr(now, 'HH:MM:SS ') 'Calculating Energy ...']);
    profile(fileNum).pumpEnergy = profile(fileNum).pumpPower(1:end-1) .* seconds( profile(fileNum).pumpPowerDT(2:end) - profile(fileNum).pumpPowerDT(1:end-1));
    profile(fileNum).pumpEnergyDT = profile(fileNum).pumpAmpsDT(1:end-1);
    
    profile(fileNum).pumpEnergySum = cumsum(profile(fileNum).pumpEnergy);
    profile(fileNum).pumpEnergySumDT = profile(fileNum).pumpEnergyDT;
    
    profile(fileNum).totalPumpEnergy = sum(profile(fileNum).pumpEnergy);
    fprintf('Total Energy this profile = %.0f Joules\n\n', profile(fileNum).totalPumpEnergy);
    
    if plotEachProfile
        hAx = subplot(4,1,2);  % Auto-fitted to the figure.
        yyaxis left
        plot(profile(fileNum).pumpPowerDT, profile(fileNum).pumpPower);
        ylabel('Pump Power (Watts)');
        yyaxis right
        plot(profile(fileNum).pressureDT, profile(fileNum).pressure);
        ylabel('Pressure (dBar)');
        hold on;
        
        xlimits = xlim;
        text(xlimits(1), 0.95*max(profile(fileNum).pumpPower), sprintf('Energy = %.0f Joules', profile(fileNum).totalPumpEnergy));
        
        plotstateTransitions(tableData, DT)
    end
    
     %% Process hotel power
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Calculating Hotel Power ...']);

    notNaN = ~isnan(tableData.hotelVolts);
    profile(fileNum).hotelVolts = tableData.hotelVolts(notNaN);
    profile(fileNum).hotelVoltsDT = DT(notNaN);
    
    notNaN = ~isnan(tableData.hotelMilliAmps);
    profile(fileNum).hotelAmps = tableData.hotelMilliAmps(notNaN) / 1000.0;
    profile(fileNum).hotelAmpsDT = DT(notNaN);

    vecLength = min(length(profile(fileNum).hotelAmpsDT), length(profile(fileNum).hotelVoltsDT));
    profile(fileNum).hotelPower = profile(fileNum).hotelVolts(1:vecLength) .* profile(fileNum).hotelAmps(1:vecLength);
    profile(fileNum).hotelPowerDT = profile(fileNum).hotelVoltsDT(1:vecLength);
        
    if plotEachProfile
        hAx = subplot(4,1,3);  % Auto-fitted to the figure.
        yyaxis left
        plot(profile(fileNum).hotelVoltsDT, profile(fileNum).hotelVolts);
        ylabel('Hotel Volts');
        yyaxis right
        plot(profile(fileNum).hotelAmpsDT, profile(fileNum).hotelAmps);
        ylabel('Hotel milliAmps');
        hold on;
        
        plotstateTransitions(tableData, DT)
    end
    
    fprintf('%s\t', [datestr(now, 'HH:MM:SS ') 'Calculating Energy ...']);
    profile(fileNum).hotelEnergy = profile(fileNum).hotelPower(1:end-1) .* seconds( profile(fileNum).hotelPowerDT(2:end) - profile(fileNum).hotelPowerDT(1:end-1));
    profile(fileNum).hotelEnergyDT = profile(fileNum).hotelAmpsDT(1:end-1);
    
    profile(fileNum).hotelEnergySum = cumsum(profile(fileNum).hotelEnergy);
    profile(fileNum).hotelEnergySumDT = profile(fileNum).hotelEnergyDT;
    %profile(fileNum).hotelEnergySum(length(profile(fileNum).hotelEnergySum) + 1) = profile(fileNum).hotelEnergySum(end);
    
    profile(fileNum).totalHotelEnergy = sum(profile(fileNum).hotelEnergy);
    fprintf('Total Energy this profile = %.0f Joules\n\n', profile(fileNum).totalHotelEnergy);
    
    if plotEachProfile
        hAx = subplot(4,1,4);  % Auto-fitted to the figure.
        yyaxis left
        plot(profile(fileNum).hotelPowerDT, profile(fileNum).hotelPower);
        ylabel('Hotel Power (Watts)');
        yyaxis right
        plot(profile(fileNum).pressureDT, profile(fileNum).pressure);
        ylabel('Pressure (dBar)');
        hold on;
        
        xlimits = xlim;
        text(xlimits(1), 0.95*max(profile(fileNum).hotelPower), sprintf('Energy = %.0f Joules', profile(fileNum).totalHotelEnergy));
        
        plotstateTransitions(tableData, DT)
    end
    
%     if(plotEachProfile)
%         figure
%         plot(profile(fileNum).pumpEnergySumDT, profile(fileNum).pumpEnergySum, ...
%             profile(fileNum).hotelEnergySumDT, profile(fileNum).hotelEnergySum, ...
%             profile(fileNum).hotelEnergySumDT, (profile(fileNum).pumpEnergySum + profile(fileNum).hotelEnergySum));
%         plotstateTransitions(tableData, DT);
%     end
    
    %% Process UBX messages
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Process GPS Messages ...']);

    ubxFind = strfind(tableData.GPS, 'UBX');
    ubxMsgIndexes = find(~cellfun('isempty', ubxFind));
    profile(fileNum).ubxMsgs = tableData.GPS(ubxMsgIndexes);
    profile(fileNum).ubxMsgsDT = DT(ubxMsgIndexes);
     
    %% Process SBDIX messages
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Process Iridium Messages ...']);

    sbdixFind = strfind(tableData.IridModem, '+SBDIX:');
    sbdixMsgIndexes = find(~cellfun('isempty', sbdixFind));
    profile(fileNum).sbdixMsgs = tableData.IridModem(sbdixMsgIndexes);
    profile(fileNum).sbdixMsgsDT = DT(sbdixMsgIndexes);
    
    %% Find error messages
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Find Error Messages ...']);

    errorFind = strfind(tableData.comment, '[Error]');
    errorMsgIndexes = find(~cellfun('isempty', errorFind));
    profile(fileNum).errorMsg = tableData.IridModem(errorMsgIndexes);
    profile(fileNum).errorMsgDT = DT(errorMsgIndexes);
    
    bpLimitErrorFind = strfind(tableData.comment, 'exceeds limits');
    bpLimitErrorMsgIndexes = find(~cellfun('isempty', bpLimitErrorFind));
    profile(fileNum).bpError = tableData.IridModem(bpLimitErrorMsgIndexes);
    profile(fileNum).bpErrorDT = DT(bpLimitErrorMsgIndexes);
    
    fprintf(1, 'Summary of errors in %d files processed: \r\n', i );
    
    for i = 1:length(errorMsgIndexes)
        fprintf(1, 'Error %d at time %s : %s \r\n', i, datestr(profile(fileNum).errorMsgDT), profile(fileNum).errorMsg(i));
    end
    
    fprintf(1, '\r\nTotal number of Bellow Position Limit Errors = %d \r\n', length(bpLimitErrorMsgIndexes));
    
    
    
    %% Other stuff
    %         figure(numSatsFig);
    %         clf;
    %         try
    %             plot(numSatstime, numSats, '+-');
    %             title('Number of GPS Satellites vs time')
    %         catch me
    %             title('Number of GPS Satellites not processed');
    %         end
    %
    %         figure(numIridiumTrysFig);
    %         clf;
    %         try
    %             plot(numSBDIXtime, numSBDIX, '+-');
    %             title('Number of SBDIX Attempts vs time')
    %         catch me
    %             title('Number of SBDIX Attempts not processed');
    %         end
    
    %        fprintf(1, 'Enter 2 points on descend plot and 2 points on ascend plots to calculate platform velocity');
    %        [x y] = ginput(4)
    %
    %        dt = 24 * 3600 * datenum(pressureDT(round(x(1)):round(x(2))));
    %        dt = dt - dt(1);
    %        [p, s] = polyfit(dt, pressure(round(x(1)):round(x(2))), 1);
    %        fprintf(1, 'platform velocity (slope) between first pair of points = %f    ', p);
    %        dt = 24 * 3600 * datenum(pressureDT(round(x(3)):round(x(4))));
    %        dt = dt - dt(1);
    %        [p, s] = polyfit(dt, pressure(round(x(3)):round(x(4))), 1);
    %        fprintf(1,'\r\n');
    %        fprintf(1, 'platform velocity (slope) between second pair of points = %f  ', p);
    
    
end

%% Waterfall plots
fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Plotting waterfalls ...']);

figX = 0.05;
figXIncr = 0.1;
figY = 0.3;
figYIncr = -0.05;

%Depth
fig = figure('Name','Depth','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Pressure')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).pressureDT)
        x(i) = profile(profileNum).pressureDT(1);
    end
    y = profile(profileNum).pressureDT - profile(profileNum).pressureDT(1);
    plot3(x, y, profile(profileNum).pressure)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Depth (dBar)')
grid
view(3)

% Bellows Position
fig = figure('Name','Bellows Pos','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Bellows Position')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).bellowsPositionDT)
        x(i) = profile(profileNum).bellowsPositionDT(1);
    end
    y = profile(profileNum).bellowsPositionDT - profile(profileNum).bellowsPositionDT(1);
    plot3(x, y, profile(profileNum).bellowsPosition)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Bellows Position (IB % Full')
grid
view(3)

%Pump Volts
fig = figure('Name','Pump Volts','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Pump Bus Volts')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).pumpVoltsDT)
        x(i) = profile(profileNum).pumpVoltsDT(1);
    end
    y = profile(profileNum).pumpVoltsDT - profile(profileNum).pumpVoltsDT(1);
    plot3(x, y, profile(profileNum).pumpVolts)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Pump Bus Volts')
grid
view(3)

%Pump power
fig = figure('Name','Pump Power','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Pump Bus Power')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).pumpPowerDT)
        x(i) = profile(profileNum).pumpPowerDT(1);
    end
    y = profile(profileNum).pumpPowerDT - profile(profileNum).pumpPowerDT(1);
    plot3(x, y, profile(profileNum).pumpPower)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Pump Bus Power (Watts)')
grid
view(3)

%Internal Pressure
fig = figure('Name','Internal Pressure','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Internal Pressure (mBar)')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).intPressureDT)
        x(i) = profile(profileNum).intPressureDT(1);
    end
    y = profile(profileNum).intPressureDT - profile(profileNum).intPressureDT(1);
    plot3(x, y, profile(profileNum).intPressure)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Internal Pressure (mBar)')
grid
view(3)

%Humidity
fig = figure('Name','Humidity','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Internal Humidity (%RH)')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).humidityDT)
        x(i) = profile(profileNum).humidityDT(1);
    end
    y = profile(profileNum).humidityDT - profile(profileNum).humidityDT(1);
    plot3(x, y, profile(profileNum).humidity)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Humidity (%RH)')
grid
view(3)

%Pump Energy sum
fig = figure('Name','Pump Cumul. Energy','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Pump Cumulative Energy (Joules)')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).pumpEnergySumDT)
        x(i) = profile(profileNum).pumpEnergySumDT(1);
    end
    y = profile(profileNum).pumpEnergySumDT - profile(profileNum).pumpEnergySumDT(1);
    plot3(x, y, profile(profileNum).pumpEnergySum)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Pump Cumulative Energy (Joules')
grid
view(3)

%Hotel Energy sum
fig = figure('Name','Hotel Cumul. Energy','NumberTitle','off');
fig.Units = 'normalized';
fig.Position = [figX figY 0.6 0.6];
figX = figX + figXIncr;
figY = figY + figYIncr;
title('Hotel Cumulative Energy (Joules)')
hold on;

for profileNum = 1:length(profile)
    for i=1:length(profile(profileNum).hotelEnergySumDT)
        x(i) = profile(profileNum).hotelEnergySumDT(1);
    end
    y = profile(profileNum).hotelEnergySumDT - profile(profileNum).hotelEnergySumDT(1);
    plot3(x, y, profile(profileNum).hotelEnergySum)
    clear x;
end
xlabel('Profile Start time');
ylabel('Time from Profile Start')
zlabel('Hotel Cumulative Energy (Joules')
grid
view(3)


%% Function: plotstateTransitions

function plotstateTransitions(tableData, DT)
%figure(pressureFig);
ylimits = ylim;

textY1 = ylimits(1) + 0.1 * (ylimits(2) - ylimits(1));
textY2 = ylimits(1) + 0.9 * (ylimits(2) - ylimits(1));

indexes = find(strcmp(tableData.state, 'Surface Ops') == 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Surface Ops')
end

indexes = find(strcmp(tableData.state, 'AB Dec Buoycy Fast') == 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY2, 'Dec Buoycy')
end

indexes = find(strcmp(tableData.state, 'Descend')== 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Descend')
end

indexes = find(strcmp(tableData.state, 'Anchor')== 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY2, 'Anchor')
end

indexes = find(strcmp(tableData.state, 'Park')== 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Park')
end

indexes = find(strcmp(tableData.state, 'Start CP Mode')== 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY2, 'Start CP')
end

indexes = find(strcmp(tableData.state, 'Deanchor')== 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Deanchor')
end

indexes = find(strcmp(tableData.state, 'Ascend')== 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY2, 'Ascend')
end

indexes = find(strcmp(tableData.state, 'Init Profile') == 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Init Profile')
end
    
indexes = find(strcmp(tableData.state, 'Surface Ops Set Bellows') == 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY2, 'SO Set Bel')
end

indexes = find(strcmp(tableData.state, 'Dump CP Data') == 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Dump CP')
end

indexes = find(strcmp(tableData.state, 'RecoveryMode') == 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Recovery')
end

indexes = find(strcmp(tableData.state, 'Init Mission') == 1);
if(~isempty(indexes))
    index = indexes(1);
    plot( [DT(index) DT(index)], [ylimits(1) ylimits(2)], 'g-.');
    text( DT(index), textY1, 'Init Mission')
end

end

function createFigure(fileName, figNum)
figX = 0.05;
figXIncr = 0.05;
figY = 0.6;
figYIncr = -0.05;

pressureFig = figure;
pressureFig.Units = 'normalized';
pressureFig.Position = [figX figY 0.6 0.4];
title('Pressure & Bellows Position vs time');
hold on;
grid on;

pumpVoltsFig = figure;
pumpVoltsFig.Units = 'normalized';
figX = figX + figXIncr;
figY = figY + figYIncr;
pumpVoltsFig.Position = [figX figY 0.6 0.4];
title('Pump Voltage & Current vs time');
hold on;
grid on;

pumpSpeedFig = figure;
pumpSpeedFig.Units = 'normalized';
figX = figX + figXIncr;
figY = figY + figYIncr;
pumpSpeedFig.Position = [figX figY 0.6 0.4];
title('Pressure & Pump Speed vs time');
hold on;
grid on;

pressureOnlyFig = figure;
pressureOnlyFig.Units = 'normalized';
figX = figX + figXIncr;
figY = figY + figYIncr;
pressureOnlyFig.Position = [figX figY 0.6 0.4];
title('Pressure & Pump Speed vs time');
hold on;
grid on;
end









