function varargout = importcomp(varargin);
% IMPORTCOMP opens the window for importing LTI Compensators into CODA GUIs
%   CompData = IMPORTCOMP('initialize',ParentFig) opens the Import LTI 
%   Compensator window when issued by a callback from the GUI with handle
%   ParentFig.  The execution of the callback is paused until the Import
%   LTI Compensator window is closed. 
%
%   After the window is closed, the results of the import are passed to
%   the Parent GUI in the structured array CompData.  If the Cancel button
%   is pressed or the window is deleted, CompData is empty.
%
%   CompData = IMPORTCOMP('initialize',ParentFig,CompName,MaxDims)
%   allows the following attributes of the Import window to be specified:
%
%      1) CompName = A default name for the Compensator
%      2) MaxDims = A 1x2 array of the form [MaxNumOutputs, MaxNumInputs]
%                   indicating the maximum size of the compensator 
%
%   See also  IMPORTFCN

%   Karen D. Gondoly
%   Copyright (c) 1986-1999 The Mathworks, Inc. All Rights Reserved.
% $Revision: 1.4 $

%---Check if number of input arguments is in the correct range
ni = nargin;
no=nargout;

error(nargchk(2,4,ni));

%---The first input argument should always be a string action
action = varargin{1};
if ~ischar(action)
   error('The first input argument must be a valid string action.');
end

%---Read data based on action
switch action
case 'initialize',
   ParentFig = varargin{2};
   if ni>2,
      CompName = varargin{3};
      if isempty(CompName),
         CompName='NewComp';
      end
      if ~ischar(CompName),
         error('The third input argument must be a character array')
      end
   else
      CompName='NewComp';
   end
   if ni>3,
      CompLimits=varargin{4};
      if ~isequal(length(CompLimits),2),
         error('The fourth argument must be a vector of length two');
      end
   else
      CompLimits = [Inf,Inf];
   end	
   
otherwise
   ImportFig = varargin{2};
   if ni>2,
      ImportUd = varargin{3};
   else
      ImportUd = get(ImportFig,'UserData');
   end
end % switch action

%---Actions
switch action
case 'initialize',
   ImportFig = LocalOpenFig(ParentFig,CompName,CompLimits);
   
   %---Wait until the figure is closed and return the new Structure number
   uiwait(ImportFig);
   
   if ishandle(ImportFig),
      ImportUd=get(ImportFig,'UserData');
      close(ImportFig)
      ModelData = ImportUd.ModelData;
   else
      ModelData = [];
   end
   if no,
      varargout{1}=ModelData ;
   end
   
case 'radiobutton',
   val = get(gcbo,'Value');
   sibs = get(gcbo,'UserData');
   
   if ~val,
      set(gcbo,'Value',1);
   elseif val==1,
      set(sibs,'Value',0);
      set(ImportUd.Handles.FileNameEdit,'String','',...
         'UserData',struct('FileName',[],'PathName',[]));
      set(ImportUd.Handles.CompEdit,'String','1','UserData',...
         struct('ListIndex',0,'String','1'));
   end % if/else val
   
case 'apply', 
   %---Get the new Compensator name
   ImportUd.ModelData.Name = get(ImportUd.Handles.ModelNameEdit,'String');
   if isempty(ImportUd.ModelData.Name),
      warndlg('You must enter a name for the compensator.','Import Warning');
      return
   end
   
   udCompEdit = get(ImportUd.Handles.CompEdit,'UserData');
   if isempty(udCompEdit.ListIndex), % Nothing entered
      warndlg({'You have not entered a Compensator.'; ...
            ''; ...
            'Enter a variable from the list into the "K=" edit box'; ...
            'or type in a valid expression to create an LTI object.'},'Import Warning');
      return
   elseif ~udCompEdit.ListIndex, % Scalar or LTI object entered
      ImportUd.ModelData.Object = eval(udCompEdit.String);
      if isa(ImportUd.ModelData.Object,'double');
         ImportUd.ModelData.Object=zpk(ImportUd.ModelData.Object);
      end
   else, % ListBox entry entered
      ImportUd.ModelData.Object = ...
      	ImportUd.ListData.Objects{udCompEdit.ListIndex};
   end
      
   %---Check the size of the Compensator, if applicable
   NewCompDims = size(ImportUd.ModelData.Object);
   if any(NewCompDims>ImportUd.CompLimits),
      warndlg('The Compensator has too many inputs or outputs','Import Warning');
      return
   end
   
   set(ImportFig,'UserData',ImportUd)
   uiresume(ImportFig)

case 'cancel', % Close the Loop Structure window without saving any changes
   ImportUd.ModelData=[];
   set(ImportFig,'UserData',ImportUd);
   uiresume(ImportFig)
   
