clear all
close all

plotWaterfalls = false;
plotProfiles = false;

%startingDir = '\\atlas\ProjectLibrary\CPF\Data\AnalysisScripts\2022-4-25T16-25-48\';
startingDir = '\\atlas\ProjectLibrary\CPF\CPF003\Data\TankTests\2023-8-18T23-52-36\';

totalHotelEnergyTransit = 0;
totalPumpEnergyTransit = 0;

fileList = ls([startingDir,'*.eng']);
numFiles = size(fileList,1);

%This is the theoretical energy available based on IE data sheet
energyAvailable = 1600000; % joules = 6 * 28.8 * volts * 2.6 * amp*hrs
%This is the calculated energy available based on 97 profile CPF003 tank test 2021-9-3T18-48-26
%energyAvailable = 1389736;

global tableData profile fileNum
global glideOnMsgIndexes glideOffMsgIndexes



%for fileNum = 1:numFiles
for fileNum = 1:3
    %% Open and read file
    if ((fileNum ~= 21) && (fileNum ~=27) && (fileNum ~= 30))
        fprintf('\nProcessing file number: %d\n', fileNum);
        fullFileName = [startingDir fileList(fileNum,:)];
        fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Importing Filename: ' fullFileName 'file number: ' int2str(fileNum) ' of ' int2str(length(fileList))]);

        tableData = readtable(fullFileName, 'FileType', 'text', 'Delimiter', '\t');

        profile(fileNum).fileName = fileList(fileNum,:);
        profile(fileNum).fullFileName = fullFileName;

        processDateTime();
        processPressure();
        processPVs();
        processBellowPosition();
        findGlide();
        processHotelEnergy();
        processPumpEnergy();

        endIndex = min(length(profile(fileNum).hotelJoules), length(profile(fileNum).pumpJoules));
        profile(fileNum).totalJoules = profile(fileNum).hotelJoules(1:endIndex) + profile(fileNum).pumpJoules(1:endIndex);
        profile(fileNum).totalJoulesDT = profile(fileNum).hotelJoulesDT(1:endIndex);
        
        joulesDiff = diff(profile(fileNum).totalJoules);
        indexes = find(joulesDiff < 0);
        joulesDiff(indexes) = 0;
        profileJoulesSum = cumsum(joulesDiff);
        profileJoulesSumDT = profile(fileNum).totalJoulesDT(2:end);
        profile(fileNum).joulesThisProfile = profileJoulesSum(end);
        profile(fileNum).joulesThisProfileDT = profileJoulesSumDT(end);
  
        if(fileNum == 1)
            missionJoules = profileJoulesSum;
            missionJoulesDT = profileJoulesSumDT;
        else
            missionJoules = [missionJoules; missionJoules(end) + profileJoulesSum];
            missionJoulesDT = [missionJoulesDT; profileJoulesSumDT];
        end        

        if fileNum == 3
            figure
            if(fileNum == 1)
                startDT = 3;
            else
                startDT = 2;
            end

            hold on
            p(1) = plot(profile(fileNum).totalJoulesDT(startDT:end), profile(fileNum).totalJoules(startDT:end), 'DisplayName', 'Total Energy');
            p(2) = plot(profile(fileNum).pumpJoulesDT(startDT:end), profile(fileNum).pumpJoules(startDT:end), 'DisplayName', 'Pump Energy');
            p(3) = plot(profile(fileNum).hotelJoulesDT(startDT:end), profile(fileNum).hotelJoules(startDT:end), 'DisplayName', 'Hotel Energy');

            plotStateTransitions(tableData, profile(fileNum).DT(startDT:end));
            xlabel('Time');
            ylabel('Joules');
            legend(p(1:3))
            hold off
        end

        fprintf('\n');
    end
end
  
function processPVs
    global tableData profile fileNum

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

    notNaN = ~isnan(tableData.LPFVel);
    profile(fileNum).LPFVel = tableData.LPFVel(notNaN);
    profile(fileNum).LPFVelDT = profile(fileNum).DT(notNaN);

    notNaN = ~isnan(tableData.DiffVel);
    profile(fileNum).diffVel = tableData.DiffVel(notNaN);
    profile(fileNum).diffVelDT = profile(fileNum).DT(notNaN);

    notNaN = ~isnan(tableData.Diff2Vel);
    profile(fileNum).diff2Vel = tableData.Diff2Vel(notNaN);
    profile(fileNum).diff2VelDT = profile(fileNum).DT(notNaN);

    notNaN = ~isnan(tableData.SlopeLPFPress);
    profile(fileNum).slopeOfLPFPress = tableData.SlopeLPFPress(notNaN);
    profile(fileNum).slopeOfLPFPressDT = profile(fileNum).DT(notNaN);
