clear all
close all

% Created by Gene Massion
% 11/04/2021, Modified by Magdalena:
% - use dir as opposed to ls to list files. save figures. print lat,lon of
%  predicted position in Map
% 11/16/2021, modified by MC to adjust field columns (SBD essage has more
% info). Plotting Health Status Data
%
% 3/29/2022: Yui Takeshita
% - updated sbdFolder to point to 'Active_Deployment'. Completed
% deployments will need to be renamed into their deployment IDs, and empty
% 'Active_Deployment'.
%
% 04/01/2022: Josh Plant
% Added several code blocks to:
%   1) automatically rename profile file SBD's with profile number
%   2) check for inconsistent SBD message & exclude from processing
%   3) Check for missing lat & lon and exclude from plotting
%   4) check for poor position fix and exclude from plotting (MAD)
%   5) generate text file of any sbds which generate warnings from tests above
%   6) build an additional table of just "good" profile positions.
%   7) replace "fix" structure with "pfix" because "fix" is a matlab function

% Specify folder to read SBDS and save kml track and plots
% sbdFolder = '\\atlas\ProjectLibrary\CPF\Operations\2021Nov02\';
% sbdFolder = '/Volumes/CPF/Operations/2021Nov02/';
% sbdFolder = '\\atlas\ProjectLibrary\CPF\Operations\2022Feb23\';
%sbdFolder = '\\atlas\ProjectLibrary\CPF\Operations\Active_Deployment\'; % YT 3/29/202. 
sbdFolder = 'C:\Users\jplant\Documents\MATLAB\CPF\data\'; % JP TESTING
% sbdFolder = '\\atlas\ProjectLibrary\CPF\Operations\2022Mar29\'; % YT 3/29/202. 
CPF_warning_fn = 'SBD_warning_log.TXT';
MISSIONID = '2022Mar29';
CPFID     = '003';
tifPath = 'C:\Users\jplant\Documents\MATLAB\CPF\montbay_colorshd.tif';

%webFolder = '\\sirocco\wwwroot\chemsensor\CPF_Current_dep\'; % YT
webFolder=sbdFolder;
path_plots=sbdFolder;

% fileList = ls([sbdFolder, '*.sbd*']);
fileList        = dir([sbdFolder, '*.sbd*']);
CPF_warning_log = cell(100,3); % sbd file, warning, sbd msg
err_ct          = 0;
GMT_offset      = -7; % for plotting DST
battV_threshold = 20; % lower limit, volts

% *************************************************************************
% DO A QUICK SCAN OF SBD MESSAGES & AND RENAME WITH MEANINGFUL NAMES
fnames    = {fileList.name}';
tProfiles = ~cellfun(@isempty, regexp(fnames,'0{6}','once')); % look for 6 zeros in a row (a true profile)
tg_name   = cellfun(@isempty, regexp(fnames,'(?<=0{6})\.\d{3}\.sbd','once')); % not already named
if sum(tProfiles & tg_name) > 0
    fnames = fnames(tProfiles & tg_name);
    fprintf('%0.0f sbd files will be renamed\n',size(fnames,1))
    for i = 1:size(fnames,1)
        fn   = fnames{i};
        fp   = fullfile(sbdFolder,fn);
        str  = fileread(fp);
        prof_num = regexp(str,'(?<=Prof Num,)\d+','once', 'match'); % cycle # as str
        name_parts = regexp(fn,'\d+','match'); % get numeric blocks
        new_fn = sprintf('%s_%s.%s.sbd', name_parts{1}, name_parts{2}, ...
            sprintf('%03.0f',str2double(prof_num)));
        copyfile(fp, fullfile(sbdFolder,new_fn));
        delete(fp);
    end
end

% *************************************************************************

