%
%  plot a stacked bar chart of the probabilities.
%
%  []=plot_prob_bars(rfunc,lstr)
%
function []=plot_prob_bars(rfunc,lstr)

if ~nargin
    help plot_prob_bars
    return
end

%%  assemble the data into a matrix and calculate the increments

desc=cell (1,length(rfunc));
for i=1:length(rfunc)
    ldata(i)=size(rfunc(i).cdf,1);
end
data=zeros(length(rfunc),max(ldata));

for i=1:length(rfunc)
    desc(i)=cellstr(rfunc(i).descriptor);
    if ~isempty(rfunc(i).cdf)
    data(i,1)=rfunc(i).cdf(1,2);
        for j=2:size(rfunc(i).cdf,1)
            if (rfunc(i).cdf(j,2) > rfunc(i).cdf(j-1,2))
                data(i,j)=rfunc(i).cdf(j,2)-rfunc(i).cdf(j-1,2);
            end
        end
    end
end

%  convert to percentage

data=data*100.;

%%  draw the stacked bar plot

%  if there's only one row, Matlab 7.5 interprets it as a column,
%  so add an extra row, then reduce xlim

if length(rfunc) == 1
    data=[data; data];
end

hl1=bar(data,'stacked');
% set(hl1(1),'FaceColor','green')
% set(hl1(2),'FaceColor','blue')
% set(hl1(3),'FaceColor','yellow')
% set(hl1(4),'FaceColor','cyan')
% set(hl1(5),'FaceColor','magenta')
% set(hl1(6),'FaceColor','red')

ax1=gca;
set(ax1,'ylim',[0 120])
if length(rfunc) == 1
    set(ax1,'xlim',[0.5 1.5])
end
set(ax1,'xticklabel',desc)

%  add the annotation

title('Probabilities for Specified Response Levels')
xlabel('Response Function')
ylabel('Percent Below Level')

if ~exist('lstr','var') || isempty(lstr)
    lstr=cell(1,max(ldata));
    for i=1:max(ldata)
        lstr(i)=cellstr(sprintf('%g',...
            rfunc(find(ldata == max(ldata),1,'first')).cdf(i,1)));
    end
    if ~isempty(find(ldata < max(ldata)))
        warning('Variable number of levels for response functions.');
    end
end

hleg1=legend(ax1,lstr,'Location','EastOutside',...
             'Orientation','vertical','Interpreter','none');

end