end

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

    notNaN = ~isnan(tableData.LPFPress);
    profile(fileNum).LPFPressure = tableData.LPFPress(notNaN);
    profile(fileNum).LPFPressureDT = profile(fileNum).DT(notNaN);
end

function processDateTime()
    global tableData profile fileNum

    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing date/time ...']);

    notNaT = ~isnat(tableData.Date);
    notNaN = ~isnan(tableData.Time);
    validIndexes = min(notNaT, notNaN);
    dt = tableData.Date(validIndexes) + tableData.Time(validIndexes);

    profile(fileNum).DT = datetime(dt, 'InputFormat', 'dd-MMM-yyyyHH:mm:ss.SSS');
    profile(fileNum).State = tableData.State;

%     notNaN = ~isnan(tableData.HotelMilliSeconds);
%     profile(fileNum).hotelSeconds = tableData.HotelMilliSeconds(notNaN) / 1.0e3;
%     profile(fileNum).hotelSecondsDT = profile(fileNum).DT(notNaN);
%     if(profile(fileNum).hotelVoltsDT(1) < datetime(2000, 1, 1))
%         profile(fileNum).hotelVoltsDT(1) = profile(fileNum).hotelVoltsDT(2) - duration(0, 0, 1);
%end

%     notNaN = ~isnan(tableData.PumpMilliSeconds);
%     profile(fileNum).pumpSeconds = tableData.PumpMilliSeconds(notNaN) / 1.0e3;
%     profile(fileNum).pumpSecondsDT = profile(fileNum).DT(notNaN);
%     if(profile(fileNum).hotelVoltsDT(1) < datetime(2000, 1, 1))
%         profile(fileNum).hotelVoltsDT(1) = profile(fileNum).hotelVoltsDT(2) - duration(0, 0, 1);
%    end
    
    initProfileIndexes = find(strcmp(char(tableData.State), 'Init Profile'));
    if ~isempty(initProfileIndexes)
        profile(fileNum).initProfileStartTime = profile(fileNum).DT(initProfileIndexes(1));
    else
        profile(fileNum).initProfileStartTime = profile(fileNum).DT(1);
    end
end

function processPID
    global tableData profile fileNum
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing PID ...']);
    notNaN = ~isnan(tableData.pid_uCPS);
    profile(fileNum).pid_uCPS = tableData.pid_uCPS(notNaN);
    profile(fileNum).pid_uCPSDT = profile(fileNum).DT(notNaN);
    
    if(~ismissing(tableData.pid_uCPS(1)))
        notNaN = ~isnan(tableData.pid_uCPS);
        profile(fileNum).pidUCps = tableData.pid_uCPS(notNaN);
        profile(fileNum).pidUCpsDT = profile(fileNum).DT(notNaN);
    end
end

function processBellowPosition()
    global tableData profile fileNum
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing bellows position ...']);
    notNaN = ~isnan(tableData.BelPos);
    profile(fileNum).bellowsPosition = tableData.BelPos(notNaN);
    profile(fileNum).bellowsPositionDT = profile(fileNum).DT(notNaN);
end
 
function findGlide()
    global tableData glideOnMsgIndexes glideOffMsgIndexes
    glideOnFind = strfind(tableData.Comment, 'glide on');
    glideOnMsgIndexes = find(isempty(glideOnFind) == 0);
  
    glideOffFind = strfind(tableData.Comment, 'glide off');
    glideOffMsgIndexes = find(isempty(glideOffFind) == 0);
end