for i=1:size(fileList,1)
    % fprintf("Processing SBD number %d: %s\n", i, fileList(i,:))
    % pfix(i).sbdString = fileread([sbdFolder,'/',fileList(i,:)]);
    
    display(["Processing SBD number %d: %s\n", i, fileList(i).name])
    fp  = fullfile(fileList(i).folder, fileList(i).name);
    sbd_str = fileread(fp);
    
    
    % CHECK VALIDITY OF MSG FILE & DATA (ADD MORE TESTS AS DESIRED)
    tg_str = ~isempty(regexp(sbd_str, 'Lat.+Lon.+BBHealth', 'once')); % bad msg will not have this pattern
    tg_LAT = isempty(regexp(sbd_str,'(?<=Lat,)0000.0','once')); % look for zero lat in str
    
    if ~tg_str
        err_str = sprintf(['WARNING: SBD message is bad or incomplete for %s', ...
            ' and will be excluded from processing'], fileList(i).name);
        err_ct = err_ct + 1;
        CPF_warning_log(err_ct,:) = {fileList(i).name, err_str, sbd_str};
        disp(sbd_str)
        continue
    end
    
    if ~tg_LAT
        err_str = sprintf(['WARNING: SBD message has 000.0 for Lat & Lon', ...
            ' position fixes for %s and will be excluded from plotting'], ...
            fileList(i).name);
        err_ct = err_ct + 1;
        CPF_warning_log(err_ct,:) = {fileList(i).name, err_str, sbd_str};
        disp(sbd_str)
    end
    
    pfix(i).sbdString = sbd_str;
    %pfix(i).sbdString = fileread([fileList(i).folder,'/',fileList(i).name]);
    
    fprintf("Msg: %s\n", pfix(i).sbdString)
    sbdFields = split(pfix(i).sbdString, ',');
    if( size(sbdFields,1) < 25)
         fullField = sbdFields(4);
         latFields = split(fullField);
         latString = latFields(1,:);
         latDeg = latString{1}(1:2);
         latMin = latString{1}(3:end);
         pfix(i).latDD = str2double(latDeg) + (str2double(latMin) / 60.0);
         if(latFields{2}(1) == 'S')
             pfix(i).latDD = -1.0 * pfix(i).latDD;
         end
         
         fullField = sbdFields(5);
         lonFields = split(fullField);
         lonString = lonFields(1,:);
         tempFields = split(lonString, '.');
         lonDeg = tempFields{1}(1:end-2);
         lonMin = [tempFields{1}(end-1:end), '.', tempFields{2}];
         pfix(i).lonDD = str2double(lonDeg) + (str2double(lonMin) / 60.0);
         if(lonFields{2}(1) == 'W')
             pfix(i).lonDD = -1.0 * pfix(i).lonDD;
         end
         
         tempFields = split(sbdFields(27), ' ');
         pfix(i).profileNum = tempFields(1);
         pfix(i).timestampString = sbdFields{1};
         pfix(i).timestampNum = datenum(sbdFields{1},'yyyy-mm-ddTHH:MM:SS');
         pfix(i).battV = str2double(sbdFields(14));

    else
         fullField = sbdFields(4);
         latFields = split(fullField);
         latString = latFields(1,:);
         latDeg = latString{1}(1:2);
         latMin = latString{1}(3:end);
         pfix(i).latDD = str2double(latDeg) + (str2double(latMin) / 60.0);
         if(latFields{2}(1) == 'S')
             pfix(i).latDD = -1.0 * pfix(i).latDD;
         end
         
         fullField = sbdFields(7);
         lonFields = split(fullField);
         lonString = lonFields(1,:);
         tempFields = split(lonString, '.');
         lonDeg = tempFields{1}(1:end-2);
         lonMin = [tempFields{1}(end-1:end), '.', tempFields{2}];
         pfix(i).lonDD = str2double(lonDeg) + (str2double(lonMin) / 60.0);
         if(lonFields{2}(1) == 'W')
             pfix(i).lonDD = -1.0 * pfix(i).lonDD;
         end
         
         tempFields = split(sbdFields(15), ' ');
         pfix(i).profileNum = tempFields(1);
         pfix(i).timestampString = sbdFields{1};
         pfix(i).timestampNum = datenum(sbdFields{1},'yyyy-mm-ddTHH:MM:SS');
         pfix(i).battV = str2double(sbdFields(33));
         
         pfix(i).canP = str2double(sbdFields(35)); % MC
         pfix(i).canHum = str2double(sbdFields(37)); % MC
    end
