%% Generate position/velocity plots

function plotPVFig ( pvErr, meanErr, stdErr, statsScaleLabel, errTitle, ...
                     errYlabel, plotName, segments, ctrl, abscissa, ...
                     verticalView, autoScale, yMax )
if verticalView
  viewStr = 'Vertical View';
else
  viewStr = 'Standard View';
end

if autoScale
  viewStr = ['AutoScaled ' viewStr];
  errTitle = ['AutoScaled ' errTitle];
  plotName = ['Auto' plotName];
else
  yLimits = [-yMax, yMax];
end

disp(['Plotting ' errTitle ' data in ' viewStr]);

LAT = 1;
LON = 2; 
HGT = 3; 

% Expand segments
segList = segments.segList; 
segColor = segments.segColor;
colorKey = segments.colorKey; 

%% Position Error Figure
figHandle = newfigure('Visible',ctrl.plotsVisible); 

titleStrings = {'Latitude', 'Longitude', 'Height'};
for idx = 1:3
  
  if (verticalView)
    subplot(3,1,idx);
  else
    subplot(2,2,idx);
  end
  
  for segIdx = 1:length(segList)
    plot(abscissa.time(segList{segIdx}), pvErr(segList{segIdx},idx), ...
          [segColor{segIdx} '.']);
    if ( segIdx == 1 ) hold on; end;
  end
  
  titleStr = sprintf( '%s mu=%.3f%s sigma=%.3f%s', titleStrings{idx}, ...
                      meanErr(idx), statsScaleLabel, stdErr(idx), ...
                      statsScaleLabel );
  title (texlabel(titleStr));
  xlabel(abscissa.timeString);
  xlim(abscissa.limits);
  if (~autoScale)
    ylim(yLimits);
  end
  ylabel (errYlabel);
  grid on; 
end

if ( verticalView )
  suptitle ([errTitle ' Errors: ' colorKey ]);
  printPngPlot ( ['Vert1D' plotName], ctrl.printPlots, verticalView );
  if ~ctrl.viewPlots
    close; 
  end
  figHandle = newfigure('Visible',ctrl.plotsVisible); 
else
  subplot(2,2,4);
end

for segIdx = 1:length(segList)
  plot( pvErr(segList{segIdx},LAT), pvErr(segList{segIdx},LON), ...
       [segColor{segIdx} '.']);
  if ( segIdx == 1 ) hold on; end;
end

xlabel(['Latitude ' errYlabel]);
ylabel(['Longitude ' errYlabel]);
title(['Lat,Lon ' errTitle ' Errors']);
axis equal;
if (~autoScale)
  xlim(yLimits);
  ylim(yLimits);
end
grid on;
suptitle ([errTitle ' Errors: ' colorKey ]);

if ( verticalView )
  printPngPlot ( ['Vert2D' plotName], ctrl.printPlots );
else
  printPngPlot ( plotName, ctrl.printPlots );
end

if ~ctrl.viewPlots
  close; 
end


end