% histPlot
% 
% Sections copied from Stuart's plotHist in piPro.
% Vivek Nadkarni
% Trimble
% July 13, 2004
% 

function [handle] = histPlot(subplotVec, bins, histVec, xlimits, name, ...
  mu, sig, epochs, histMax)

% Convert to percentages
histVec = histVec*100; 
histMax = histMax*100; 
% Round up to closest 10 percent
yMax = 10*ceil(histMax/10);
yTickMarks = [0 yMax/2 yMax];

if (length(subplotVec) == 3)
  handle = subplot(subplotVec(1), subplotVec(2), subplotVec(3));
else
  % The handle is encoded in the fourth element of subplotVec
  % This is a kludge to get around the fact that suptitle 
  % doesn't operate properly on nonstandard axes. 
  handle = subplot(subplotVec(4));
end
bar(bins,histVec);
hold on;
xlim(xlimits);
titlestr = ...
  sprintf('%s: \\mu=%.3f \\sigma=%.3f N=%d', ...
  name, mu, sig, epochs);
title(titlestr);
grid on; 

%
% Compute the integral across the bin.
% 
% All bin sizes should be the same
binSize = bins(2) - bins(1);
y =   LocalNormCDF(bins+binSize/2,mu,sig) ...
    - LocalNormCDF(bins-binSize/2,mu,sig);

y = y*100; % convert to percentage kludge
% Plots density line over histogram.
[AX,H1,H2] = plotyy(bins,y,bins,cumsum(histVec)); 

set(AX(1),'YLim', [0 yMax]);
set(AX(1), 'YTick', yTickMarks);
set(AX(1), 'YTickLabel', yTickMarks);
set(AX(1), 'XLim', xlimits); 

set(AX(2),'YLim', [0 100]);
set(AX(2), 'XLim', xlimits); 

if (subplotVec(3) == 3)
  % left hand side plots
  set(get(AX(1),'Ylabel'),'String','Distribution [%]');
end

if (subplotVec(3) == 4)
  % right hand side plots
  set(get(AX(2),'Ylabel'),'String','Cumulative Distribution [%]');
end

if (subplotVec(3) <= 4)
  set(handle, 'XTickLabel', []); 
  set(AX(1), 'XTickLabel', []); 
  set(AX(2), 'XTickLabel', []); 
end

set(H1,'color','r');
set(H1,'LineWidth',2);
set(H2,'color','g');
set(H2,'LineWidth',2);

return;
%
% ------------ Local Functions ---------
%

function dist = LocalNormCDF(x, mu, sig)
  % Normal Cumulative Distribution Function
  dist = (1 + (erf((x-mu)/(sig*sqrt(2)))))./2;
return;
