clear all
close all
[allData, header, pressureDT, pressure, bellowsPositionDT, bellowsPosition] = procCPFEngrLog;

function [cellData, header, pressureDT, pressure, ...
         bellowsPositionDT, bellowsPosition] = procCPFEngrLog;
        
    startingDir = '//atlas.shore.mbari.org/ProjectLibrary/CPF/Data/BenchTopSimulatorTest2018Dec11-/2019Jan09/';
    [fileName, pathName] = uigetfile([startingDir '*.eng']);
    numFiles = 1;
    
    init;

    fullFileName = fullfile(pathName, fileName);
   
    for i = 1:numFiles
        setFigurePositions;
        
        fprintf('%s\n',[datestr(now, 'HH:MM:SS ') 'Importing file: ' fullFileName ' ...']);

        fid = fopen(fullFileName);

        headerLine = fgetl(fid);
        header  = textscan(headerLine,'%s','Delimiter','\t');
        header  = header{1,1};

        formatString = '';
        for i = 1:length(header)
            formatString = [formatString,' %s'];
        end

        cellData = textscan(fid, formatString, 'Delimiter','\t');
        fclose(fid);

        %fprintf([datestr(now, 'HH:MM:SS ') 'Processing date/time ...']);
        d = char(cellData{dateIndex});
        t = char(cellData{timeIndex});
        dt = [d t];
        dateTime = datetime(dt, 'InputFormat', 'dd-MMM-yyyyHH:mm:ss.SSS');
        profileStartTime(profileStartTimeIndex) = dateTime(1);
        profileStartTimeIndex = profileStartTimeIndex + 1;

        %fprintf([datestr(now, 'HH:MM:SS ') 'Processing pressure ...']);
        a = cellfun(@str2num, cellData{rawPressureIndex}, 'UniformOutput', false);
        emptyCellIndexes = cellfun('isempty', a);
        a(emptyCellIndexes) = {nan};
        pressure = cell2mat(a);

        glideOnFind = strfind(cellData{commentIndex}, 'glide on');
        glideOnMsgIndexes = find(cellfun('isempty', glideOnFind) == 0);
        for i = 1:length(glideOnMsgIndexes)
            for j = 0:5
                glideOnDepth(glideOnIndex) = str2double(char(cellData{pressureIndex}(glideOnMsgIndexes(i)-j)));
                if ~isnan(glideOnDepth(glideOnIndex))
                    break;
                end
            end
            glideOnTime(glideOnIndex) = dateTime(glideOnMsgIndexes(i));
            glideOnIndex = glideOnIndex + 1;
        end

        glideOffFind = strfind(cellData{commentIndex}, 'glide off');
        glideOffMsgIndexes = find(cellfun('isempty', glideOffFind) == 0);
        for i = 1:length(glideOffMsgIndexes)
            for j = 0:5
                glideOffDepth(glideOffIndex) = str2double(char(cellData{pressureIndex}(glideOffMsgIndexes(i)-j)));
                if ~isnan(glideOffDepth(glideOffIndex))
                    break;
                end
            end
            glideOffTime(glideOffIndex) = dateTime(glideOffMsgIndexes(i));
            glideOffIndex = glideOffIndex + 1;
        end
        
        %fprintf([datestr(now, 'HH:MM:SS ') 'Processing bellows position ...']);
        a = cellfun(@str2num, cellData{bellowsPosIndex}, 'UniformOutput', false);
        emptyCellIndexes = cellfun('isempty', a);
        a(emptyCellIndexes) = {nan};
        bellowsPosition = cell2mat(a);

        figure(pressureFig);
        pressureDT = dateTime(~isnan(pressure));
        pressure = pressure(~isnan(pressure));
        bellowsPositionDT = dateTime(~isnan(bellowsPosition));
        bellowsPosition = bellowsPosition(~isnan(bellowsPosition));
        [hAx, hLine1, hLine2] = plotyy(pressureDT, pressure, bellowsPositionDT, bellowsPosition);
        ylabel(hAx(1), 'Pressure (dBar)');
        ylabel(hAx(2), 'Bellows Position (mm)');
        
        if plotFilename
            text(datenum(dateTime(1)), 0, fullFileName, 'rotation', 270, 'HorizontalAlignment', 'left', 'interpreter', 'none');
        end
        
        plotStateTransitions;

        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 = [];

        %fprintf([datestr(now, 'HH:MM:SS ') 'Processing pump speed ...']);
        a = cellfun(@str2num, cellData{pumpSpeedIndex}, 'UniformOutput', false);
        emptyCellIndexes = cellfun('isempty', a);
        a(emptyCellIndexes) = {nan};
        pumpSpeed = cell2mat(a);

        figure(pumpSpeedFig);
        pumpSpeedDT = dateTime(~isnan(pumpSpeed));
        pumpSpeed = pumpSpeed(~isnan(pumpSpeed));
        [hAx, hLine1, hLine2] = plotyy(pressureDT, pressure, pumpSpeedDT, pumpSpeed);
        ylabel(hAx(1), 'Pressure (dBar)');
        ylabel(hAx(2), 'Pump Speed (RPS');
        
        if plotFilename
            text(datenum(dateTime(1)), 0, fullFileName, 'rotation', 270, 'HorizontalAlignment', 'left', 'interpreter', 'none');
        end
        
        plotStateTransitions;

        
        %fprintf([datestr(now, 'HH:MM:SS ') 'Calculating Power ...']);
        clear a
        a = cellfun(@str2num, cellData{batteryVoltsIndex}, 'UniformOutput', false);
        emptyCellIndexes = cellfun('isempty', a);
        a(emptyCellIndexes) = {nan};
        batteryVolts = cell2mat(a);

        clear a
        a = cellfun(@str2num, cellData{batteryAmpsIndex}, 'UniformOutput', false);
        emptyCellIndexes = cellfun('isempty', a);
        a(emptyCellIndexes) = {nan};
        batteryAmps = cell2mat(a) / 1000.0;
        power = batteryVolts .* batteryAmps;
        
        figure(batteryVoltsFig);
        batteryVoltsDT = dateTime(~isnan(batteryVolts));
        batteryVolts = batteryVolts(~isnan(batteryVolts));
        batteryAmpsDT = dateTime(~isnan(batteryAmps));
        batteryAmps = batteryAmps(~isnan(batteryAmps));
        [hAx, hLine1, hLine2] = plotyy(batteryVoltsDT, batteryVolts, batteryAmpsDT, batteryAmps);
        ylabel(hAx(1), 'Battery Volts');
        ylabel(hAx(2), 'Battery Amps');
        plotStateTransitions
        
        %fprintf([datestr(now, 'HH:MM:SS ') 'Calculating Energy ... \t']);
        powerValuesIndex = ~isnan(power);
        tempPower = power(powerValuesIndex);
        tempDateTime = dateTime(powerValuesIndex);
        energy = tempPower(1:end-1) .* seconds((tempDateTime(2:end) - tempDateTime(1:end-1)));

        energySum = cumsum(energy);
        energySum(length(energySum) + 1) = energySum(end);

        totalEnergy = sum(energy);
        energyHistoryTime(i) = dateTime(end);
        energyHistoryEnergy(i) = totalEnergy;
        fprintf('Total Energy this profile = %.0f Joules\n\n', totalEnergy);

        ubxFind = strfind(cellData{gpsIndex}, 'UBX');
        ubxMsgIndexes = find(cellfun('isempty', ubxFind) == 0);
        try
            for i = 1:length(ubxMsgIndexes)
                ubxMsg = char(cellData{gpsIndex}(ubxMsgIndexes(i)));
                ubxSplit = strsplit(ubxMsg, ',');
                numSats(numSatsIndex) = str2double(char(ubxSplit(18)));
                numSatsTime(numSatsIndex) = dateTime(ubxMsgIndexes(i));
                numSatsIndex = numSatsIndex + 1;
            end
        catch me
            fprintf(1, 'Error parsing UBX message\n');
        end

        sbdixFind = strfind(cellData{iridiumIndex}, '+SBDIX:');
        sbdixMsgIndexes = find(cellfun('isempty', sbdixFind) == 0);
        for i = 1:length(sbdixMsgIndexes)
            sbdixMsg = char(cellData{iridiumIndex}(sbdixMsgIndexes(i)));
            sbdixSplit = strsplit(sbdixMsg, ',');
            numSBDIX(numSBDIXIndex) = i;
            numSBDIXTime(numSBDIXIndex) = dateTime(sbdixMsgIndexes(i));
            numSBDIXIndex = numSBDIXIndex + 1;
        end

        errorFind = strfind(cellData{commentIndex}, 'Error');
        errorMsgIndexes = find(cellfun('isempty', errorFind) == 0);
        for i = 1:length(errorMsgIndexes)
            errorMsg(errorIndex) = cellData{commentIndex}(errorMsgIndexes(i));
            errorMsgTime(errorIndex) = dateTime(errorMsgIndexes(i));
            errorIndex = errorIndex + 1;
        end

        bpLimitErrorFind = strfind(cellData{commentIndex}, 'exceeds limits');
        bpLimitErrorMsgIndexes = find(cellfun('isempty', bpLimitErrorFind) == 0);
        for i = 1:length(bpLimitErrorMsgIndexes)
            bpLimitErrorMsg(bpLimitErrorIndex) = cellData{commentIndex}(bpLimitErrorMsgIndexes(i));
            bpLimitErrorMsgTime(bpLimitErrorIndex) = dateTime(bpLimitErrorMsgIndexes(i));
            bpLimitErrorIndex = bpLimitErrorIndex + 1;
        end

        fprintf(1, 'Summary of errors in %d files processed: \r\n', i );

        for i = 1:errorIndex-1
            fprintf(1, 'Error %d at time %s : %s \r\n', i, datestr(errorMsgTime(i)), errorMsg{i});
        end

        fprintf(1, '\r\nTotal number of Bellow Position Limit Errors = %d \r\n', bpLimitErrorIndex - 1);