function processHotelEnergy()
    global tableData profile fileNum
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Calculating Hotel Power ...']);

    notNaN = ~isnan(tableData.HotelVolts);
    profile(fileNum).hotelVolts = tableData.HotelVolts(notNaN) / 1.0e3;
    profile(fileNum).hotelVoltsDT = profile(fileNum).DT(notNaN);
    if(profile(fileNum).hotelVoltsDT(1) < datetime(2000, 1, 1))
        profile(fileNum).hotelVoltsDT(1) = profile(fileNum).hotelVoltsDT(2) - duration(0, 0, 1);
    end
    
    notNaN = ~isnan(tableData.HotelMilliamps);
    profile(fileNum).hotelAmps = tableData.HotelMilliamps(notNaN) / 1.0e3;
    profile(fileNum).hotelAmpsDT = profile(fileNum).DT(notNaN);
    if(profile(fileNum).hotelAmpsDT(1) < datetime(2000, 1, 1))
        profile(fileNum).hotelAmpsDT(1) = profile(fileNum).hotelAmpsDT(2) - duration(0, 0, 1);
    end
    
    notNaN = ~isnan(tableData.HotelMilliWatts);
    profile(fileNum).hotelWatts = tableData.HotelMilliWatts(notNaN) / 1.0e6;
    profile(fileNum).hotelWattsDT = profile(fileNum).DT(notNaN);
    if(profile(1).hotelWattsDT(1) < datetime(2000, 1, 1))
        profile(1).hotelWattsDT(1) = profile(1).hotelWattsDT(2) - duration(0, 0, 1);
    end
    profile(fileNum).hotelEnergy = tableData.HotelMilliWatts(notNaN) * 65536 * 16.39543e-3 * 1e-3;
    
    notNaN = ~isnan(tableData.HotelUCoulombs);
    profile(fileNum).hotelCoulombs = tableData.HotelUCoulombs(notNaN) / 1.0e6;
    profile(fileNum).hotelCoulombsDT = profile(fileNum).DT(notNaN);
    if(profile(fileNum).hotelCoulombsDT(1) < datetime(2000, 1, 1))
        profile(fileNum).hotelCoulombsDT(1) = profile(fileNum).hotelCoulombsDT(2) - duration(0, 0, 1);
    end
    
    notNaN = ~isnan(tableData.HotelJoules);
    profile(fileNum).hotelJoules = tableData.HotelJoules(notNaN) / 1.0e9;
    profile(fileNum).hotelJoulesDT = profile(fileNum).DT(notNaN);
    if(profile(fileNum).hotelJoulesDT(1) < datetime(2000, 1, 1))
        profile(fileNum).hotelJoulesDT(1) = profile(fileNum).hotelJoulesDT(2) - duration(0, 0, 1);
    end
    
    profile(fileNum).totalHotelJoules = profile(fileNum).hotelJoules(end);
    
%     if(fileNum == 1)
%         profile(fileNum).missionHotelEnergyTotal = profile(fileNum).missionHotelEnergyTotal + profile(fileNum).totalHotelEnergy;
%     else
%         profile(fileNum).missionHotelEnergyTotal = profile(fileNum-1).missionHotelEnergyTotal + profile(fileNum).totalHotelEnergy;
%     end
%     
%     if(fileNum == 1)
%     profile(fileNum).missionEnergyTotal = profile(fileNum).missionEnergyTotal + profile(fileNum).totalPumpEnergy + profile(fileNum).totalHotelEnergy;
%     else
%         profile(fileNum).missionEnergyTotal = profile(fileNum-1).missionEnergyTotal + profile(fileNum).totalPumpEnergy + profile(fileNum).totalHotelEnergy;
%     end
%         
%     fprintf('\nTotal sum of hotel energy this profile = %.0f Joules\n', profile(fileNum).totalHotelEnergy);
%     fprintf('Final value of hotel energy sum this profile = %.0f Joules\n\n', profile(fileNum).hotelEnergyCalcSum(end));
end