end

unsortedFixTable = struct2table(pfix);
fixTable = sortrows(unsortedFixTable, 'timestampNum');
fprintf(1,'\nSBD attachments sorted by time\n')
fprintf(1,'Msg: %s\n', string([fixTable.sbdString]))


% CHECK FOR MISSING (000.000) FIXES & ONLY FIND profile nums > 0
% TEMPOARAY FIX ASSUMING NO REAL ZERO LAT
tgLAT  = fixTable.latDD ~= 0; % this may change to NaN?
tgPROF = str2double(fixTable.profileNum) > 0;
tg     = tgLAT & tgPROF;

% CHECK FOR UNREASONABLE POSITION FIXES - meadian absolute deviation
B = 1.4826; % Assume Normal distribution for now
LatLon   = [fixTable.latDD, fixTable.lonDD];
mLL      = median(LatLon(tgLAT&tgPROF,:),1,'omitnan'); % median
mLL_anom = abs(LatLon(tgLAT&tgPROF,:) - ones(size(LatLon(tgLAT&tgPROF,1)))*mLL);
MAD      = median(mLL_anom,1,'omitnan');
Z =  ones(size(LatLon,1),2) *NaN;
Z(tgLAT&tgPROF,:) = mLL_anom ./ MAD;
tBF = Z(:,1) > 20 | Z(:,2) >20;

if sum(tBF>0)
    err_str = sprintf(['Unreasonable position fix for profile', ...
        ' %s will be excluded from plotting'], ...
        fixTable.profileNum{tBF});
    err_ct = err_ct + 1;
    CPF_warning_log(err_ct,:) = {'---', err_str, fixTable.sbdString{tBF}};
    disp(err_str)
    tg = tg & ~tBF;
end

if err_ct > 0 % if errors print warning log to file
    CPF_warning_log = CPF_warning_log(1:err_ct,:);
    D   = CPF_warning_log';
    fid = fopen(fullfile(sbdFolder, CPF_warning_fn),'w');
    fprintf(fid,'%s\t%s\t%s\n',D{:});
    fclose(fid);
end

tf_mapping = license('test', 'mapping toolbox');
% PRE ALOCATE
fixTable.easting           = fixTable.latDD*NaN;
fixTable.northing          = fixTable.latDD*NaN;
fixTable.range             = fixTable.latDD*NaN;
fixTable.heading           = fixTable.latDD*NaN;
fixTable.speed             = fixTable.latDD*NaN;
fixTable.predictedEasting  = fixTable.latDD*NaN;
fixTable.predictedNorthing = fixTable.latDD*NaN;
fixTable.predictedLon      = fixTable.latDD*NaN;
fixTable.predictedLat      = fixTable.latDD*NaN;
fixTable.positionZScore    = Z;

% ADD SOME MORE DATA TO THETABLE
GoodFixTable = fixTable(tg,:);
nGood        = size(GoodFixTable,1);
[easting,northing,utmzone] = deg2utm(GoodFixTable.latDD,GoodFixTable.lonDD); % file exchange
fixTable.easting(tg)       = easting;
fixTable.northing(tg)      = northing;
GoodFixTable.easting       = easting;
GoodFixTable.northing      = northing;

