function stepwise(X,y,inmodel,alpha);
%STEPWISE Interactive tool for stepwise regression.
%   STEPWISE(X,Y,INMODEL,ALPHA) fits a regression model of Y on the
%   columns of X specified in the vector INMODEL. ALPHA is the significance 
%   for testing each term in the model. By default, 
%   ALPHA = 1 - (1 - 0.025).^(1/p) where p is the number of columns in X.
%   This translates to plotted 95% simultaneous confidence intervals
%   (Bonferroni) for all the coefficients.
%
%   The least squares coefficient is plotted with a green filled circle.
%   A coefficient is not significantly different from zero if its confidence
%   interval crosses the white zero line. Significant model terms are plotted
%   using solid lines. Terms not significantly different from zero are plotted 
%   with dotted lines.
%
%   Click on the confidence interval lines to toggle the state of the model
%   coefficients. If the confidence interval line is green the term is in the model.
%   If the the confidence interval line is red the term is not in the model.
%   Use the pop-up menu, Export, to move variables to the base workspace.
%
%   Reference: Draper, Norman and Smith, Harry, Applied Regression Analysis,
%   Second Edition, John Wiley & Sons, Inc. 1981 pp. 307-312.

%   B. Jones 6-14-94
%   Copyright(c) 1994-96 by The MathWorks, Inc.
%   $Revision: 2.4 $  $Date: 1996/03/20 17:11:11 $

if ~isstr(X) 
    action = 'start';
else
    action = X;
end

%On recursive calls get all necessary handles and data.
if ~strcmp(action,'start')
   flag = y;
   step_fig = inmodel;
   data_fig = alpha(1);
   hist_fig = alpha(2);

   ch = get(0,'Children');
   good = find(ch == data_fig);
   if isempty(good)
      if ~isempty(step_fig),close(step_fig);end
      if ~isempty(hist_fig),close(hist_fig);end
      warndlg('Sorry, STEPWISE requires all three figure windows to run.');
      return
   end

   good = find(ch == step_fig);
   if isempty(good)
      if ~isempty(data_fig),close(data_fig);end
      if ~isempty(hist_fig),close(hist_fig);end
      warndlg('Sorry, STEPWISE requires all three figure windows to run.');
      return
   end

   good = find(ch == hist_fig);
   if isempty(good)
      if ~isempty(data_fig),close(data_fig);end
      if ~isempty(step_fig),close(step_fig);end
      warndlg('Sorry, STEPWISE requires all three figure windows to run.');
      return
   end
   hist_ax = get(hist_fig,'UserData');
      
   u = get(step_fig,'Userdata');

   handles     = get(u(1),'Userdata');
   X           = get(u(2),'Userdata');
   y           = get(u(3),'Userdata');
   inmodel     = get(u(4),'Userdata');
   crit        = get(u(5),'Userdata');
   outputpopup = u(6);
   scalebutton = u(7);
   scaledx     = get(u(8),'Userdata');
   step_axes   = u(9);
   [n,p]       = size(X);
   bhandle     = u(10:10+p-1);

end

if strcmp(action,'start')
[n, p]=size(X);
colheads = str2mat('Column #','Parameter','Lower ','Upper');
colheads1 = str2mat('RMSE','R-square','F','P');

screen = get(0,'ScreenSize');
ht = screen(4);
w  = screen(3);
fight = (p+2)*14 + 65;
data_fig = figure('Visible','off');

hist_fig = figure('Visible','off');

% Set Up for Stepwise Plot Figure
instance = length(findobj(0,'Tag','stepfig'))+1;
drawnow;
step_fig = figure('Visible','off');
stepht = min(0.1*(p+1),0.8);
set(step_fig,'Units','Normalized','Color','k','Tag','stepfig',...
   'Position',[0.01 0.98-stepht-0.05*instance 0.4 stepht],'Resize','off',...
   'Name',['Stepwise Regression Plot #',int2str(instance)]);

