%
%  plot a stacked bar chart of the sample distributions.
%
%  []=plot_normdist_bars(rfunc,plev)
%
function []=plot_normdist_bars(rfunc,plev)

if ~nargin
    help plot_normdist_bars
    return
end

if ~exist('plev','var') || isempty(plev)
    plev=[0.01 0.25 0.50 0.75 0.99];
end

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

desc=cell (1,length(rfunc));
data=zeros(length(rfunc),5);

if ~isfield(rfunc,'mean') || ~isfield(rfunc,'stddev')
    for i=1:length(rfunc)
        [rfunc(i).mean,rfunc(i).stddev,...
            rfunc(i).meanci,rfunc(i).stddevci]=...
            normfit(rfunc(i).sample,0.05);
    end
end

for i=1:length(rfunc)
    desc(i)=cellstr(rfunc(i).descriptor);
    data(i,:)=norminv(plev,rfunc(i).mean,rfunc(i).stddev);
end

for j=length(plev):-1:2
    data(:,j)=data(:,j)-data(:,j-1);
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,'xtick',1:1:max(length(rfunc),2));
set(ax1,'xticklabel',desc)

%  add the annotation

title('Normal Distributions of Design Variables and/or Response Functions')
xlabel('Design Variable or Response Function')
ylabel('Value')

if ~exist('lstr','var') || isempty(lstr)
    lstr=cell(1,length(plev));
    for i=1:length(plev)
        lstr(i)=cellstr(sprintf('%g%%',100*plev(i)));
    end
end

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

end
