% 
% plotPVHist.m
% 
% Function to plot position error histogram. 

function plotPVHist ( pvErr, errTitle, errXlabel, segments, ctrl, ...
                      doPlot, plotName, autoScale, xMax )


if autoScale
  plotName = ['Auto' plotName];
  histBins = 5; 
  errTitle = ['AutoScaled ' errTitle];
else
  histBins = -xMax:xMax/2:xMax;
end

if ~( doPlot && ctrl.plotHist )
  disp(['Skip ' errTitle ' Histogram']);
  return; 
else
  disp(['Plot ' errTitle ' Histogram']);  
end



figHandle = newfigure('Visible', ctrl.plotsVisible); 

%  Try to create a histogram with segments
nCol = 0; 
for segIdx = 1:length(segments.segList)
  vecLen(segIdx) = length( pvErr(segments.segList{segIdx}, 1) );
  if ( vecLen(segIdx) > 0 )
    nCol = nCol + 1; 
  end
end
maxLen = max(vecLen);
segMatrix = NaN(maxLen, nCol);

titleStrings = {'Latitude', 'Longitude', 'Height'};

for idx = 1:3

  colIdx = 0; 
  for segIdx = 1:length(segments.segList)
    if vecLen(segIdx)>0
      colIdx = colIdx+1;
      colorLUT(colIdx) = segments.segColor{segIdx}; 
      segMatrix(1:vecLen(segIdx), colIdx) = pvErr(segments.segList{segIdx}, idx);
    end
  end
  
  subplot(1,3,idx);
  [binCounts, binCenters] = hist( segMatrix, histBins ); 
  barHandle = bar(binCenters, log10(binCounts), 1);
  for hIdx = 1:colIdx
    set( barHandle(hIdx), 'FaceColor', colorLUT(hIdx) );
  end
  
  axis square;
  title(titleStrings{idx});
  xlabel(errXlabel);
  ylabel('log_1_0(count)');
end
suptitle([errTitle ' Error Histograms']);

if ( ctrl.printPlots )
  paperPosition = get ( gcf, 'PaperPosition' );
  paperPosition(4) = paperPosition(4)/2;
  set(gcf, 'PaperPosition', paperPosition);
  printPngPlot( plotName, ctrl.printPlots );
end

if ~ctrl.viewPlots
  close;
end

end