case 'selectcomp',
   % List box callback that allows user to double-click on a name to enter a compensator.
   % Only good when there is only one data edit box for obects to go into.
   if strcmpi(get(ImportFig,'SelectionType'),'open')
      AllNames = get(ImportUd.Handles.ModelList,'String');
      if ~isempty(AllNames), % Make sure these is something in the list
         SelectedName = get(ImportUd.Handles.ModelList,'Value');
         udEdit = get(ImportUd.Handles.CompEdit,'UserData');
         udEdit.String = AllNames{SelectedName};
         udEdit.ListIndex = SelectedName;
         set(ImportUd.Handles.CompEdit,'String',AllNames{SelectedName},'UserData',udEdit);
         importcomp('setname',ImportFig)
      end
   end
   
case 'setname', % Set the Compensator name to be same as compensator variable name
   VarName = get(ImportUd.Handles.CompEdit,'String');
   if ~isempty(VarName),
      set(ImportUd.Handles.ModelNameEdit,'String',VarName,'UserData',VarName)
   end
   
case 'help',
   set(ImportFig,'WindowStyle','normal');
   
   helptext={'Importing LTI Compensators', ...
         {'The Import LTI Compensators window is used to import an LTI ';
         'compensator into a Graphical User Interface in the MATLAB Control ';
         'Design and Analysis environment';
         '';
         'The following data is needed to completely specify the compensator:';
         '  1) The compensator name';
         '  2) The compensator data';
         '';
         'Press OK to import the specified compensator.';
         'Press Cancel to close the window without importing a compensator.';
         '';
         'Flip through the remaining Topics for a detailed description of how ';
         'to specify the compensator data.'};
      'Compensator Source',...
         {'The Import From: field indicates where the Import window looks for ';
         'the compensator data.';
         '';
         'Data can be imported from one of three locations:';
         '   1) The Workspace - lists all LTI objects in MATLAB''s workspace';
         '   2) A MAT-file - lists all LTI objects in the specified MAT-file';
         '   3) A Simulink diagram - lists all LTI blocks in the specified diagram';
         '';
         'When selecting MAT-file or Simulink diagram, either:';
         '   1) Enter the appropriate file or diagram name in the editable text box';
         '   2) Press the Browse button to search for a particular file or diagram.';
         '';
         'Caution: The file or diagram must exist on the current MATLAB path.'};
      'Compensator List',...
         {'The Compensator List box shows all the LTI models or blocks found ';
         'in the location indicated in the Import From: field.  The compensator ';
         'must come from this list.';
         '';
         'To move an item in the list to the Compensator field:';
         '   1) Select the variable name in the list box';
         '   2) Press the arrow button associated with the appropriate data field'};
      'Compensator',...
         {'The Compensator field shows the compensator to be imported';
         '';
         'Enter a name for the Compensator in the Name: editable text box.';
         ''
         'Enter data into the Compensator Data editable text boxes by either:';
         '   1) Selecting an item in the list box and pressing the appropriate';
         '      arrow button';
         '   2) Typing the name of a list box variable in the editable text box';
         '   3) Typing in a scalar gain or expression that evaluates to an LTI object';
         '';
         'Cautions:';
         '   1) Only variables that exist in the list box may be entered into';
         '         the Compensator Data boxes';
         '   2) All Compensator Data must be entered before exiting the Import window'}};
   
   
   
   helpwin(helptext);
end % switch action


%--------------------------Internal Functions------------------------
%%%%%%%%%%%%%%%%%%%%
%%% LocalOpenFig %%%
%%%%%%%%%%%%%%%%%%%%
function a = LocalOpenFig(ParentFig,CompName,CompLimits);

StdColor = get(0,'DefaultFigureColor');
PointsToPixels = 72/get(0,'ScreenPixelsPerInch');
StdUnit = 'points';

ud = struct('Parent',ParentFig,...
   'ListData',struct('Names',[],'Objects',[]),...
   'ModelData',struct('Name',CompName,'Object',zpk(1)),...
   'CompLimits',CompLimits,...
   'Handles',[]);

a = figure('Units','points', ...
	'Color',StdColor, ...
	'MenuBar','none', ...
   'visible','off',...
   'IntegerHandle','off',...
	'Name','Import LTI Compensator', ...
	'NumberTitle','off', ...
   'WindowStyle','modal',...
	'Position',PointsToPixels*[75 171 515 204], ...
	'Tag','ImportCompFig');

%---Add Frames
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Position',PointsToPixels*[176 4 334 28], ...
	'Style','frame');
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Position',PointsToPixels*[178 37 148 150], ...
	'Style','frame');
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Position',PointsToPixels*[7 39 163 149], ...
   'Style','frame');

%---Add Import From: controls
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Position',PointsToPixels*[39 173 97 24], ...
	'String','Import From:', ...
	'Style','text');
ud.Handles.Wbutton = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
   'Callback','importcomp(''radiobutton'',gcbf);importfcn(''workspace'',gcbf);',...
	'Position',PointsToPixels*[15 161 100 19], ...
	'String','Workspace', ...
	'Style','radiobutton', ...
	'Tag','Wbutton', ...
	'Value',1);
ud.Handles.Mbutton = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
   'Callback','importcomp(''radiobutton'',gcbf);importfcn(''matfile'',gcbf);',...
	'Position',PointsToPixels*[15 142 100 19], ...
	'String','MAT-file', ...
	'Style','radiobutton', ...
	'Tag','Mbutton');