X   = fixTable.easting(tg); % ONLY GOOD FIXES
Y   = fixTable.northing(tg);
sdn = GoodFixTable.timestampNum;
for i=2:length(X)
    if tg(i) == 0 % skip bad, missing non profile fixes
        continue
    end
    GoodFixTable.range(i) = sqrt( (X(i) - X(i-1))^2 + (Y(i) - Y(i-1))^2 );
    angle  = atan2d((Y(i) - Y(i-1)), (X(i) - X(i-1)));
    GoodFixTable.heading(i) = mod(90 - angle, 360);
    GoodFixTable.speed(i) = GoodFixTable.range(i) / ((sdn(i) - sdn(i-1)) * 24.0);
    GoodFixTable.predictedEasting(i) = X(i) + (GoodFixTable.range(i) * cosd(angle));
    GoodFixTable.predictedNorthing(i) = Y(i) + (GoodFixTable.range(i) * sind(angle));
    [GoodFixTable.predictedLat(i),GoodFixTable.predictedLon(i)] = ...
        utm2ll(GoodFixTable.predictedEasting(i), ...
        GoodFixTable.predictedNorthing(i),10,'nad83');
end


% % Write KML file for Google Earth
kmlfile = ['CPFTrack_',MISSIONID,'.kml'];
writeKMLTrack(GoodFixTable, sbdFolder, kmlfile);


% MAKE DIAGNOSTIC PLOTS
F1 = figure(1);
F1.Units = 'Inches';
F1.Position = [1 1 10 10];

ax_fontsize = 12;
TT = datetime(GoodFixTable.timestampNum ,'ConvertFrom','datenum');

% **************
ax1(1) = subplot(3,1,1);
Y = GoodFixTable.battV;
plot(TT,Y,'ko-','MarkerfaceColor','r','MarkerSize',6);
tstr = sprintf('CPF: %s   Mission: %s',CPFID, MISSIONID);
title(tstr)
ylabel('Battery voltage, volts')
hold on
plot(xlim, [battV_threshold, battV_threshold],'--','LineWidth', 2)
hold off
ax1(1).YLim(1) = battV_threshold - 1;
T1 = text(mean(ax1(1).XLim),battV_threshold+1,'Low voltage limit', ...
'Color','r', 'FontSize',12);
ax1(1).FontSize = ax_fontsize;

% **************
ax1(2) = subplot(3,1,2);
Y = GoodFixTable.canP;
plot(TT,Y,'ko-','MarkerfaceColor','r','MarkerSize',6);
ylabel('Can Pressure, mbar')
ax1(2).FontSize = ax_fontsize;

% **************
ax1(3) = subplot(3,1,3);
Y = GoodFixTable.canHum;
plot(TT,Y,'ko-','MarkerfaceColor','r','MarkerSize',6);
ylabel('Can Relative Humidity, %')
xlabel('GMT')
ax1(3).FontSize = ax_fontsize;



