clear all
close all

plotWaterfalls = false;
plotProfiles = false;

startingDir = '\\atlas\ProjectLibrary\CPF\Data\AnalysisScripts\2022-4-25T16-25-48\';
totalHotelEnergyTransit = 0;
totalPumpEnergyTransit = 0;

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

%% Variable names
fileFormat = 3;  %1 = pre 2021Feb26, 2 = 1 to 2021Mar15, 3 = post 2021Mar15

if(fileFormat == 3)
varNames = {'stx', 'date', 'time', 	'state', 	'comment', 	...
    'pressure', 'bellowsPos', ...
    'pumpVolts', 	'pumpMilliamps', 'pumpCoulombs', 'pumpJoules', 'pumpMotor'...
    'hotelVolts', 	'hotelMilliamps', 'hotelCoulombs', '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', ...
    'OCRtext', 'OCRCh1', 'OCRCh2', 'OCRCh3', 'OCRCh4', ...
    'GPS', 'IridModem', 'MSC'};
varTypes = {'string', 'string', 'string', 'string', 'string', ...
    'double', 'double', ...
    'double', 'double','double', 'double', 'string'...
    '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', 'string', ...
    'string', 'string', 'string'};   
elseif(fileFormat == 2)
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

%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

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

profile(1).missionEnergyTotal = 0;
profile(1).missionPumpEnergyTotal = 0;
profile(1).missionHotelEnergyTotal = 0;

