function rsmdemo(action)
%RSMDEMO Demo of design of experiments and surface fitting.
%   RSMDEMO Creates a GUI that simulates a chemical reaction.
%   To start, you have a budget of 13 test reactions. Try to find out how
%   changes in each reactant affect the reaction rate. Determine the 
%   reactant settings that maximize the reaction rate. Estimate the
%   run-to-run variability of the reaction.
%
%   Now run a designed experiment using the model popup. Compare your
%   previous results with the output from response surface modelling or
%   nonlinear modelling of the reaction.
%
%   The GUI has the following elements:
%   1) A RUN button to perform one reactor run at the current settings.
%   2) An Export button to export the X and Y data to the base workspace.
%   3) Three sliders with associated data entry boxes to control the 
%      partial pressures of the chemical reactants: Hydrogen, n-Pentane,
%      and Isopentane.
%   4) A text box to report the reaction rate.
%   5) A text box to keep track of the number of test reactions you have
%      left.

%   Copyright (c) 1993-96 by The MathWorks, Inc.
%   $Revision: 2.2 $  $Date: 1996/02/13 23:36:29 $
%   B.A. Jones 4-21-95.

if nargin < 1
    action = 'start';
end

%On recursive calls get all necessary handles and data.
if ~strcmp(action,'start')   
  fact_fig = findobj(0,'Tag','control');
  p1field = findobj(fact_fig,'Tag','p1f');
  p1slider = findobj(fact_fig,'Tag','p1s');
  
  p2field = findobj(fact_fig,'Tag','p2f');
  p2slider = findobj(fact_fig,'Tag','p2s');
  
  p3field = findobj(fact_fig,'Tag','p3f');
  p3slider = findobj(fact_fig,'Tag','p3s');

  out_field = findobj(fact_fig,'Tag','of');
  runs_field = findobj(fact_fig,'Tag','rf');
  run_btn   = findobj(fact_fig,'Tag','rb');
  reset_btn = findobj(fact_fig,'Tag','rs');   

  data_fig = findobj(0,'Tag','data1');
  doe_fig  = findobj(0,'Tag','data2');
  if ~isempty(data_fig);
     trial_data = get(data_fig,'UserData');
     p1_popup   = findobj(data_fig,'Tag','popup1');
  end

  if ~isempty(doe_fig);
     doe_data   = get(doe_fig,'UserData'); 
  
     p2_popup   = findobj(doe_fig,'Tag','popup2');
     doe_button = findobj(doe_fig,'Tag','doe_button');
  end
end

if strcmp(action,'start')

% Initialize data values.
p1   = 200;
p1hi = 470;
p1lo = 100;
p2   = 150;
p2hi = 300;
p2lo = 80;

p3   = 50;
p3hi = 120;
p3lo = 10;

% Define graphics objects
fcolor  = [0.5 0.5 0.5];
fieldp1 = [120 80 80 20];
slidep1 = fieldp1 + [85 -60 -65 80];
textp1  = fieldp1 + [0 20 0 0];
fieldp2 = [240 80 80 20];
slidep2 = fieldp2 + [85 -60 -65 80];
textp2  = fieldp2 + [0 20 0 0];
fieldp3 = [360 80 80 20];
slidep3 = fieldp3 + [85 -60 -65 80];
textp3  = fieldp3 + [0 20 0 0];
outfieldp = [240 150 80 20];
textout   = outfieldp + [-10 20 20 0];

% Create Reaction Simulator Figure
fact_fig = figure('Units','Pixels','Position',[25 525 480 200]);
set(fact_fig,'Color','k','Backingstore','off','Resize','off',...
    'Name','Reaction Simulator','NextPlot','new','Tag','control');

gray_axes = axes;
set(gray_axes,'XTick',[],'YTick',[],'Units','Normalized','Position',[0 0 1 1]);
set(gray_axes,'Color',fcolor);
set(gray_axes,'ButtonDownFcn','rsmdemo(''stray_click'')');

p1_field=uicontrol('Style','edit','Units','Pixels','Position',fieldp1,...
         'BackgroundColor','white','String',num2str(p1),'Tag','p1f',...
       'Callback','rsmdemo(''setp1field'')');
         
p1_slider=uicontrol('Style','slider','Units','Pixels','Position',slidep1,...
        'Value',p1,'Max',p1hi,'Min',p1lo,...
        'Callback','rsmdemo(''setp1slider'')','Tag','p1s');

