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

if ~nargin
    help plot_sampdist_bars
    return
end

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

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

if ~isfield(rfunc,'min')    || ~isfield(rfunc,'quart1') || ...
   ~isfield(rfunc,'median') || ~isfield(rfunc,'quart3') || ...
   ~isfield(rfunc,'max')
    for i=1:length(rfunc)
        rfunc(i).min   =min    (rfunc(i).sample);
        rfunc(i).quart1=prctile(rfunc(i).sample,25);
        rfunc(i).median=median (rfunc(i).sample);
        rfunc(i).quart3=prctile(rfunc(i).sample,75);
        rfunc(i).max   =max    (rfunc(i).sample);
    end
end

for i=1:length(rfunc)
    desc(i)=cellstr(rfunc(i).descriptor);
    data(i,1)=rfunc(i).min;
    data(i,2)=rfunc(i).quart1-rfunc(i).min;
    data(i,3)=rfunc(i).median-rfunc(i).quart1;
    data(i,4)=rfunc(i).quart3-rfunc(i).median;
    data(i,5)=rfunc(i).max   -rfunc(i).quart3;
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('Sample Distributions of Design Variables and/or Response Functions')
xlabel('Design Variable or Response Function')
ylabel('Value')

if ~exist('lstr','var') || isempty(lstr)
    lstr={'minimum' 'quartile 1' 'median' 'quartile 3' 'maximum'};
end

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

end
