function ncdexpo(message,sys)
%NCDEXPO Manages demonstration of ncddemo1.m for Expo.

%       Author(s): A. Potvin, 8-1-94
%       Copyright (c) 1994 by The MathWorks, Inc.
 
ni = nargin;
if ni==0,
   error('Must have at least one input.')
end

if strcmp(message,'create'),
   % Create special demo window
   DefUiBgC = get(0,'DefaultUicontrolBackgroundColor');
   figt1 = figure('Menubar','none','Unit','norm', ...
    'NumberTitle','off','Name',['Info: ' sys],'Position',[0.6 0.7 0.39 0.29], ...
    'ColorMap',[],'Color',DefUiBgC);
   str = ...
       ['Welcome to the Nonlinear Control Design (NCD)  '
	'Toolbox demonstration.                         '
	'                                               '
	'DOUBLE CLICK on the block labeled "NCD Toolbox"'
	'This will display a constraint window and      '
	'begin the demonstration.                       '
	'                                               '
	'PRESS CLOSE NCD Demo at anytime during this    '
	'demonstration to exit.                         '];
   uicontrol('Style','edit','Unit','norm','Tag','EditInfo','Position', ...
    [0 .15 1 .85],'Max',2,'Backgroundcolor','w','String',str);
   uicontrol('Style','push','String','CLOSE NCD Demo', ...
    'Unit','norm','Position',[.25 .02 .5 .1], ...
    'Callback',['ncdexpo(''close'',''' sys ''')']);

   % Open ncddemo1 and initialize necessary variables
   eval(sys)
   p = get_param(sys,'Location');
   set_param(sys,'Location',[0 0 p(3)-p(1) p(4)-p(2)])

   % Augment the NCD Toolbox block's Mask Dialogue
   set_param([sys '/Outport'],'Mask Dialogue', ...
    'eval(''optblock,ncdexpo(''''ParamMaker'''')'')'); 
   if strcmp(sys,'ncddemo3'),
      set_param('ncddemo3/Outport1','Mask Dialogue', ...
       'eval(''optblock,ncdexpo(''''ParamMaker'''')'')'); 
   end

elseif strcmp(message,'close'),
   % Clear variables and close figures and systems

   % Close ncddemo1 if it's still on the screen
   % Note: this should also close all subwindows
   bdclose(sys)

   % Close all NCD Toolbox figures
   % Includes Expo, Help dialogs, other dialogs, and Constraint figures
   % Does not close a few dialogs.  Should we check for those explicitely?
   for i=get(0,'Children')',
      Name = lower(get(i,'Name'));
      if ~isempty(findstr(Name,'ncd')),
         close(i);
      end
   end

   % Clear all the NCD Toolbox variables or ncddemo1 variables
   clear global NCD_LB NCD_UB options topt varstr vlbstr vubstr
   clear global RANGE_LIMIT REF_SIG OPT_STOP OPT_STEP SAVED_SYS
   clear global UC_UV UC_LB UC_UB UC_MC UC_ON
   clear global Kd Ki Kd a1 a2

elseif strcmp(message,'ParamMaker'),
   global Ki Kp Kd
   Ki_str = mat2str(Ki,3);
   Kp_str = mat2str(Kp,3);
   Kd_str = mat2str(Kd,3);

   % Get current system name.  Assumes the NCD Block just double-clicked.
   sys = get_param;

   % NCD constraint figure will be current figure
   NCDFig = get(0,'CurrentFigure');

   % Check if Parameter Update figure is on the screen
   FName = ['NCD Parameter Update: ' sys];
   [flag,fig] = figflag(FName,1);
   if ~flag,
      % Create the Parameter Update figure
      DefUiBgC = get(0,'DefaultUicontrolBackgroundColor');
      if strcmp(sys,'ncddemo1'),
         FigPos = [.6 .51 .39 .13];
      else
         FigPos = [.4 .51 .59 .13];
      end
      fig = figure('Menubar','none','Unit','norm','NumberTitle','off', ...
       'Position',FigPos,'Name',FName, ...
       'ColorMap',[],'Color',DefUiBgC);

      % Create the column header texts
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[0 .75 .35 .25],'HorizontalAlignment','left', ...
       'String','Variable');  
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[.15 .75 .39 .25],'HorizontalAlignment','left', ...
       'String','Original ');
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[.6 .75 .39 .25],'HorizontalAlignment','left', ...
       'String','Adjusted');

      % Create the Ki variable name text, original text, and adjusted text
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[0 .5 .1 .25],'HorizontalAlignment','left', ...
       'String',' Ki');
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[.15 .5 .39 .25],'HorizontalAlignment','left', ...
       'String',Ki_str,'Tag','Ki_org');
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[.6 .5 .39 .25],'HorizontalAlignment','left', ...
       'String','----','Tag','Ki_adj');
      
      % Create the Kp variable name text, original text, and adjusted text
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[0 .25 .1 .25],'HorizontalAlignment','left', ...
       'String',' Kp');
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[.15 .25 .39 .25],'HorizontalAlignment','left', ...
       'String',Kp_str,'Tag','Kp_org');
      uicontrol(fig,'Style','text','Unit','norm', ...
       'Position',[.6 .25 .39 .25],'HorizontalAlignment','left', ...
       'String','----','Tag','Kp_adj');
      
      if strcmp(sys,'ncddemo1'),
         % Create the Kd variable name text, original text, and adjusted text if necessary
         uicontrol(fig,'Style','text','Unit','norm', ...
          'Position',[0 0.01 .1 .25],'HorizontalAlignment','left', ...
          'String',' Kd');
         uicontrol(fig,'Style','text','Unit','norm', ...
          'Position',[.15 0.01 .39 .25],'HorizontalAlignment','left', ...
          'String',Kd_str,'Tag','Kd_org');
         uicontrol(fig,'Style','text','Unit','norm', ...
          'Position',[.6 0.01 .39 .25],'HorizontalAlignment','left', ...
          'String','----','Tag','Kd_adj');
      end

   else
      set(findobj(fig,'Tag','Ki_org'),'String',Ki_str);
      set(findobj(fig,'Tag','Ki_adj'),'String','----');

      set(findobj(fig,'Tag','Kp_org'),'String',Kp_str);
      set(findobj(fig,'Tag','Kp_adj'),'String','----');

      if strcmp(sys,'ncddemo1'),
         set(findobj(fig,'Tag','Kd_org'),'String',Kd_str);      
         set(findobj(fig,'Tag','Kd_adj'),'String','----');      
      end
   end

   % Alter the constraint figure if necessary
   if isempty(get(NCDFig,'Tag')),
      set(NCDFig,'Tag',sys)
      %   Make figure invisible
      %   Resize/move it
      %   Rescale uicontrols, remove ylabel, and move xlabel
      FigChil = get(NCDFig,'Children');
      set(NCDFig,'Visible','off')
      drawnow
      if strcmp(get_param(sys,'Current Block'),'Outport1'),
         Pos = [.5 0 .5 .35];
      else
         Pos = [0 0 .5 .35];
      end
      set(NCDFig,'Position',Pos)
      uictrls = findobj(FigChil,'flat','Type','uicontrol');
      for i=uictrls',
         set(i,'Position',get(i,'Position')+[0 0 .02 .02])
      end
      port = findobj(uictrls,'flat','String','Port:');
      set(port,'Position',get(port,'Position')-[0.02 0 0 0])
      ax = get(NCDFig,'CurrentAx');
      delete(get(ax,'YLabel'))
      xlab = get(ax,'XLabel');
      p = get(xlab,'Position').*[1 -1];
      delete(xlab)
      set(NCDFig,'Visible','on')
      set(0,'CurrentFigure',NCDFig)
      text('Unit','norm','Position',[.5 .05 0],'String','Time (s)')
   
      % Call for an initial simulation
      nlinopt(sys,1)
   
      % Change Start callbacks to update parameters
      StartP = findobj(FigChil,'flat','String','Start');
      StartM = findobj(FigChil,'flat','Label','Start');
      set([StartP; StartM],'Callback', ...
       ['ncdexpo(''ParamMaker''),' get(StartP,'Callback') ...
        ',ncdexpo(''ParamUpdate'',''' sys ''')'])
   end

   % Also change info string
   str =...
    [' NOTE: The demo plots the system response given the  '
     ' original values of the tunable variables.  You can  '
     ' do this at any time using the Initial response      '
     ' submenu of the Options menu.                        ' 
     ' Adjust the red bars to change design specifications ' 
     ' --------------------------------------------------- '
     ' Move mouse to any bar                               '  
     ' Click and drag bar to desired position.             '  
     '                                                     '
     ' Press START button to begin the optimization.       ' 
     '                                                     ' 
     ' NOTE: the bars may have any slope.                  '];
   if strcmp(sys,'ncddemo3'),
      str(12,:) = ' NOTE: The optimization takes 5 minutes on a Sparc10 ';
   end  
   Edit = findobj('Tag','EditInfo');
   set(Edit,'String',str)

elseif strcmp(message,'ParamUpdate'),
   global Ki Kp Kd
   Ki_str = mat2str(Ki,3);
   Kp_str = mat2str(Kp,3);
   Kd_str = mat2str(Kd,3);

   % Check if Parameter Update figure is on the screen
   FName = ['NCD Parameter Update: ' sys];
   [flag,fig] = figflag(FName,1);
   if flag,
      % Set the edit strings
      set(findobj(fig,'Tag','Ki_adj'),'String',Ki_str);
      set(findobj(fig,'Tag','Kp_adj'),'String',Kp_str);
      if strcmp(sys,'ncddemo1'),
         set(findobj(fig,'Tag','Kd_adj'),'String',Kd_str);
      end
   end

else
   error('Unknown message.')
end

% end ncdexpo