for fileNum = 1:numFiles
    %% Open and read file
    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);
 
    profile(fileNum).fileName = fullFileName;
    
    %% Process date/time
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing date/time ...']);
   
    dt = tableData.date + tableData.time;
    profile(fileNum).DT= datetime(dt, 'InputFormat', 'dd-MMM-yyyyHH:mm:ss.SSS');
    
    initProfileIndexes = find(tableData.state == 'Init Profile');
    if ~isempty(initProfileIndexes)
        profile(fileNum).initProfileStartTime = profile(fileNum).DT(initProfileIndexes(1));
    else
        profile(fileNum).initProfileStartTime = profile(fileNum).DT(1);
    end

    %% Process pressure
    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);

    %% Process Platform Velocities
    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.slopeOfLPFPress);
    profile(fileNum).slopeOfLPFPress = tableData.slopeOfLPFPress(notNaN);
    profile(fileNum).slopeOfLPFPressDT = profile(fileNum).DT(notNaN);

    %% Process PID
    notNaN = ~isnan(tableData.pid_uCPS);
    profile(fileNum).pid_uCPS = tableData.pid_uCPS(notNaN);
    profile(fileNum).pid_uCPSDT = profile(fileNum).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 = profile(fileNum).DT(notNaN);
 
    %% Find glide on
    glideOnFind = strfind(tableData.comment, 'glide on');
    glideOnMsgIndexes = find(isempty(glideOnFind) == 0);
   
    
    %% Find glide off
    glideOffFind = strfind(tableData.comment, 'glide off');
    glideOffMsgIndexes = find(isempty(glideOffFind) == 0);
   
    

    %% Process PID uCPS
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing PID uCPS ...']);
    
    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
     
     %% Process Twitter JV commands
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Processing Twitter JV commands ...']);
    
    jvIndexes = contains(tableData.pumpMotor, 'JV=');
    jvStrings = split(tableData.pumpMotor(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
    fprintf('%s\n', [datestr(now, 'HH:MM:SS ') 'Calculating Pump Power ...']);

    notNaN = ~isnan(tableData.pumpVolts);
    profile(fileNum).pumpVolts = tableData.pumpVolts(notNaN);
    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) / 1000.0;
    profile(fileNum).pumpAmpsDT = profile(fileNum).DT(notNaN);
    if(profile(1).pumpAmpsDT(1) < datetime(2000, 1, 1))
        profile(1).pumpAmpsDT(1) = profile(1).pumpAmpsDT(2) - duration(0, 0, 1);
    end

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

   
    notNaN = ~isnan(tableData.pumpJoules);
    profile(fileNum).pumpJoules = tableData.pumpJoules(notNaN);
    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

    vecLength = min(length(profile(fileNum).pumpAmpsDT), length(profile(fileNum).pumpVoltsDT));
    profile(fileNum).pumpPowerCalc = profile(fileNum).pumpVolts(1:vecLength) .* profile(fileNum).pumpAmps(1:vecLength);
    profile(fileNum).pumpPowerCalcDT = profile(fileNum).pumpAmpsDT(1:vecLength);
 
    fprintf('%s\t', [datestr(now, 'HH:MM:SS ') 'Calculating Energy ...']);
    profile(fileNum).pumpEnergyCalc = profile(fileNum).pumpPowerCalc(1:end-1) .* seconds( profile(fileNum).pumpPowerCalcDT(2:end) - profile(fileNum).pumpPowerCalcDT(1:end-1));
    profile(fileNum).pumpEnergyCalcDT = profile(fileNum).pumpAmpsDT(2:end);
    
    profile(fileNum).pumpEnergyCalcSum = cumsum(profile(fileNum).pumpEnergyCalc);
    profile(fileNum).pumpEnergyCalcSumDT = profile(fileNum).pumpEnergyCalcDT;
    
    profile(fileNum).totalPumpEnergy = sum(profile(fileNum).pumpEnergyCalc);
    
    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));
        
     %% 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 = 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
    profile(fileNum).hotelVoltsState = tableData.state(notNaN);
    
    notNaN = ~isnan(tableData.hotelMilliamps);
    profile(fileNum).hotelAmps = tableData.hotelMilliamps(notNaN) / 1000.0;
    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
    profile(fileNum).hotelMilliampsState = tableData.state(notNaN);
    
    notNaN = ~isnan(tableData.hotelCoulombs);
    profile(fileNum).hotelCoulombs = tableData.hotelCoulombs(notNaN);
    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);
    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
    
    vecLength = min(length(profile(fileNum).hotelAmpsDT), length(profile(fileNum).hotelVoltsDT));
    profile(fileNum).hotelPowerCalc = profile(fileNum).hotelVolts(1:vecLength) .* profile(fileNum).hotelAmps(1:vecLength);
    profile(fileNum).hotelPowerCalcDT = profile(fileNum).hotelVoltsDT(1:vecLength);
    profile(fileNum).hotelPowerCalcState = profile(fileNum).hotelVoltsState(1:vecLength);
      
    fprintf('%s\t', [datestr(now, 'HH:MM:SS ') 'Calculating Energy ...']);
    profile(fileNum).hotelEnergyCalc = profile(fileNum).hotelPowerCalc(1:end-1) .* seconds( profile(fileNum).hotelPowerCalcDT(2:end) - profile(fileNum).hotelPowerCalcDT(1:end-1));
    profile(fileNum).hotelEnergyCalcDT = profile(fileNum).hotelPowerCalcDT(2:end);
    profile(fileNum).hotelEnergyCalcState = profile(fileNum).hotelVoltsState(1:vecLength);
    
    profile(fileNum).hotelEnergyCalcSum = cumsum(profile(fileNum).hotelEnergyCalc);
    profile(fileNum).hotelEnergyCalcSumDT = profile(fileNum).hotelEnergyCalcDT;
    
    profile(fileNum).totalHotelEnergy = sum(profile(fileNum).hotelEnergyCalc);

    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));
   
    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);
      
  
    %% 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(true)
    for i=1:numFiles
        figure
        title('Pump and Hotel Power');
        yyaxis left;
        plot(profile(fileNum).pumpPowerCalcDT, profile(fileNum).pumpPowerCalc)
        ylabel('Pump Power (Watts)')
        yyaxis right;
        hold on
        plot(profile(fileNum).hotelPowerCalcDT, profile(fileNum).hotelPowerCalc)
        ylabel('Hotel power (Watts)')
        plotStateTransitions(tableData, profile(fileNum).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 Watts)')
%     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 Watts)')
%     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 Watts)')
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