function processPumpEnergy()
global tableData profile fileNum
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Calculating Pump Power ...']);

    notNaN = ~isnan(tableData.PumpVolts);
    profile(fileNum).pumpVolts = tableData.PumpVolts(notNaN) / 1.0e3;
    profile(fileNum).pumpVoltsDT = profile(fileNum).DT(notNaN);
    if(profile(1).pumpVoltsDT(1) < datetime(2000, 1, 1))
        profile(1).pumpVoltsDT(1) = profile(1).pumpVoltsDT(2) - duration(0, 0, 1);
    end
    
    notNaN = ~isnan(tableData.PumpMilliamps);
    profile(fileNum).pumpAmps = tableData.PumpMilliamps(notNaN) / 1.0e3;
    profile(fileNum).pumpAmpsDT = profile(fileNum).DT(notNaN);
    if(profile(1).pumpAmpsDT(1) < datetime(2000, 1, 1))
        profile(1).pumpAmpsDT(1) = profile(1).MilliAmpsDT(2) - duration(0, 0, 1);
    end

    notNaN = ~isnan(tableData.PumpMilliWatts);
    profile(fileNum).pumpWatts = tableData.PumpMilliWatts(notNaN) / 1.0e6;
    profile(fileNum).pumpWattsDT = profile(fileNum).DT(notNaN);
    if(profile(1).pumpWattsDT(1) < datetime(2000, 1, 1))
        profile(1).pumpWattsDT(1) = profile(1).MilliWattsDT(2) - duration(0, 0, 1);
    end

    notNaN = ~isnan(tableData.PumpUCoulombs);
    profile(fileNum).pumpCoulombs = tableData.PumpUCoulombs(notNaN) / 1.0e6;
    profile(fileNum).pumpCoulombsDT = profile(fileNum).DT(notNaN);
    if(profile(fileNum).pumpCoulombsDT(1) < datetime(2000, 1, 1))
        profile(fileNum).pumpCoulombsDT(1) = profile(fileNum).pumpUCoulombsDT(2) - duration(0, 0, 1);
    end

   
    notNaN = ~isnan(tableData.PumpJoules);
    profile(fileNum).pumpJoules = tableData.PumpJoules(notNaN) / 1.0e9;
    profile(fileNum).pumpJoulesDT = profile(fileNum).DT(notNaN);
    if(profile(fileNum).pumpJoulesDT(1) < datetime(2000, 1, 1))
        profile(fileNum).pumpJoulesDT(1) = profile(fileNum).pumpJoulesDT(2) - duration(0, 0, 1);
    end
    profile(fileNum).totalPumpJoules = profile(fileNum).pumpJoules(end);
    
  
    
    
%
%     if(fileNum == 1)
%         profile(fileNum).missionPumpEnergyTotal = profile(fileNum).missionPumpEnergyTotal + profile(fileNum).totalPumpEnergy;
%     else
%         profile(fileNum).missionPumpEnergyTotal = profile(fileNum-1).missionPumpEnergyTotal + profile(fileNum).totalPumpEnergy;
%     end
%     
%     fprintf('\nTotal sum of pump energy this profile = %.0f Joules\n', profile(fileNum).totalPumpEnergy);
%     fprintf('Final value of hotel energy sum this profile = %.0f Joules\n\n', profile(fileNum).pumpEnergyCalcSum(end));
%         
%  
%     totalEnergy = profile(fileNum).totalHotelEnergy - totalHotelEnergyTransit + profile(fileNum).totalPumpEnergy - totalPumpEnergyTransit;
%     fprintf('Total energy this profile = %.0f Joules', totalEnergy);
%     percentAvailable = 100 * totalEnergy / energyAvailable;
%     fprintf(' = %3.1f precent of total Joules available\n\n', percentAvailable);
%       
%   
end

function calculateHotelEnergy()
global tableData profile fileNum
    profile(fileNum).hotelPowerCalc = profile(fileNum).hotelVolts .* profile(fileNum).hotelAmps;
    profile(fileNum).hotelPowerCalcDT = profile(fileNum).hotelVoltsDT;
      
    dt = profile(fileNum).hotelSeconds(2:end) - profile(fileNum).hotelSeconds(1:end-1);
    startIndex = find(dt < 0);
    dt =  profile(fileNum).hotelSeconds(startIndex + 2:end) - profile(fileNum).hotelSeconds(startIndex + 1:end-1);
    power = profile(fileNum).hotelPowerCalc(startIndex + 1:end - 1);
    profile(fileNum).hotelJoulesCalc = dt .* power;
    profile(fileNum).hotelJoulesCalcDT = profile(fileNum).hotelPowerCalcDT(1:end-1);
    
    profile(fileNum).hotelJoulesCalcSum = cumsum(profile(fileNum).hotelJoulesCalc);
    profile(fileNum).hotelJoulesCalcSumDT = profile(fileNum).hotelJoulesCalcDT;
    
    profile(fileNum).totalHotelJoulesCalc = sum(profile(fileNum).hotelJoulesCalc);
end