if ~tf_mapping
    % ************************************************************************
    %BUILD MAP  WITH OUT USING MAPPING TOOLBOX - GET GEOTIFF INFO
    % JUST FOR MBay plotting do expand until geotiff fully inderstood
    info        = imfinfo(tifPath);
    PixelScale  = info.ModelPixelScaleTag;
    ImageTiePts = info.ModelTiepointTag;
    XYsize      = [info.Width info.Height]; % X Y pixel counts
    XSandS      = [ImageTiePts(4), PixelScale(1)]; % UTM start and stride
    YSandS      = [ImageTiePts(5), PixelScale(2)]; % UTM start and stride
    
    imX = (0:XYsize(1)-1)*XSandS(2) + XSandS(1);
    
    %DON'T UNDERSTAND the minus 40* pixel count but did this to match Y's from
    %independent function check???
    % I = GEOTIFF_READ(tifPath);
    % imshow(I.z,'xdata', I.x, 'ydata', I.y );
    imY = (0:XYsize(2)-1)*YSandS(2) + YSandS(1)  -(0:XYsize(2)-1)*40;
    A = imread(tifPath);
    
    % SUBSET  LAT IMAGE DEMENSION A BIT - This is For N. Monterey bay CPF
    % DEPLOYMENT ZONE
    % COMMENT OUT FOR FULL MONTEREY BAy AND BEYOND
    tgY = imY > 4.06e6 & imY < max(imY) - 0; % northing meters
    imY = imY(tgY);
    tgX = imX > 5.7e5 & imX < max(imX) - 0; % easting meters
    imX = imX(tgX);
    A = A(tgY,tgX,:);
    
    % GET SOME SCALING INFO
    ScrnSz = get(0,'screensize'); % for normailzed fig position
    %ScrnXYratio = ScrnSz(4)./ ScrnSz(3); %for normalized fig pos
    %figWH = 0.6; % MAY NEED TO CHANGE THIS (for "normalized" fig pos)
    
    % Scaling by inches to start makes life easier for printing and dealing
    % with diff screen resolutions
    ScrnXYratio = 1; %for inches fig pos
    figWH       = 7; % MAY NEED TO CHANGE THIS (for "inches" fig pos)
    
    if numel(imX) > numel(imY) % % ASPECT RATIO TO SCALE AXIS
        AspectRatio = numel(imY)./numel(imX);
        %fig_pos_vec = [0.2 0.2  figWH*ScrnXYratio figWH*AspectRatio]; %normalized
        fig_pos_vec = [2 2  figWH*ScrnXYratio figWH*AspectRatio]; %inches
        %ax_pos_vec = [0.05 0.05 0.9 0.9*AspectRatio];
    else
        AspectRatio = numel(imX)./numel(imY);
        %fig_pos_vec = [0.2 0.2  figWH*AspectRatio*ScrnXYratio figWH]; %normalized
        fig_pos_vec = [2 2 figWH*AspectRatio*ScrnXYratio figWH]; %inches
        %ax_pos_vec = [0.05 0.05 0.9*AspectRatio 0.9];
    end
    
    F2 = figure(2);
    %F2.Units = 'Normalized';
    F2.Units = 'Inches';
    %F2.Position = [0.3375 0.6125 0.2533 0.3279];
    F2.Position = fig_pos_vec;
    
    % Keep axis ratio 1:1 & let defined fig position do the scaling
    ax2(1) = axes('units','normalized', 'position',[0.15 0.15 0.7 0.7]);
    uistack(ax2(1),'bottom');
    %hi = image(A);
    hi = imshow(A,'xdata', imX, 'ydata', imY);
    ax2(1).YDir ='Normal';
    ax2(1).Box = 'on';
    
    ax2(2) = axes('units','normalized', 'position', ax2(1).Position);
    
    plot(easting, northing,'ko','MarkerFaceColor','r', 'MarkerSize', 6)
    ax2(2).Color = 'none';
    ax2(2).YDir = 'Normal';
    ax2(2).YLim = ax2(1).YLim;
    ax2(2).XLim = ax2(1).XLim;
    
    hold on
    plot(easting(end), northing(end),'kh','MarkerFaceColor','y', 'MarkerSize', 8)
    xlabel('Easting, meters');
    ylabel('Northing, meters');
    pfix_deg = floor([GoodFixTable.latDD(nGood), GoodFixTable.lonDD(nGood)]);
    pfix_min = ([GoodFixTable.latDD(nGood), GoodFixTable.lonDD(nGood)] - pfix_deg) * 60;
    tstr1 = sprintf('Last Fix: %s (GMT%0.0fhrs)', ...
        datestr(GoodFixTable.timestampNum(nGood)+GMT_offset/24, ...
        'mm/dd/yyyy HH:MM'),GMT_offset);
    tstr2 = sprintf('%0.0f° %0.3f'' & %0.0f° %0.3f''', ...
        pfix_deg(1),pfix_min(1),pfix_deg(2),pfix_min(2));
    title({tstr1, tstr2, ' '});
    hold off
    ax2(2).FontSize = 12;
    

end

% PRINT FIGURES
set(F1,'PaperPositionMode','auto')
print(F1,[sbdFolder,'CPF_diagnostics'],'-dpng','-r160')

set(F2,'PaperPositionMode','auto')
print(F2,[sbdFolder,'CPF_track'],'-dpng','-r160')
    
    
    return
    