p1_text=uicontrol('Style','text','Units','Pixels','Position',textp1,...
        'BackgroundColor',fcolor,...
        'ForegroundColor','white','String','Hydrogen');

p2_field=uicontrol('Style','edit', 'Units','Pixels','Position',fieldp2,...
       'BackgroundColor','white','String',num2str(p2),'Tag','p2f',...
      'Callback','rsmdemo(''setp2field'')');

         
p2_slider=uicontrol('Style','slider','Units','Pixels','Position',slidep2,...
        'Value',p2,'Max',p2hi,'Min',p2lo,...
        'Callback','rsmdemo(''setp2slider'')','Tag','p2s');
                           
p2_text=uicontrol('Style','text','Units','Pixels','Position',textp2,...
        'BackgroundColor',fcolor,...
        'ForegroundColor','white','String','n-Pentane');

p3_field=uicontrol('Style','edit','Units','Pixels','Position',fieldp3,...
         'BackgroundColor','white','String',num2str(p3),'Tag','p3f',...
       'Callback','rsmdemo(''setp3field'')');
         
p3_slider=uicontrol('Style','slider','Units','Pixels','Position',slidep3,...
       'Value',p3,'Max',p3hi,'Min',p3lo,...
        'Callback','rsmdemo(''setp3slider'')','Tag','p3s');
                           
p3_text=uicontrol('Style','text','Units','Pixels','Position',textp3,...
        'BackgroundColor',fcolor,...
        'ForegroundColor','white','String','Isopentane');

out_field=uicontrol('Style','text','Units','Pixels',...
          'BackgroundColor','white','Position',outfieldp,'Tag','of');

out_text=uicontrol('Style','text','Units','Pixels','Position',textout,...
        'BackgroundColor',fcolor,'ForegroundColor','white','String','Reaction Rate');

runs_field=uicontrol('Style','text','Units','Pixels','String',num2str(13),...
         'BackgroundColor','white','Position',[25 150 70 20],'Tag','rf');

runs_text=uicontrol('Style','text','Units','Pixels','Position',[25 170 75 20],...
        'BackgroundColor',fcolor,'ForegroundColor','white','String','Runs Left');

reset_button = uicontrol('Style','Pushbutton','Position',[25 125 75 20],...
             'Units','Pixels','Callback','rsmdemo(''reset'')',...
          'Visible','off','Tag','rs','String','Reset');

run_button = uicontrol('Style','Pushbutton','Position',[25 80 75 20],'Tag','rb',...
             'Units','Pixels','Callback','rsmdemo(''run'')','String','Run');

output_button = uicontrol('Style','Pushbutton','Position',[25 55 75 20],...
               'Units','Pixels','Callback','rsmdemo(''output'')','String','Export');

help_button = uicontrol('Style','Pushbutton','Position',[375 170 100 20],...
            'Units','Pixels','Callback','rsmdemo(''help'')',...
            'String','Help');

close_button = uicontrol('Style','Pushbutton','Position',[25 10 75 20],...
               'Units','Pixels','Callback','rsmdemo(''close'')','String','Close');

% Create Trial and Error Data View
colheads = str2mat('Run #','Hydrogen','n-Pentane','Isopentane','Reaction Rate');
data_fig = figure('Units','Normalized','Position',[0.01 0.25 0.45 0.35]);
set(data_fig,'Color','w',...
    'Name','Trial and Error Data','NextPlot','new','Tag','data1');
data_axes = axis('off');
set(data_axes,'Units','Normalized','Position',[0 0 1 1],...
    'EraseMode','xor','DrawMode','fast');   
z = [-.1 0.05 0.28 0.52 0.79];
h = zeros(5,1);
for k = 1:5
  h(k)=text(z(k),0.95,colheads(k,:));
  set(h(k),'FontName','Geneva','FontSize',12);
  set(h(k),'Color','k');
end

analyze_button = uicontrol('Style','Pushbutton','Position',[0.01 0.01 0.25 0.1],...
             'Units','Normalized','Callback','rsmdemo(''analyze'')','String','Analyze');

p1_popup       = uicontrol(data_fig,'Style','Popup','String',...
              'Plot|Hydrogen vs. Rate|n-Pentane vs. Rate|Isopentane vs. Rate',...
              'Units','normalized','Position',[0.3 0.01 0.3 0.1],...
              'CallBack','rsmdemo(''plot1'')','Tag','popup1');

