%
%  plot a stacked bar chart of the response levels.
%
%  []=plot_rlev_bars(rfunc,lstr)
%
function []=plot_rlev_bars(rfunc,lstr)

if ~nargin
    help plot_rlev_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,1);
        for j=2:size(rfunc(i).cdf,1)
            if (rfunc(i).cdf(j,1) > rfunc(i).cdf(j-1,1))
                data(i,j)=rfunc(i).cdf(j,1)-rfunc(i).cdf(j-1,1);
            end
        end
    end
end

%%  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 barseries properties for lowest value
whitebg('white')
set(hl1(1),'FaceColor','white')
set(hl1(1),'Visible','off')

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

%  add the annotation

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

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

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

end
