%
%  plot a stacked bar chart of the importance factors.
%
%  []=plot_if_bars(rfunc,ifmin,isort)
%
function []=plot_if_bars(rfunc,ifmin,isort)

if ~nargin
    help plot_if_bars
    return
end

if ~exist('ifmin','var') || isempty(ifmin)
    ifmin=0;
end

if ~exist('isort','var') || isempty(isort)
    isort=0;
end

%%  assemble the data into a matrix

desc=cell (1,length(rfunc));
for i=1:length(rfunc)
    ldata(i)=length(rfunc(i).impfac);
end
data=zeros(length(rfunc),max(ldata));
dvar=rfunc(find(ldata == max(ldata),1,'first')).desvar;

for i=1:length(rfunc)
    desc(i)=cellstr(rfunc(i).descriptor);
    data(i,1:ldata(i))=rfunc(i).impfac;
end

%%  sort the data, if necessary

if (isort)
    ipmax=max(data,[],1);
    if (isort > 0)
        [ipmax,index]=sort(ipmax,'descend');
    else
        [ipmax,index]=sort(ipmax,'ascend' );
    end
    clear ipmax
    
    dvar=dvar(index);
    data=data(:,index);
end

%%  filter the data, if necessary

if (ifmin > 0)
    nif=length(dvar);
    dvar(nif+1,1)=cellstr(sprintf('others < %f',ifmin));
    data(:,nif+1)=0.;
    
    nif2=0;
    dvar2=cell (size(dvar));
    data2=zeros(size(data));
    
%  sum filtered rows and copy unfiltered rows

    for i=1:nif
        if (max(data(:,i)) < ifmin)
            data(:,nif+1)=data(:,nif+1)+data(:,i);
        else
            nif2=nif2+1;
            dvar2(nif2)  =dvar(i);
            data2(:,nif2)=data(:,i);
        end
    end
    
%  copy sums

    dvar2(nif2+1)  =dvar(nif+1);
    data2(:,nif2+1)=data(:,nif+1);
    
%  copy back and truncate filtered rows

    clear dvar data
    if (isort >= 0)
        dvar(1:nif2+1)  =dvar2(1:nif2+1);
        data(:,1:nif2+1)=data2(:,1:nif2+1);
    else
        dvar(1       )  =dvar2(  nif2+1);
        dvar(2:nif2+1)  =dvar2(1:nif2  );
        data(:,1       )=data2(:,  nif2+1);
        data(:,2:nif2+1)=data2(:,1:nif2  );
    end
    clear nif nif2 dvar2 data2
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');

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

%  add the annotation

title('Importance Factors')
xlabel('Response Function')
ylabel('Importance Factor Value')

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

end