% Create Designed Experiment Data View
doe_fig = figure('Units','Normalized','Position',[0.47 0.22 0.45 0.39]);
set(doe_fig,'Color','w',...
    'Name','Experimental Design Data','NextPlot','new','Tag','data2');
doe_axes = axis('off');
set(doe_axes,'Units','Normalized','Position',[0 0 1 1],...
    'EraseMode','xor','DrawMode','fast');   
z = [-.1 0.05 0.28 0.52 0.79];
h = zeros(5,1);
for k = 1:5
  h(k)=text(z(k),0.9,colheads(k,:));
  set(h(k),'FontName','Geneva','FontSize',12);
  set(h(k),'Color','k');
end

doe_button = uicontrol('Style','Pushbutton','Position',[0.01 0.88 0.3 0.1],...
             'Units','Normalized','Callback','rsmdemo(''doe'')',...
          'String','Do Experiment','Tag','doe_button');

rsm_button = uicontrol('Style','Pushbutton','Position',[0.01 0.01  0.3 0.1],...
             'Units','Normalized','Callback','rsmdemo(''fit1'')','String','Response Surface');

nlin_button = uicontrol('Style','Pushbutton','Position',[0.34 0.01 0.3 0.1],...
             'Units','Normalized','Callback','rsmdemo(''fit2'')','String','Nonlinear Model');

p2_popup       = uicontrol(doe_fig,'Style','Popup','String',...
              'Plot|Hydrogen vs. Rate|n-Pentane vs. Rate|Isopentane vs. Rate',...
              'Units','normalized','Position',[0.67 0.01 0.3 0.1],...
              'CallBack','rsmdemo(''plot2'')','Tag','popup2');

% Bring Up Help Screen
hthelp('simgui.html');
% Initialization Complete

% Callback for Hydrogen Slider
elseif strcmp(action,'setp1slider')
  p1 = get(p1slider,'Value');
  set(p1field,'String',num2str(p1));

% Callback for n-Pentane Slider
elseif strcmp(action,'setp2slider')
  p2 = get(p2slider,'Value');
  set(p2field,'String',num2str(p2));

% Callback for Isopentane Slider
elseif strcmp(action,'setp3slider')
  p3 = get(p3slider,'Value');
  set(p3field,'String',num2str(p3));

% Callback for Hydrogen Data Entry Field
elseif strcmp(action,'setp1field')
  p1 = str2num(get(p1field,'String'));
  set(p1slider,'Value',p1);

% Callback for n-Pentane Data Entry Field
elseif strcmp(action,'setp2field')
  p2 = str2num(get(p2field,'String'));
  set(p2slider,'Value',p2);

% Callback for Isopentane Data Entry Field
elseif strcmp(action,'setp3field')
  p3 = str2num(get(p3field,'String'));
  set(p3slider,'Value',p3);

% Callback for Run Button
elseif strcmp(action,'run')
    if isempty(data_fig)
       % Create No Data Figure Dialog.
       warndlg('The data figure is gone. Restart rsmdemo to run more tests.');
        return;
    end
   
    data = get(data_fig,'UserData');
   [m,n] = size(data);
   if m >= 12
       % Create Reset Button Dialog.
       warndlg('Press the Reset button to get another 13 runs');
      set(reset_btn,'Visible','on');
   end
   if m == 13
       set(run_btn,'Enable','off');
      return;
   end
   set(runs_field,'String',num2str(13-m-1));
    p1 = get(p1slider,'Value');
    p2 = get(p2slider,'Value');
    p3 = get(p3slider,'Value');
   y  = 1.25*(p2 - p3/1.5183)./(1+0.064*p1+0.0378*p2+0.1326*p3)*normrnd(1,0.05);
    set(out_field,'String',num2str(y));
    data = [data;p1 p2 p3 y];
    set(data_fig,'UserData',data);
   set(0,'CurrentFigure',data_fig);
   z = [-0.02 0.15 0.4 0.63 0.95];
   x = 0.95 - 0.068*(m+1);
   row = [m+1 p1 p2 p3 y];
   for k = 1:5
       if k < 5,
          h(k) = text(z(k),x,sprintf('%4i',round(row(k))));
         set(h(k),'HorizontalAlignment','right');
          set(h(k),'FontName','Geneva','FontSize',12);
           else
          h(k) = text(z(k),x,sprintf('%6.2f',row(k)));
         set(h(k),'HorizontalAlignment','right');
         set(h(k),'FontName','Geneva','FontSize',12);
       end

      set(h(k),'Color','k');
   end
   set(0,'CurrentFigure',fact_fig);