if tf_mapping
    %%
    % figure('Name','GPS Fixes (lat, lon)','NumberTitle','off');
    % hold on
    %
    % plot(lonDD, latDD, '-+')
    % daspect([1 1 1]);
    % pbaspect([1 1 1]);
    % grid
    % hold off
    
    %%

    
    figure % why here? JP
    
    
    
    utmstruct = defaultm('utm');
    utmstruct.zone = utmzone(fixTable.latDD(1), fixTable.lonDD(1));
    wgs84 = wgs84Ellipsoid;
    ellipsoid = [wgs84.SemimajorAxis wgs84.Eccentricity];
    utmstruct.geoid = ellipsoid;
    utm.struct = defaultm(utmstruct);
    

    
    
    [fixTable.easting(tg), fixTable.northing(tg)] = mfwdtran(utm.struct, fixTable.latDD(tg), fixTable.lonDD(tg));
    [latCheck, lonCheck] = minvtran(utm.struct, fixTable.easting, fixTable.northing);
    
    chartFig = figure('Name','GPS Fixes (easting, northing)','NumberTitle','off', 'Units', 'normalized', 'Position', [0.1 0.1 0.4 0.7]);
    [mbay, R] = readgeoraster('\\atlas\ProjectLibrary\CPF\Operations\MapsChartsEtc\montbay_colorshd.tif');
    % [mbay, R] = readgeoraster('/Volumes/CPF/Operations/MapsChartsEtc/montbay_colorshd.tif');
    
    mapshow(mbay,R);
    xLimits = xlim;
    yLimits = ylim;
    
    hold on
    % plot(fixTable.easting, fixTable.northing, 'r-+')
    % plot(fixTable.easting(end), fixTable.northing(end), 'ro');
    X = fixTable.easting(tg); % ONLY GOOD FIXES
    Y = fixTable.northing(tg);
    
    plot(X, Y, 'r-+')
    plot(X(end), Y(end), 'ro');
    

    
    for i=2:length(X(tg))
        if tg(i) == 0 % skip bad, missing non profile fixes
            continue
        end
        GoodFixTable.range(i) = sqrt( (GoodFixTable.easting(i) - GoodFixTable.easting(i-1))^2 + (GoodFixTable.northing(i) - GoodFixTable.northing(i-1))^2 );
        angle  = atan2d((GoodFixTable.northing(i) - GoodFixTable.northing(i-1)), (GoodFixTable.easting(i) - GoodFixTable.easting(i-1)));
        GoodFixTable.heading(i) = mod(90 - angle, 360);
        GoodFixTable.speed(i) = GoodFixTable.range(i) / ( (GoodFixTable.timestampNum(i) - GoodFixTable.timestampNum(i-1)) * 24.0);
        GoodFixTable.predictedEasting(i) = GoodFixTable.easting(i) + (GoodFixTable.range(i) * cosd(angle));
        GoodFixTable.predictedNorthing(i) = GoodFixTable.northing(i) + (GoodFixTable.range(i) * sind(angle));
        [GoodFixTable.predictedLat(i), GoodFixTable.predictedLon(i)] = minvtran(utm.struct, GoodFixTable.predictedEasting(i), GoodFixTable.predictedNorthing(i));
    end
    
  
    
    plot(GoodFixTable.predictedEasting(2:end), GoodFixTable.predictedNorthing(2:end), 'gX')
    RSB = sprintf('\nLast fix to this fix range: %4.1f m  speed: %4.0f m/hour  compass heading: %3.1f deg', GoodFixTable.range(end), GoodFixTable.speed(end), GoodFixTable.heading(end));
    title(RSB)
    fprintf(1, '%s\n', RSB);
    
    text(GoodFixTable.predictedEasting(end)+0.01, GoodFixTable.predictedNorthing(end)+0.01, ['(',latDeg,' ', latMin,', ',lonDeg,' ', lonMin,')'])
    
    
    % Define MissionID to save plots
    MISSIONID=char(datetime(datevec(nanmin(GoodFixTable.timestampNum)),'format','yyyyMMdd')); % MC
    
    % Save figure
    width=40; height=40; ftsize=22;
    print_setup(width,height,ftsize)
    print([path_plots,'Map_CPFtrack_',MISSIONID,'.jpg'],'-djpeg');
    print([path_plots,'Map_CPFtrack_',MISSIONID,'.fig']);
    print([webFolder,'Map_CPFtrack.jpg'],'-djpeg'); % YT
    
    % % Write KML file for Google Earth
    kmlfile=['CPFTrack_',MISSIONID,'.kml'];
    writeKMLTrack(GoodFixTable, sbdFolder, kmlfile);