function calculatePumpEnergy()
global tableData profile fileNum
    profile(fileNum).pumpPowerCalc = profile(fileNum).pumpVolts .* profile(fileNum).pumpAmps;
    profile(fileNum).pumpPowerCalcDT = profile(fileNum).pumpVoltsDT;

    dt = profile(fileNum).pumpSeconds(2:end) - profile(fileNum).pumpSeconds(1:end-1);
    startIndex = find(dt < 0);
    dt =  profile(fileNum).pumpSeconds(startIndex + 2:end) - profile(fileNum).pumpSeconds(startIndex + 1:end-1);
    power = profile(fileNum).pumpPowerCalc(startIndex + 1:end - 1);
    if(length(dt) == length(power))
        profile(fileNum).pumpEnergyCalc = dt .* power;
        profile(fileNum).pumpEnergyCalcDT = profile(fileNum).pumpPowerCalcDT(1:end-1);

        profile(fileNum).pumpEnergyCalcSum = cumsum(profile(fileNum).pumpEnergyCalc);
        profile(fileNum).pumpEnergyCalcSumDT = profile(fileNum).pumpEnergyCalcDT;

        profile(fileNum).totalpumpEnergyCalc = sum(profile(fileNum).pumpEnergyCalc);
    end
end


%    
%     
% 
%     %% Process PID uCPS
%   
%      
%      %% Process Twitter JV commands
%     fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing Twitter JV commands ...']);
%     
%     jvIndexes = contains(tableData.pumpMotorMsg, 'JV=');
%     jvStrings = split(tableData.pumpMotorMsg(jvIndexes), "=");
%     jvStrings = erase(jvStrings, ";");
%     profile(fileNum).JVs = str2double(jvStrings);
%     profile(fileNum).JVsDT = profile(fileNum).DT(jvIndexes);
%     
%     %% 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 = profile(fileNum).DT(notNaN);
%  
%     notNaN = ~isnan(tableData.SHT21Humid);
%     profile(fileNum).humidity = tableData.SHT21Humid(notNaN);
%     profile(fileNum).humidityDT = profile(fileNum).DT(notNaN);
%  
%     %% Process pump power