% Callback for Do Experiment Button
elseif strcmp(action,'doe')
   % Do Designed Experiment.  
   data = get(doe_fig,'UserData');
   if ~isempty(data),
      doe_axes = get(doe_fig,'CurrentAxes');
      t = get(doe_axes,'Children');
      delete(t(1:length(t)-5));
   end

   settings = cordexch(3,13,'q');
   mr = [285 190 65];
   mr = mr(ones(13,1),:);

   hr = [185 110 55];
   hr = hr(ones(13,1),:);
   settings = settings.*hr + mr;
   y = zeros(13,1);
   p1 = settings(:,1);
   p2 = settings(:,2);
   p3 = settings(:,3);
   z = [-0.02 0.15 0.4 0.63 0.95];
   for k = 1:13
     x = 0.90 - 0.065*k;
     row = [k p1(k) p2(k) p3(k) y(k)];
     for k1 = 1:4
        h(k1) = text(z(k1),x,sprintf('%4i',round(row(k1))));
       set(h(k1),'HorizontalAlignment','right');  
       set(h(k1),'FontName','Geneva','FontSize',12);
        set(h(k1),'Color','k');
     end
   end
   for k = 1:13
     set(p1slider,'Value',p1(k));
     set(p1field,'String',num2str(p1(k)));

     set(p2slider,'Value',p2(k));
      set(p2field,'String',num2str(p2(k)));

     set(p3slider,'Value',p3(k));
     set(p3field,'String',num2str(p3(k)));

     y(k)  = 1.25*(p2(k) - p3(k)/1.5183)./(1+0.064*p1(k)+0.0378*p2(k)+0.1326*p3(k))*normrnd(1,0.05);
     set(out_field,'String',num2str(y(k)));
     set(doe_fig,'UserData',data);
     set(0,'CurrentFigure',doe_fig);
     x = 0.9 - 0.067*k;
     row = [k p1(k) p2(k) p3(k) y(k)];
     h(5) = text(z(5),x,sprintf('%6.2f',row(5)));
      set(h(5),'HorizontalAlignment','right');
     set(h(5),'FontName','Geneva','FontSize',12);
     set(h(5),'Color','k');
     set(0,'CurrentFigure',fact_fig);
     pause(1);
     set(runs_field,'String',num2str(13-k));   
   end
   data = [settings y];
   set(doe_fig,'UserData',data);
   set(reset_btn,'Visible','on');
   set(run_btn,'Enable','off');

% Callback for Analyze Button
elseif strcmp(action,'analyze')
      data = get(data_fig,'UserData');
   
      if size(data,1) < 6
       % Create Not Enough Data Dialog.
       warndlg('Not enough data. Please do more test reactions.');
       return;
     end
      x = data(:,1:3);
      y = data(:,4);
      xname = str2mat('Hydrogen','n-Pentane','Isopentane');
      yname = 'Reaction Rate';
      rstool(x,y,'linear',[],xname,yname);

% Callback for Trial and Error Figure Plot Menu
elseif strcmp(action,'plot1')
      data = get(data_fig,'UserData');
      if size(data,1) < 2
       % Create Not Enough Data Dialog.
       warndlg('Not enough data. Please do more test reactions.');
       return;
     end
     if get(p1_popup,'Value') == 2
        plot(data(:,1),data(:,4),'+');
       if any(diff(sort(data(:,1)))) > 0
          lsline;
       end
       xlabel('Hydrogen');
       ylabel('Rate');
     elseif get(p1_popup,'Value') == 3
        plot(data(:,2),data(:,4),'+');
       if any(diff(sort(data(:,2)))) > 0
          lsline;
       end
       xlabel('n-Pentane');
       ylabel('Rate');
     elseif get(p1_popup,'Value') == 4
        plot(data(:,3),data(:,4),'+');
       if any(diff(sort(data(:,3)))) > 0
          lsline;
       end
       xlabel('Isopentane');
       ylabel('Rate');
      else
        return;
      end
      set(p1_popup,'Value',1);     