ud.Handles.Sbutton = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
   'BackgroundColor',StdColor, ...
   'Callback','importcomp(''radiobutton'',gcbf);importfcn(''simulink'',gcbf);',...
   'Position',PointsToPixels*[15 123 100 19], ...
	'String','Simulink', ...
	'Style','radiobutton', ...
	'Tag','Sbutton');
set(ud.Handles.Wbutton,'UserData',[ud.Handles.Mbutton,ud.Handles.Sbutton]);
set(ud.Handles.Mbutton,'UserData',[ud.Handles.Wbutton,ud.Handles.Sbutton]);
set(ud.Handles.Sbutton,'UserData',[ud.Handles.Mbutton,ud.Handles.Wbutton]);
ud.Handles.FileNameText = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Enable','off', ...
	'Position',PointsToPixels*[16 95 141 20], ...
	'String','MAT-file name:', ...
	'Style','text', ...
	'Tag','FileNameText');
ud.Handles.FileNameEdit = uicontrol('Parent',a, ...
   'Units',StdUnit, ...
   'Horiz','left',...
   'Enable','off',...
	'BackgroundColor',[1 1 1], ...
	'Position',PointsToPixels*[15 74 141 20], ...
	'Style','edit', ...
   'UserData',struct('FileName',[],'PathName',[]),...
   'Tag','FileNameEdit');
ud.Handles.BrowseButton = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
   'Callback','importcomp(''browse'',gcbf);',...
	'Enable','off', ...
	'Position',PointsToPixels*[15 49 142 20], ...
	'String','Browse', ...
	'Tag','BrowseButton');

%---Add Compensator List
ud.Handles.ModelText = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Position',PointsToPixels*[183 182 140 16], ...
	'String','Workspace Compensators', ...
	'Style','text');
ud.Handles.ModelList = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
   'BackgroundColor',[1 1 1], ...
   'Callback','importcomp(''selectcomp'',gcbf)', ...
	'Position',PointsToPixels*[185 45 132 133], ...
	'Style','listbox', ...
	'Tag','ModelList', ...
   'Value',1);

%---Add Design Compensator Field
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Position',PointsToPixels*[361 38 149 149], ...
	'Style','frame');
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'Position',PointsToPixels*[378 181 108 18], ...
	'String','Compensator', ...
	'Style','text');
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'HorizontalAlignment','left', ...
	'Position',PointsToPixels*[367 160 40 20], ...
	'String','Name:', ...
	'Style','text');
ud.Handles.ModelNameEdit = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',[1 1 1], ...
   'Callback','importfcn(''namecallback'',gcbf);',...
   'Horiz','left',...   
   'Position',PointsToPixels*[380 139 125 20], ...
   'Style','edit', ...
   'String',CompName,...
   'UserData',CompName,...
	'Tag','ModelNameEdit');
b = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',StdColor, ...
	'HorizontalAlignment','left', ...
	'Position',PointsToPixels*[368 105 60 22], ...
	'String','K =', ...
	'Style','text');
EditUd = struct('ListIndex',[],'String','');
ud.Handles.CompEdit = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
	'BackgroundColor',[1 1 1], ...
   'Callback','importfcn(''editcallback'',gcbf);importcomp(''setname'',gcbf);',...
   'Position',PointsToPixels*[380 84 125 20], ...
   'Style','edit', ...
   'Horiz','left',...
   'UserData',EditUd,...
	'Tag','CompEdit');
ud.Handles.CompButton = uicontrol('Parent',a, ...
	'Units',StdUnit, ...
   'Callback','importfcn(''buttoncallback'',gcbf);importcomp(''setname'',gcbf);',...
	'Position',PointsToPixels*[331 84 25 20], ...
   'String','-->', ...
   'UserData',ud.Handles.CompEdit,...
	'Tag','CompButton');

%---Compensator I/O Button
%---Revisit for CODA
%b = uicontrol('Parent',a, ...
%	'Units',StdUnit, ...
%	'Position',PointsToPixels*[372 46 130 25], ...
%	'String','Compensator I/Os', ...
%	'Tag','IObutton');

ud.Handles.HelpButton = uicontrol('Parent',a, ...
   'Callback','importcomp(''help'',gcbf);',...
   'Unit',StdUnit,...
	'Position',PointsToPixels*[182 8 74 20], ...
	'String','Help', ...
	'Tag','HelpButton');
ud.Handles.OKButton = uicontrol('Parent',a, ...
   'Callback','importcomp(''apply'',gcbf);',...
   'Unit',StdUnit,...
	'Position',PointsToPixels*[306 8 74 20], ...
	'String','OK', ...
	'Tag','OKButton');
ud.Handles.CancelButton = uicontrol('Parent',a, ...
   'Callback','importcomp(''cancel'',gcbf);',...
   'Unit',StdUnit,...
	'Position',PointsToPixels*[429 8 74 20], ...
	'String','Cancel', ...
	'Tag','CancelButton');

set(a,'UserData',ud,'visible','on')
importfcn('workspace',a);