%     %% 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 = profile(fileNum).DT(ubxMsgIndexes);
%     index = 1;
%     for i = 1:length(profile(fileNum).ubxMsgs)
%         fields = split(profile(fileNum).ubxMsgs(i), [",", "*"]);
%         if(fields(2) == "00")
%             profile(fileNum).fixDT(index) = profile(fileNum).ubxMsgsDT(i);
%             profile(fileNum).latDDM(index) = fields(4);
%             profile(fileNum).latHemi(index) = fields(5);
%             profile(fileNum).lonDDM(index) = fields(6);
%             profile(fileNum).lonHemi(index) = fields(7);
%             profile(fileNum).numSats(index) = str2double(fields(19));
%             profile(fileNum).latDD(index) = latDDM2DD(fields(4), fields(5));
%             profile(fileNum).lonDD(index) = lonDDM2DD(fields(6), fields(7));
%             index = index + 1;
%         end
%     end
%         
% %     for i=1:length(profile(fileNum).ubxMsgs)
% %         fprintf('%s %s\n', profile(fileNum).ubxMsgsDT(i),  profile(fileNum).ubxMsgs(i));
% %     end
%     fprintf('\n');
%     
%     %% 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);
% %% Process Twitter IQ and JV messages
% %     fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing Twitter IQ Messages ...']);
% %     
% %     iqIndex = find(tableData.pumpMotor == "IQ;");
% %     iq = tableData.pumpMotor(iqIndex + 1);
% %     profile(fileNum).iq = str2double(strip(iq,';'));
% %     profile(fileNum).iqDT = datetime(dt(iqIndex+1), 'InputFormat', 'dd-MMM-yyyyHH:mm:ss.SSS');
% %     
% %     jvIndex = find(contains(tableData.pumpMotor, "JV="));
% %     jv = tableData.pumpMotor(jvIndex);
% %     jvFields = split(jv, ["=", ";"]);
% %     profile(fileNum).jv = str2double(jvFields(:,2));
% %     profile(fileNum).jvDT = datetime(dt(jvIndex), 'InputFormat', 'dd-MMM-yyyyHH:mm:ss.SSS');
% %             
%     %% 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.comment(errorMsgIndexes);
%     profile(fileNum).errorMsgDT = profile(fileNum).DT(errorMsgIndexes);
%       
%     fprintf(1, 'Errors in %d files processed: \r', i );
%     
%     for i = 1:length(errorMsgIndexes)
%         %fprintf(1, 'Error %d at time %s : %s \r', i, datestr(profile(fileNum).errorMsgDT(i)), profile(fileNum).errorMsg(i));
%     end
%  
% end
% %% Process mission totals
%     pumpTotalEnergyMinusTransit = profile(end).missionPumpEnergyTotal - totalPumpEnergyTransit;
%     fprintf('Total pump energy this mission = %.0f Joules', pumpTotalEnergyMinusTransit);
%     percentAvailable = 100 * pumpTotalEnergyMinusTransit / energyAvailable;
%     fprintf(' = %3.1f precent of total Joules available\n\n', percentAvailable);
% 
%     hotelTotalEnergyMinusTransit = profile(end).missionHotelEnergyTotal - totalHotelEnergyTransit;
%     fprintf('Total hotel energy this mission = %.0f Joules', hotelTotalEnergyMinusTransit);
%     percentAvailable = 100 * hotelTotalEnergyMinusTransit / energyAvailable;
%     fprintf(' = %3.1f precent of total Joules available\n\n', percentAvailable);
% 
%     missionEnergyMinusTransit = profile(end).missionEnergyTotal - totalPumpEnergyTransit - totalHotelEnergyTransit;
%     fprintf('Total energy this mission = %.0f Joules', missionEnergyMinusTransit);
%     percentAvailable = 100 * missionEnergyMinusTransit / energyAvailable;
%     fprintf(' = %3.1f precent of total Joules available\n\n', percentAvailable);
% 
%     allLatsDD = [];
%     allLonsDD = [];
%     for i=1:length(profile)
%         allLatsDD = [allLatsDD profile(i).latDD];
%         allLonsDD = [allLonsDD profile(i).lonDD];
%     end
%     [allEastings, allNorthings] = LatLon2UTM(allLatsDD, allLonsDD);
%     %% Read .msg files
%     msgFileList = ls([startingDir,'*.msg']);
%     numMsgFiles = size(fileList, 1);
%     
% %     for i=1:length(msgFileList)
% %         fullFileName = [startingDir msgFileList(i,:)];
% %         fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Importing .msg Filename: ' fullFileName 'file number: ' int2str(fileNum) ' of ' int2str(length(fileList))]);
% %         
% %         msg(i) = tdfread(fullFileName);
% %     end
% 
% %% plot individual profiles
% if(plotProfiles)
%     figure
%     plot(profile(fileNum).pidY1DT, profile(fileNum).pidY1, ...
%         profile(fileNum).LPFVelDT, profile(fileNum).LPFVel, ...
%         profile(fileNum).diffVelDT, profile(fileNum).diffVel, ...
%         profile(fileNum).diff2VelDT, profile(fileNum).diff2Vel, ...
%         profile(fileNum).slopeOfLPFPressDT, profile(fileNum).slopeOfLPFPress);
%     legend('pidY1', 'LPFVel', 'diffVel', 'diff2Vel', 'slopeOfLPFPress');
%     hold on
%     plotStateTransitions(tableData, profile(fileNum).DT);
%     hold off
%     xlabel('Time');
%     ylabel('Platform Velocity');
% end
% 
% if(false)
%     for  profileNum = 1:length(profile)
%         figure
%         title(['Pump and Hotel Power ' profile(profileNum).fileName]);
%         yyaxis left;
%         plot(profile(profileNum).pumpPowerCalcDT, profile(profileNum).pumpPowerCalc)
%         ylabel('Pump Power (millimilliWattss)')
%         yyaxis right;
%         hold on
%         plot(profile(profileNum).hotelPowerCalcDT, profile(profileNum).hotelPowerCalc)
%         ylabel('Hotel power (millimilliWattss)')
%         plotStateTransitions(tableData, profile(profileNum).DT);
%         xlabel('Time');
%         hold off
%         
%         figure
%         title(['Pump and Hotel Energy ' profile(profileNum).fileName]);
%         yyaxis left;
%         plot(profile(profileNum).pumpEnergyCalcSumDT, profile(profileNum).pumpEnergyCalcSum)
%         ylabel('Pump Energy (Joules)')
%         yyaxis right;
%         hold on
%         plot(profile(profileNum).hotelEnergyCalcSumDT, profile(profileNum).hotelEnergyCalcSum)
%         ylabel('Hotel Energy (Joules)')
%         plotStateTransitions(tableData, profile(profileNum).DT);
%         xlabel('Time');
%         hold off
%         
%         
%     end
%     
%     fig = figure('Name','Pump Energy (calculated)','NumberTitle','off');
%     title('Pump Bus Energy (calculated)')
%     hold on;
%     for profileNum = 1:length(profile)
%         for i=1:length(profile(profileNum).pumpEnergyCalcDT)
%             x(i) = profile(profileNum).pumpEnergyCalcDT(1);
%         end
%         y = profile(profileNum).pumpEnergyCalcDT - profile(profileNum).initProfileStartTime;
%         plot3(x, y, profile(profileNum).pumpEnergyCalc)
%         clear x;
%     end
%     set(gca, 'YDir', 'reverse');
%     xlabel('Profile Start time');
%     ylabel('Time from Profile Start')
%     zlabel('Pump Bus Energy (calculated Joules)')
%     grid
%     view(3)
%     
% %     fig = figure('Name','Pump Power (calculated)','NumberTitle','off');
% %     title('Pump Bus Power (calculated)')
% %     hold on;
% %     for profileNum = 1:length(profile)
% %         for i=1:length(profile(profileNum).pumpPowerCalcDT)
% %             x(i) = profile(profileNum).pumpPowerCalcDT(1);
% %         end
% %         y = profile(profileNum).pumpPowerCalcDT - profile(profileNum).initProfileStartTime;
% %         plot3(x, y, profile(profileNum).pumpPowerCalc)
% %         clear x;
% %     end
% %     set(gca, 'YDir', 'reverse');
% %     xlabel('Profile Start time');
% %     ylabel('Time from Profile Start')
% %     zlabel('Pump Bus Power (calculated milliWatts)')
% %     grid
% %     view(3)
% % 
% %     fig = figure('Name','Hotel Power (calculated)','NumberTitle','off');
% %     title('Hotel Bus Power (calculated)')
% %     hold on;
% %     for profileNum = 1:length(profile)
% %         for i=1:length(profile(profileNum).hotelPowerCalcDT)
% %             x(i) = profile(profileNum).hotelPowerCalcDT(1);
% %         end
% %         y = profile(profileNum).hotelPowerCalcDT - profile(profileNum).initProfileStartTime;
% %         plot3(x, y, profile(profileNum).hotelPowerCalc)
% %         clear x;
% %     end
% %     set(gca, 'YDir', 'reverse');
% %     xlabel('Profile Start time');
% %     ylabel('Time from Profile Start')
% %     zlabel('Hotel Bus Power (calculated milliWattss)')
% %     grid
% %     view(3)
% end
% 
% if(plotProfiles)
%     figure
%     yyaxis left
%     ylabel('Pressure (dBar)');
%     yyaxis right
%     ylabel('Slope of LPF Pressure (dBar/sec)');
%     title('Pressure and Platform Velocity');
%     
%     hold on
%     for i = 1:numFiles
%         yyaxis left
%         plot(profile(i).pressureDT, profile(i).pressure, 'b-')
%         yyaxis right
%         plot(profile(i).slopeOfLPFPressDT, profile(i).slopeOfLPFPress, 'r-')
%     end
% end
% 
% if(plotProfiles)
%     for i=1:numFiles
%         figLabel = 'Pressure and Bellows Position, Profile Num: ' + string(i);
%         plotPandBP(figLabel, i, profile, tableData);
%         
%         figLabel = 'Pressure and Jog Velocity, Profile Num: ' + string(i);
%         plotPandJV(figLabel, i, profile, tableData);
%         
%         figLabel = 'Pressure and energy sum, ProfileNum: ' + string(i);
%         plotPandEnergySum(figLabel, i, profile, tableData);
%     end
%     
%     plotAllFixes(profile, allEastings, allNorthings);
%     
%     figure
%     hold on
%     for i=1:length(profile)
%         plot(profile(i).pressureDT, profile(i).pressure)
%     end
%     
% end
% 
% %% Waterfall plots
% if(plotWaterfalls)
%     fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Plotting waterfalls ...']);
%     
%     figX = 0.05;
%     figXIncr = 0.05;
%     figY = 0.6;
%     figYIncr = -0.05;
%     figWidth = 0.3;
%     figHeight = 0.3;
%     
%     %% Depth
%     fig = figure('Name','Depth','NumberTitle','off');
%     fig.Units = 'normalized';
%     fig.Position = [figX figY figWidth figHeight];
%     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
%     set(gca, 'YDir', 'reverse');
%     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 figWidth figHeight];
%     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
%     set(gca, 'YDir', 'reverse');
%     zlim([0 100]);
%     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 figWidth figHeight];
%     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
%     set(gca, 'YDir', 'reverse');
%     xlabel('Profile Start time');
%     ylabel('Time from Profile Start')
%     zlabel('Pump Bus Volts')
%     grid
%     view(3)
% 
%     %% Internal Pressure
%     fig = figure('Name','Internal Pressure','NumberTitle','off');
%     fig.Units = 'normalized';
%     fig.Position = [figX figY figWidth figHeight];
%     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
%     set(gca, 'YDir', 'reverse');
%     xlabel('Profile Start time');
%     ylabel('Time from Profile Start')
%     zlabel('Internal Pressure (mBar)')
%     grid
%     view(3)
%     
% 
% %Pump power
% fig = figure('Name','Pump Power (calculated)','NumberTitle','off');
% fig.Units = 'normalized';
% fig.Position = [figX figY figWidth figHeight];
% figX = figX + figXIncr;
% figY = figY + figYIncr;
% title('Pump Bus Power (calculated)')
% hold on;
% 
% for profileNum = 1:length(profile)
%     for i=1:length(profile(profileNum).pumpPowerCalcDT)
%         x(i) = profile(profileNum).pumpPowerCalcDT(1);
%     end
%     y = profile(profileNum).pumpPowerCalcDT - profile(profileNum).pumpPowerCalcDT(1);
%     plot3(x, y, profile(profileNum).pumpPowerCalc)
%     clear x;
% end
% set(gca, 'YDir', 'reverse');
% xlabel('Profile Start time');
% ylabel('Time from Profile Start')
% zlabel('Pump Bus Power (calculated milliWattss)')
% grid
% view(3)
% 
% %% Humidity
%     fig = figure('Name','Humidity','NumberTitle','off');
%     fig.Units = 'normalized';
%     fig.Position = [figX figY figWidth figHeight];
%     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
%     set(gca, 'YDir', 'reverse');
%     xlabel('Profile Start time');
%     ylabel('Time from Profile Start')
%     zlabel('Humidity (%RH)')
%     grid
%     view(3)
%   
%     %% Hotel Energy sum
%     fig = figure('Name','Hotel Cumul. Energy','NumberTitle','off');
%     fig.Units = 'normalized';
%     fig.Position = [figX figY figWidth figHeight];
%     figX = figX + figXIncr;
%     figY = figY + figYIncr;
%     title('Hotel Cumulative Energy (Joules)')
%     hold on;
%     
%     for profileNum = 1:length(profile)
%         for i=1:length(profile(profileNum).hotelEnergyCalcSumDT)
%             x(i) = profile(profileNum).hotelEnergyCalcSumDT(1);
%         end
%         y = profile(profileNum).hotelEnergyCalcSumDT - profile(profileNum).hotelEnergyCalcSumDT(1);
%         plot3(x, y, profile(profileNum).hotelEnergyCalcSum)
%         clear x;
%     end
%     set(gca, 'YDir', 'reverse');
%     xlabel('Profile Start time');
%     ylabel('Time from Profile Start')
%     zlabel('Hotel Cumulative Energy (Joules')
%     grid
%     view(3)
%     
%     %% Pump Energy sum
%     fig = figure('Name','Pump Cumul. Energy','NumberTitle','off');
%     fig.Units = 'normalized';
%     fig.Position = [figX figY figWidth figHeight];
%     figX = figX + figXIncr;
%     figY = figY + figYIncr;
%     title('Pump Cumulative Energy (Joules)')
%     hold on;
%     
%     for profileNum = 1:length(profile)
%         for i=1:length(profile(profileNum).pumpEnergyCalcSumDT)
%             x(i) = profile(profileNum).pumpEnergyCalcSumDT(1);
%         end
%         y = profile(profileNum).pumpEnergyCalcSumDT - profile(profileNum).pumpEnergyCalcSumDT(1);
%         plot3(x, y, profile(profileNum).pumpEnergyCalcSum)
%         clear x;
%     end
%     set(gca, 'YDir', 'reverse');    xlabel('Profile Start time');
%     ylabel('Time from Profile Start')
%     zlabel('Pump Cumulative Energy (Joules')
%     grid
%     view(3)
% 
% end