% Callback for DOE Figure Plot Menu
elseif strcmp(action,'plot2')
      data = get(doe_fig,'UserData');
      if size(data,1) < 1
       % Create Not Enough Data Dialog.
       warndlg('No data. Please press "Do Experiment" Button.');
       return;
     end
     if get(p2_popup,'Value') == 2
        plot(data(:,1),data(:,4),'+');
       lsline;
       xlabel('Hydrogen');
       ylabel('Rate');
     elseif get(p2_popup,'Value') == 3
        plot(data(:,2),data(:,4),'+');
       lsline;
       xlabel('n-Pentane');
       ylabel('Rate');
     elseif get(p2_popup,'Value') == 4
        plot(data(:,3),data(:,4),'+');
       lsline;
       xlabel('Isopentane');
       ylabel('Rate');
      else
        return;
      end
      set(p2_popup,'Value',1);     

% Callback for Response Surface Button 
elseif strcmp(action,'fit1')
      data = get(doe_fig,'UserData');
   
      if size(data,1) < 1
       % Create Not Enough Data Dialog.
       warndlg('No data. Please press "Do Experiment" Button.');
       return;
     end
   
      x = data(:,1:3);
      y = data(:,4);
      xname = str2mat('Hydrogen','n-Pentane','Isopentane');
      yname = 'Reaction Rate';
      rstool(x,y,'quadratic',[],xname,yname);

% Callback for Nonlinear Model Button 
elseif strcmp(action,'fit2')
      data = get(doe_fig,'UserData');
      if size(data,1) < 6
       % Create Not Enough Data Dialog.
       warndlg('No data. Please press "Do Experiment" Button.');
       return;
     end
   
      x = data(:,1:3);
      y = data(:,4);
      xname = str2mat('Hydrogen','n-Pentane','Isopentane');
      yname = 'Reaction Rate';
      beta0 = [1.2 0.1 0.01 0.1 1.5];
      nlintool(x,y,'hougen',beta0,[],xname,yname);

% Callback for Help Button 
elseif strcmp(action,'help')
   hthelp('simgui.html');

% Callback for Close Button 
elseif strcmp(action,'close')
   close(fact_fig);
   close(data_fig);
   close(doe_fig);
 
% Callback for Reset Button 
elseif strcmp(action,'reset')
   set(run_btn,'Enable','on');
   data_axes = get(data_fig,'CurrentAxes');
   t = get(data_axes,'Children');
   
   delete(t(1:length(t)-5));
   set(runs_field,'String',num2str(13));
   set(reset_btn,'Visible','off');
   set(data_fig,'Userdata',[]);
   
% Callback for Export Button 
elseif strcmp(action,'output')
   if isempty(data_fig)
      warndlg('The data is gone. Restart rsmdemo to generate more data.');
     return;
   end
   data1 = get(data_fig,'UserData');

   if ~isempty(doe_fig)
      data2 = get(doe_fig,'UserData');
   else
      data2 = [];
   end

   if isempty(data1) & isempty(data2),
     warndlg('There is no data. Please do some test reactions.');
     return;
   elseif ~isempty(data1) & isempty(data2)
      x1 = data1(:,1:3);
      y1 = data1(:,4);
      matqueue('put',x1);
      matqueue('put',y1);

     entrystr = 'reactants,rate';
      promptstr = 'Enter names for the variables or use the supplied defaults.';
      matqdlg('buffer2ws','PromptString',promptstr,'EntryString',entrystr);
   elseif isempty(data1) & ~isempty(data2)
      x2 = data2(:,1:3);
      y2 = data2(:,4);
      matqueue('put',x2);
      matqueue('put',y2);

     entrystr = 'doe_reactants,doe_rate';
      promptstr = 'Enter names for the variables or use the supplied defaults.';
      matqdlg('buffer2ws','PromptString',promptstr,'EntryString',entrystr);
   elseif ~isempty(data1) & ~isempty(data2)
      x1 = data1(:,1:3);
      y1 = data1(:,4);
      matqueue('put',x1);
      matqueue('put',y1);
      x2 = data2(:,1:3);
      y2 = data2(:,4);
      matqueue('put',x2);
      matqueue('put',y2);

     entrystr = 'reactants,rate,doe_reactants,doe_rate';
      promptstr = 'Enter names for the variables or use the supplied defaults.';
      matqdlg('buffer2ws','PromptString',promptstr,'EntryString',entrystr);
   end
end