end

%%  Printing More Plots
close all

% Define acceptable ranges for CanP, CanH and BBVolts cutoff

battV_threshold=20; % battery threshold cutoff

rangeH(1,:)=[24.742 29.052];
rangeP(1,:)=[1189.38 1856.42]; % 2021-10-19T16-3-9/

rangeH(2,:)=[31.848 39.016];
rangeP(2,:)=[1.2346 1.3029]*1.0e+03; % mission='/ParagonTests/MICRORIDER/2021-11-16T19-16-49'; % OVERNIGHT mission, 19 profiles

rangeH(3,:)=[36.683 40.429];
rangeP(3,:)=[1166.59 1302.12]; % 2022-2-23T16-59-6/

% NOTE: thresholds taken from previous deployment (.eng files)

%% Plot Battery Voltage vs Time

figure(3)
plot([fixTable.timestampNum], fixTable.battV,'-o');
datetick('x');
ylabel('[Volts]')
title([MISSIONID,' Battery Voltage vs. Time']);
ylim([23 34])

hold on
plot([nanmin(fixTable.timestampNum) nanmax(fixTable.timestampNum)], [battV_threshold battV_threshold],'--r');

% Save figure 
width=60; height=30; ftsize=24;
print_setup(width,height,ftsize)
print([path_plots,'BatteryVoltage_CPFtrack_',MISSIONID,'.jpg'],'-djpeg'); % MC
print([webFolder,'BatteryVoltage_CPFtrack.jpg'],'-djpeg'); % YT

%% Plot Can Pressure vs Time
figure(4)
plot([fixTable.timestampNum], fixTable.canP,'-o');
datetick('x');
ylabel('[mbar]')
title([MISSIONID,' Can Pressure vs. Time']);

hold on
plot([nanmin(fixTable.timestampNum) nanmax(fixTable.timestampNum)], [nanmin(rangeP(:)) nanmin(rangeP(:))],'--r');
plot([nanmin(fixTable.timestampNum) nanmax(fixTable.timestampNum)], [nanmax(rangeP(:)) nanmax(rangeP(:))],'--r');

% Save figure
print_setup(width,height,ftsize)
print([path_plots,'CanPressure_CPFtrack_',MISSIONID,'.jpg'],'-djpeg'); % MC
print([webFolder,'CanPressure_CPFtrack.jpg'],'-djpeg'); % YT

%% Plot Can Humidity vs Time

figure(5)
plot([fixTable.timestampNum], fixTable.canHum,'-o');
datetick('x');
ylabel('[%]')
title([MISSIONID,' Can Humidity vs. Time']);

hold on
plot([nanmin(fixTable.timestampNum) nanmax(fixTable.timestampNum)], [nanmin(rangeH(:)) nanmin(rangeH(:))],'--r');
plot([nanmin(fixTable.timestampNum) nanmax(fixTable.timestampNum)], [nanmax(rangeH(:)) nanmax(rangeH(:))],'--r');

% Save figure
print_setup(width,height,ftsize)
print([path_plots,'CanHumidity_CPFtrack_',MISSIONID,'.jpg'],'-djpeg'); % MC
print([webFolder,'CanHumidity_CPFtrack.jpg'],'-djpeg'); % YT