bcolor = [0.5 0.5 0.5];
parens = ['[],',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
gray_axes = axes;
set(gray_axes,'XTick',[],'YTick',[],'Units','Normalized','Position',[0 0 1 1],...
    'Color',bcolor,'UserData',data_fig,'Tag','gray',...
    'ButtonDownFcn',['stepwise(''stray_click'',',parens]);

set(step_fig,'Units','Pixels');
figpos  = get(step_fig,'Position');
axisp   = [80 70 figpos(3)-100 figpos(4)-90];
step_axes = axes;
set(step_axes,'NextPlot','add','DrawMode','fast','Units','Pixels',...
    'Position',axisp,'Tag','stepaxes','Color','k','Box','on',...
   'Ydir','reverse');
set(step_fig,'Units','Normalized')
if nargin == 4
  sigprob = 1 - alpha/2;
else
  sigprob = (0.975).^(1/p);
end

mx = mean(X);
X = (X - mx(ones(n,1),:));
y = y - mean(y);
colidx = 1:p;

sx = std(X);
scaledx = X./sx(ones(n,1),:);


df = n-2:-1:n-p-1;
crit = tinv(sigprob,df);

if nargin < 3
  inmodel = colidx;
end

notin  = colidx;
notin(inmodel) = [];

if ~isempty(inmodel)
   [Q,R]=qr(X(:,inmodel),0);
   b = R\(Q'*y);
   r = y - X(:,inmodel)*b;
   RI = R\eye(size(R));
   xtxid = (sum(RI'.*RI'))';
else
   r = y;
end
terms = length(inmodel);
mse = r'*r./(n-terms-1);
rmse = sqrt(mse);
tss = y'*y;
rss = y'*y-r'*r;
if terms == 0
   prob = 1;
   r2   = 0;
   f    = 0;
else
   f   = (rss./terms)./mse;
   prob = 1-fcdf(f,terms,(n-terms-1));
   r2  = rss./tss;
   seb = sqrt(xtxid)*rmse;
   t = b./seb;
end

beta = zeros(p,1);
beta(inmodel) = b;

delta = zeros(p,1);
if ~isempty(inmodel)
   delta(inmodel) = seb*crit(terms);
end

tstats = zeros(p,1);
tstats(inmodel) = t;

for index = notin
   Xnew = [X(:,inmodel) X(:,index)];
   [Qadd, Radd] = qr(Xnew,0);
   bnew = Radd\(Qadd'*y);
   rnew = y - Xnew*bnew;
   RInew = Radd\eye(terms+1,terms+1);
   xtxidnew = (sum(RInew'.*RInew'))';
   rmse1 = sqrt(sum(rnew.*rnew)./(n-terms-2));
   seb = sqrt(xtxidnew(terms+1))*rmse1;

   beta(index) = bnew(terms+1);
   tstats(index) = bnew(terms+1)./seb;
   delta(index) = seb*crit(terms+1);
end
xmax = -Inf;
xmin = Inf;
handles = plot([(beta-delta)'; (beta+delta)'],[colidx; colidx]);
for k = 1:length(colidx),
   bhandle(k,1) = plot(beta(k),colidx(k),'.');
   parens = [int2str(k),',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
   set(bhandle(k,1),'ButtonDownFcn',['stepwise(''click'',',parens],'MarkerSize',20)
   set(handles(k),'ButtonDownFcn',['stepwise(''click'',',parens],'LineWidth',2)
   xmax = max(beta(k)+delta(k),xmax);
   xmin = min(beta(k)-delta(k),xmin);
end
xrange = xmax-xmin;
set(gca,'XLim',[xmin-0.05*xrange xmax+0.05*xrange]);

ytext=uicontrol('Style','text','Position',[0.01 0.55 0.13 0.05],...
        'Units','normalized','BackgroundColor',bcolor,...
        'ForegroundColor','white','String',' Term # ');

notsig = find(beta-delta<0 & beta+delta>0);
sig = 1:p;
sig(notsig) = [];
set(handles(inmodel),'Color','g');
set(bhandle(inmodel),'Color','g');

set(handles(notin),'Color','r');
set(bhandle(notin),'Color','r');

set(handles(sig),'LineStyle','-');
set(handles(notsig),'LineStyle',':');

set(gca,'Ylim',[0.5 p+0.5],'Ytick',(1:p),'Position',axisp);

parens = ['[],',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
outputpopup = uicontrol(step_fig,'Style','Popup','String',...
        'Export|Parameters|Confidence Intervals|Terms In|Terms Out|All','Value',1,...
        'Units','Pixels','Position',[245 10 150 20],...
        'CallBack',['stepwise(''output'',',parens]);

scalebutton = uicontrol(step_fig,'Style','radio','String',...
        'Scale Inputs','Units','Pixels',...
        'Position',[95 10 125 20],...
        'CallBack',['stepwise(''scale'',',parens]);

close_button = uicontrol('Style','Pushbutton','Units','Pixels',...
               'Position',[10 10 60 20],'Callback',['stepwise(''close'',',parens],...
            'String','Close','Tag','sclose');

hstore     = uicontrol('Style','text','Visible','off','UserData',handles);
xstore     = uicontrol('Style','text','Visible','off','UserData',X,'Tag','xstore');
ystore     = uicontrol('Style','text','Visible','off','UserData',y,'Tag','ystore');
instore    = uicontrol('Style','text','Visible','off','UserData',inmodel,'Tag','in');
critstore  = uicontrol('Style','text','Visible','off','UserData',crit);
sxstore    = uicontrol('Style','text','Visible','off','UserData',scaledx);

u = [hstore; xstore; ystore; instore; critstore; ...
     outputpopup; scalebutton; sxstore; step_axes; bhandle];
yref = get(gca,'YLim');    
h = plot([0 0],yref,'w-');

% Set Up for Stepwise Parameter Data Table.
set(0,'CurrentFigure',data_fig);
%set(data_fig,'Visible','off');
set(data_fig,'Units','Pixels',...
   'Position',[450+30*instance ht-(fight+30*instance) 340 fight]);

set(data_fig,'Color','k','Name',['Stepwise Table #',int2str(instance)],...
    'NextPlot','new','Tag','datafig','Resize','off');
ax = axes;
set(ax,'Units','Pixels','Position',[10 45 380 fight-45],'Color','k',...
    'Xlim',[0 380],'Ylim',[0 fight],'Visible','off');

h=text(180,fight-12,'Confidence Intervals');
set(h,'FontName','Geneva','FontSize',9,'Color','w');
z = [10 80 175 245];
z1 = [10 80 195 265];
h = zeros(4,1);
l = zeros(4,1);
for k = 1:4
  h(k)=text(z(k),fight-26,colheads(k,:));
  set(h(k),'FontName','Geneva','FontSize',9,'Color','w');
  l(k)=text(z1(k),15,colheads1(k,:));
  set(l(k),'FontName','Geneva','FontSize',9,'Color','w');
end

x = fight-35;
h = zeros(4,p+1);
for params = 1:p
    z = [30 120 200 270];
    x = x - 16;
   row = [params beta(params) beta(params)-delta(params) beta(params)+delta(params)];
    parens = [int2str(params),',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
    bdf = ['stepwise(''click'',',parens];
   for k = 1:4
       if k == 1,
          h(k,params) = text(z(k),x,sprintf('%4i',row(k)));
          set(h(k,params),'HorizontalAlignment','right',...
             'FontName','Geneva','FontSize',9,'Tag','text',...
             'ButtonDownFcn',bdf);
       else
          h(k,params) = text(z(k),x,sprintf('%11.4g',row(k)));
          set(h(k,params),'HorizontalAlignment','right','Tag','text',...
             'FontName','Geneva','FontSize',9,'ButtonDownFcn',bdf);
       end
       if any(inmodel == params)
         set(h(k,params),'Color','g');
       else
         set(h(k,params),'Color','r');
       end
   end
   row = [rmse r2 f prob];
   z = [35 120 205 290];
   for k = 1:4
       h(k,p+1) = text(z(k),-5,sprintf('%11.4g',row(k)));
       set(h(k,p+1),'HorizontalAlignment','right','Tag','text',...
         'FontName','Geneva','FontSize',9,'Color','w');
   end
end
parens = ['[],',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
close_button1 = uicontrol('Style','Pushbutton','Units','Pixels',...
               'Position',[10 5 100 20],'Callback',['stepwise(''close'',',parens],...
               'String','Close','Tag','dclose');

help_button = uicontrol('Style','Pushbutton','Position',[230 5 100 20],...
            'Units','Pixels','Callback','hthelp(''stephelp.html'')',...
            'String','Help');

% Set Up for History Figure
set(0,'CurrentFigure',hist_fig);
hist_ax = axes;
parens = ['[]',',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];

set(hist_fig,'WindowButtonMotionFcn',['stepwise(''histmotion'',',parens],...
     'Units','Normalized','Position',[0.05+0.05*instance 0.2-0.05*instance 0.4 0.3]);
set(hist_fig,'Color','k','Tag','histfig','Name',['Stepwise History #',int2str(instance)]);

trm  = n-1:-1:n-p-1;
trml = length(trm);
low  = 0.025;
hi   = 0.975;

chi2crit = chi2inv([low(ones(trml,1),1) hi(ones(trml,1),1)],[trm' trm']);
critstore  = uicontrol('Style','text','Visible','off','UserData',chi2crit,'Tag','chi2');

rmseci  =  sqrt([(mse*sqrt((n-terms-1)./chi2crit(terms+1,2))) (mse*sqrt((n-terms-1)./chi2crit(terms+1,1)))]);
cirange = diff(rmseci);
ylhi = rmseci(2) + 0.1*cirange;
yllo = rmseci(1) - 0.1*cirange;
tmp = NaN;
tmp = tmp(ones(p,1),1);
tmp(1:length(inmodel)) = inmodel;
rmsehandle = plot([1 1],rmseci);
parens = [int2str(1),',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
bdf = ['stepwise(''history'',',parens];
set(rmsehandle(1),'ButtonDownFcn',bdf);
handlestore  = uicontrol('Style','text','Visible','off','UserData',rmsehandle,'Tag','lineh');
instore  = uicontrol('Style','text','Visible','off','UserData',tmp,'Tag','in');

h = plot(1,rmse,'y.',[1 1],rmseci,'y-');
set(h,'MarkerSize',20);
xlabel('Model Number');
ylabel('RMSE');
set(hist_ax,'Xlim',[0.5 1.5],'Xtick',1,'Ylim',[yllo ylhi],'NextPlot','add');

parens = ['[]',',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
set(step_fig,'WindowButtonMotionFcn',['stepwise(''stepmotion'',',parens])
set(data_fig,'WindowButtonMotionFcn',['stepwise(''datamotion'',',parens])

set(hist_fig,'Userdata',hist_ax,'Visible','on');
set(data_fig,'Visible','on','UserData',step_fig);
set(step_fig,'Userdata',u,'Visible','on');
% End of initialization Phase

% Callback for motion inside the Coefficients Table figure.
elseif strcmp(action,'datamotion'),
     set(0,'CurrentFigure',data_fig);
      cursorstate = get(data_fig,'Pointer');
     ax = findobj(data_fig,'Type','axes');
      cp = get(ax,'CurrentPoint');
      cx = cp(1,1);
      cy = cp(1,2);
     pos = get(data_fig,'Position');
     if 80 < cx & 130 > cx & 45 < cy & pos(4)-30 > cy
         online = 1;
     else
        online = 0;
     end
      if online & strcmp(cursorstate,'arrow'),
         set(gcf,'Pointer','circle');
      elseif ~online & strcmp(cursorstate,'circle'),
         set(gcf,'Pointer','arrow');
      end

% Callback for motion inside the Stepwise Errorbar Graph figure.
elseif strcmp(action,'stepmotion'),
     set(0,'CurrentFigure',step_fig);
      cursorstate = get(step_fig,'Pointer');
      cp = get(step_axes,'CurrentPoint');
      cx = cp(1,1);
      cy = cp(1,2);
     u = get(step_fig,'Userdata');
     handles     = get(u(1),'Userdata');
     if cy > 0.9 & cy < length(handles)+0.1
        xint = get(handles(round(cy)),'XData');
     else 
        xint = zeros(1,2);
     end
     if abs(cy-round(cy)) < 0.1 & cx > xint(1) & cx < xint(2)
         online = 1;
     else
        online = 0;
     end
      if online & strcmp(cursorstate,'arrow'),
         set(gcf,'Pointer','circle');
      elseif ~online & strcmp(cursorstate,'circle'),
         set(gcf,'Pointer','arrow');
      end

% Callback for motion inside the Stepwise History figure.
elseif strcmp(action,'histmotion'),
     cursorstate = get(hist_fig,'Pointer');
     set(0,'CurrentFigure',hist_fig);
     cp = get(hist_ax,'CurrentPoint');
     cx = cp(1,1);
     if abs(cx-round(cx)) < 0.02 & round(cx) > 1
         online = 1;
     else
         online = 0;
     end
     if online & strcmp(cursorstate,'arrow'),
         set(gcf,'Pointer','circle');
     elseif ~online & strcmp(cursorstate,'circle'),
         set(gcf,'Pointer','arrow');
     end
   
% Callback for Export Button.
elseif strcmp(action,'output');
    bmf = get(step_fig,'WindowButtonMotionFcn');
    bdf = get(step_fig,'WindowButtonDownFcn');
    set(step_fig,'WindowButtonMotionFcn','');
    set(step_fig,'WindowButtonDownFcn','');

   if get(scalebutton,'Value') == 1
      X = scaledx;
   end

   colidx = 1:p;

   notin  = 1:p;
   notin(inmodel) = [];

   [Q,R]=qr(X(:,inmodel),0);
   b = R\Q'*y;
   r = y - X(:,inmodel)*b;
   RI = R\eye(size(R));
   xtxid = (sum(RI'.*RI'))';
   terms = length(inmodel);
   rmse = sqrt(sum(r.*r)./(n-terms-1));
   seb = sqrt(xtxid)*rmse;
   t = b./seb;

   beta = zeros(p,1);

   delta = zeros(p,1);
   if ~isempty(inmodel);
      delta(inmodel) = seb*crit(terms);
      beta(inmodel) = b;
      tstats(inmodel) = t;
   end

   tstats = zeros(p,1);

   for index = notin
      Xnew = [X(:,inmodel) X(:,index)];
      [Qadd, Radd] = qr(Xnew,0);
      bnew = Radd\Qadd'*y;
     rnew = y - Xnew*bnew;
      RInew = Radd\eye(terms+1,terms+1);
      xtxidnew = (sum(RInew'.*RInew'))';
      rmse1 = sqrt(sum(rnew.*rnew)./(n-terms-2));
      seb = sqrt(xtxidnew(terms+1))*rmse1;

      beta(index) = bnew(terms+1);
      tstats(index) = bnew(terms+1)./seb;
      delta(index) = seb*crit(terms+1);
   end

   cases = get(outputpopup,'Value');

   if cases == 2
      matqueue('put',beta);
      promptstr = 'Enter names for the parameters or use the supplied default.';
      entrystr = 'beta';
   elseif cases == 3
      matqueue('put',[beta-delta beta+delta]);
      promptstr = 'Enter names for the confidence intervals or use the supplied default.';
      entrystr = 'betaci';
   elseif cases == 4;
      matqueue('put',inmodel);
      promptstr = 'Enter names for the terms in the model or use the supplied default.';
      entrystr = 'in';
   elseif cases == 5
      matqueue('put',notin);
      promptstr = 'Enter names for the terms out of the model or use the supplied default.';
      entrystr = 'out';
   elseif cases == 6
      matqueue('put',beta);
      matqueue('put',[beta-delta beta+delta]);
      matqueue('put',inmodel);
      matqueue('put',notin);
      promptstr = 'Enter names for statistical outputs or use the defaults.';
      entrystr = 'beta,betaci,in,out';
    end
    if cases ~= 1
       matqdlg('buffer2ws','PromptString',promptstr,'EntryString',entrystr);
   end

   set(outputpopup,'Value',1);
   set(step_fig,'WindowButtonMotionFcn',bmf);
   set(step_fig,'WindowButtonDownFcn',bdf);

elseif strcmp(action,'click')
   cf = get(0,'CurrentFigure');
   set(0,'CurrentFigure',step_fig);
   toggle = any(inmodel == flag);
   if toggle == 0
      inmodel = sort([inmodel(:); flag]);
   else
      k = find(inmodel==flag);
      inmodel(k) = [];
   end

   if get(scalebutton,'Value') == 1
      X = scaledx;
   end
         
   colidx = 1:p;

   notin  = 1:p;
   notin(inmodel) = [];

   if ~isempty(inmodel)
      [Q,R]=qr(X(:,inmodel),0);
      b = R\Q'*y;
      r = y - X(:,inmodel)*b;
      RI = R\eye(size(R));
      xtxid = (sum(RI'.*RI'))';
   else
      r = y;
   end
   terms = length(inmodel);
   mse = r'*r./(n-terms-1);
   rmse = sqrt(mse);
   tss = y'*y;
   rss = y'*y-r'*r;
   if terms == 0
      prob = 1;
      r2   = 0;
      f    = 0;
   else
      f   = (rss./terms)./mse;
      prob = 1-fcdf(f,terms,(n-terms-1));
      r2  = rss./tss;
      seb = sqrt(xtxid)*rmse;
      t = b./seb;
   end

   beta = zeros(p,1);

   delta = zeros(p,1);
   if ~isempty(inmodel);
      delta(inmodel) = seb*crit(terms);
      beta(inmodel) = b;
      tstats(inmodel) = t;
   end

   tstats = zeros(p,1);

   for index = notin
      Xnew = [X(:,inmodel) X(:,index)];
      [Qadd, Radd] = qr(Xnew,0);
      bnew = Radd\Qadd'*y;
      rnew = y - Xnew*bnew;
      RInew = Radd\eye(terms+1,terms+1);
      xtxidnew = (sum(RInew'.*RInew'))';
      rmse1 = sqrt(sum(rnew.*rnew)./(n-terms-2));
      seb = sqrt(xtxidnew(terms+1))*rmse1;

      beta(index) = bnew(terms+1);
      tstats(index) = bnew(terms+1)./seb;
      delta(index) = seb*crit(terms+1);
   end
   xmax = -inf;
   xmin = inf;
   for k = 1:p
      set(handles(k),'XData',[beta(k)-delta(k); beta(k)+delta(k)]);
      set(bhandle(k),'XData',beta(k));
      xmax = max(beta(k)+delta(k),xmax);
      xmin = min(beta(k)-delta(k),xmin);
   end
   xrange = xmax-xmin;
   set(gca,'XLim',[xmin-0.05*xrange xmax+0.05*xrange]);

   notsig = find(beta-delta<0 & beta+delta>0);
   sig = 1:p;
   sig(notsig) = [];
   set(handles(inmodel),'Color','g');
   set(bhandle(inmodel),'Color','g');

   set(handles(notin),'Color','r');
   set(bhandle(notin),'Color','r');

   set(handles(sig),'LineStyle','-');
   set(handles(notsig),'LineStyle',':');
   set(u(4),'UserData',inmodel)

   if ~isempty(data_fig)
     set(0,'CurrentFigure',data_fig);
     ax = gca;
     ch = findobj(ax,'Tag','text');
     delete(ch);
     pos = get(data_fig,'Position');
     x = pos(4)-30;
     h = zeros(4,p);
     for params = 1:p
         z = [30 120 200 270];
         x = x - 16;
         row = [params beta(params) beta(params)-delta(params) beta(params)+delta(params)];
         parens = [int2str(params),',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
         bdf = ['stepwise(''click'',',parens];
         for k = 1:4
           if k == 1,
              h(k,params) = text(z(k),x,sprintf('%4i',row(k)));
              set(h(k,params),'HorizontalAlignment','right','Tag','text',...
                 'FontName','Geneva','FontSize',9);
           else
              h(k,params) = text(z(k),x,sprintf('%11.4g',row(k)));
              set(h(k,params),'HorizontalAlignment','right','ButtonDownFcn',bdf,...
                 'FontName','Geneva','FontSize',9,'Tag','text');
           end
           if any(inmodel == params)
              set(h(k,params),'Color','g');
           else
              set(h(k,params),'Color','r');
           end
         end
         row = [rmse r2 f prob];
         z = [35 120 205 290];
         for k = 1:4
            h(k,p+1) = text(z(k),-5,sprintf('%11.4g',row(k)));
            set(h(k,p+1),'HorizontalAlignment','right','Tag','text',...
               'FontName','Geneva','FontSize',9,'Color','w','ButtonDownFcn',bdf);
         end
      end
   end 
   
   set(0,'CurrentFigure',hist_fig);
   
   chi2crit = get(findobj(hist_fig,'Tag','chi2'),'Userdata');
   rmseci  =  sqrt([(mse*sqrt((n-terms-1)./chi2crit(terms+1,2)))
               (mse*sqrt((n-terms-1)./chi2crit(terms+1,1)))]);
   cirange = diff(rmseci);
   ylhi = rmseci(2) + 0.1*cirange;
   yllo = rmseci(1) - 0.1*cirange;
   
   tmp = NaN;
   tmp = tmp(ones(p,1),1);
   tmp(1:length(inmodel)) = inmodel;
   
   instore = findobj(hist_fig,'Tag','in');
   in = get(instore,'UserData');
   in = [in tmp];
   set(instore,'UserData',in);
   
   hstore = findobj(hist_fig,'Tag','lineh');
   rmsehandle = get(hstore,'Userdata');
   num_mod = length(rmsehandle)+1;   
   rmsehandle(num_mod) = plot([num_mod num_mod],rmseci);
   set(hstore,'UserData',rmsehandle);
   
   parens = [int2str(num_mod),',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
   bdf = ['stepwise(''history'',',parens];
   set(rmsehandle(num_mod),'ButtonDownFcn',bdf);
   yl = get(gca,'Ylim');
   yhi = max(ylhi,yl(2));
   ylo = min(yllo,yl(1));
   set(hist_ax,'Xlim',[0.5 num_mod+0.5],'Xtick',(1:num_mod),'Ylim',[ylo yhi]);
   h = plot(num_mod,rmse,'.');
   set(h,'MarkerSize',20,'ButtonDownFcn',bdf);
   set(0,'CurrentFigure',cf);   

% Callback for Scale Inputs radio button.
elseif strcmp(action,'scale'),
   set(0,'CurrentFigure',step_fig);
   if get(scalebutton,'Value') == 1
      X = scaledx;
   end

   colidx = 1:p;

   notin  = 1:p;
   notin(inmodel) = [];
      
   if ~isempty(inmodel)
      [Q,R]=qr(X(:,inmodel),0);
      b = R\Q'*y;
      r = y - X(:,inmodel)*b;
      RI = R\eye(size(R));
      xtxid = (sum(RI'.*RI'))';
   else
      r = y;
   end
   terms = length(inmodel);
   mse = r'*r./(n-terms-1);
   rmse = sqrt(mse);
   tss = y'*y;
   rss = y'*y-r'*r;
   if terms == 0
      prob = 1;
      r2   = 0;
      f    = 0;
   else
      f   = (rss./terms)./mse;
      prob = 1-fcdf(f,terms,(n-terms-1));
      r2  = rss./tss;
      seb = sqrt(xtxid)*rmse;
      t = b./seb;
   end

   beta = zeros(p,1);

   delta = zeros(p,1);
   if ~isempty(inmodel);
      delta(inmodel) = seb*crit(terms);
      beta(inmodel) = b;
      tstats(inmodel) = t;
   end

   tstats = zeros(p,1);

   for index = notin
      Xnew = [X(:,inmodel) X(:,index)];
      [Qadd, Radd] = qr(Xnew,0);
      bnew = Radd\Qadd'*y;
      rnew = y - Xnew*bnew;
      RInew = Radd\eye(terms+1,terms+1);
      xtxidnew = (sum(RInew'.*RInew'))';
      rmse1 = sqrt(sum(rnew.*rnew)./(n-terms-2));
      seb = sqrt(xtxidnew(terms+1))*rmse1;

      beta(index) = bnew(terms+1);
      tstats(index) = bnew(terms+1)./seb;
      delta(index) = seb*crit(terms+1);
   end
   
   xmax = -inf;
   xmin = inf;
   for k = 1:p
      set(handles(k),'XData',[beta(k)-delta(k); beta(k)+delta(k)]);
      set(bhandle(k),'XData',beta(k));
      xmax = max(beta(k)+delta(k),xmax);
      xmin = min(beta(k)-delta(k),xmin);
   end
   set(gca,'XLim',[xmin xmax]);


   notsig = find(beta-delta<0 & beta+delta>0);
   sig = 1:p;
   sig(notsig) = [];
   set(handles(inmodel),'Color','g');
   set(bhandle(inmodel),'Color','g');

   set(handles(notin),'Color','r');
   set(bhandle(notin),'Color','r');

   set(handles(sig),'LineStyle','-');
   set(handles(notsig),'LineStyle',':');
   set(u(4),'UserData',inmodel)

   set(0,'CurrentFigure',data_fig);
   ax = gca;
   ch = findobj(ax,'Tag','text');
   delete(ch);
   
   pos = get(data_fig,'Position');
   x = pos(4)-30;
   h = zeros(4,p);
   for params = 1:p
      z = [30 120 200 270];
      x = x - 16;
      parens = [int2str(params),',',int2str(step_fig),',[',int2str(data_fig),' ',int2str(hist_fig),'])'];
      bdf = ['stepwise(''click'',',parens];
      row = [params beta(params) beta(params)-delta(params) beta(params)+delta(params)];
      for k = 1:4
        if k == 1,
           h(k,params) = text(z(k),x,sprintf('%4i',row(k)));
          set(h(k,params),'HorizontalAlignment','right','Tag','text',...);
                'FontName','Geneva','FontSize',9,'ButtonDownFcn',bdf);
         else
           h(k,params) = text(z(k),x,sprintf('%11.4g',row(k)));
          set(h(k,params),'HorizontalAlignment','right','Tag','text',...
                'FontName','Geneva','FontSize',9,'ButtonDownFcn',bdf);
        end

         if any(inmodel == params)
           set(h(k,params),'Color','g');
        else
           set(h(k,params),'Color','r');
        end
      end
      row = [rmse r2 f prob];
      z = [35 120 205 290];
      for k = 1:4
        h(k,p+1) = text(z(k),-5,sprintf('%11.4g',row(k)));
        set(h(k,p+1),'HorizontalAlignment','right','Tag','text',...);
          'FontName','Geneva','FontSize',9,'Color','w');
      end
   end 
   set(0,'CurrentFigure',step_fig);

elseif strcmp(action,'history'),
   in = get(findobj(hist_fig,'Tag','in'),'UserData');
   in = in(:,flag);
   in = in(find(~isnan(in)));
   set(hist_fig,'Pointer','watch');
   stepwise(X,y,in)
   set(hist_fig,'Pointer','arrow');

elseif strcmp(action,'stray_click')
   set(step_fig,'CurrentAxes',step_axes)
       
elseif strcmp(action,'close'),
   close(data_fig);
   close(step_fig);
   close(hist_fig);
end