%         figure(numSatsFig);
%         try
%             plot(numSatsTime, numSats, '+-');
%             title('Number of GPS Satellites vs Time')
%         catch me
%             title('Number of GPS Satellites not processed');
%         end
% 
%         figure(numIridiumTrysFig);
%         try
%             plot(numSBDIXTime, numSBDIX, '+-');
%             title('Number of SBDIX Attempts vs Time')
%         catch me
%             title('Number of SBDIX Attempts not processed');
%         end
    
        header = header';
       % figure(pressureFig);
        
        figure(pressureOnlyFig);
        plot(pressure);
        
%        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
    
    function init
        dateIndex = 2;
        timeIndex = 3;
        stateIndex = 4;
        commentIndex = 5;
        pressureIndex = 6;
        bellowsPosIndex = 7;
        batteryVoltsIndex = 8;
        batteryAmpsIndex = 9;
        ctdIndex = 11;
        rawPressureIndex = 12;
        LPS311TemperatureIndex = 20;
        SHT21TemperatureIndex = 22;
        pumpSpeedIndex = 30;
        gpsIndex = 39;
        iridiumIndex = 40;
        
        numSatsIndex = 1;
        numSBDIXIndex = 1;
        profileStartTimeIndex = 1;
        glideOnIndex = 1;
        glideOffIndex = 1;
        errorIndex = 1;
        bpLimitErrorIndex = 1;
        plotFilename = true;
    end

    function setFigurePositions
        figX = 0.05;
        figXIncr = 0.05;
        figY = 0.6 - (i * 0.1);
        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;
        
        batteryVoltsFig = figure;
        batteryVoltsFig.Units = 'normalized';
        figX = figX + figXIncr;
        figY = figY + figYIncr;
        batteryVoltsFig.Position = [figX figY 0.6 0.4];
        title('Battery 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

    function plotStateTransitions
        %figure(pressureFig);
        ylimits = ylim;
        
        textY1 = ylimits(1) + 0.04 * (ylimits(2) - ylimits(1));
        textY2 = ylimits(1) + 0.07 * (ylimits(2) - ylimits(1));
        
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'AB Retract Fast')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], ':');
            text( dateTime(index), textY1, 'AB Dec Buoycy')
        end
        
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'Descend')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], '-.');
            text( dateTime(index), textY2, 'Descend')
        end
        
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'Anchor')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], ':');
            text( dateTime(index), textY1, 'Anchor')
        end
        
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'Park')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], ':');
            text( dateTime(index), textY1, 'Anchor')
        end
        
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'Start CP Mode')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], '-.');
            text( dateTime(index), textY2, 'Start CP Mode')
        end
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'DeAnchor')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], ':');
            text( dateTime(index), textY1, 'DeAnchor')
        end
        
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'Ascend')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], '-.');
            text( dateTime(index), textY2, 'Ascend')
        end
        
        indexes = find(cellfun('isempty', strfind(cellData{4}, 'Init Profile')) == 0);
        if( ~isempty(indexes))
            index = indexes(1);
            plot( [dateTime(index) dateTime(index)], [ylimits(1) ylimits(2)], ':');
            text( dateTime(index), textY1, 'Init Profile')
        end
    end

end





