function ImpRespObj = impplot(RespObj,Systems,X,Y,PlotStyle);      
%IMPPLOT Create a Impulse Response Object for the Control System Toolbox

%   Authors: Karen Gondoly, 2-2-98
%   Revised: Adam W. DiVergilio
%   Copyright 1986-2000 The MathWorks, Inc. 
%   $Revision: 1.20 $ $Date: 2000/08/02 20:55:11 $

ni = nargin;

%---Properties
ImpRespObj = struct(...
   'PeakResponse','off',...
   'PeakResponseValue',[],...
   'SettlingTime','off',...
   'SettlingTimeThreshold',[],...
   'SettlingTimeValue',[]);

%---Return cases (ni==0,1)
switch ni
case 0
   RespObj = response;
   ImpRespObj = class(ImpRespObj,'impplot',RespObj);
   return
case 1
   if ~isa(RespObj,'response')
      error('Invalid Response Object passed to IMPPLOT')
   elseif isa(RespObj,'impplot')
      ImpRespObj = RespObj;
   else
      ImpRespObj = class(ImpRespObj,'impplot',RespObj);
   end
   return
end

%---Initialize ImpRespObj
ImpFlag = isa(RespObj,'impplot');
if ImpFlag
   ImpRespObj = RespObj;
   RespObj = ImpRespObj.response;
else
   Preferences = get(RespObj,'Preferences');
   ImpRespObj.SettlingTimeThreshold = Preferences.SettlingTimeThreshold;
   set(get(RespObj,'PlotAxes'),'XScale','linear','YScale','linear');
end

%---Access needed parent property values
PV = get(RespObj,{'PlotAxes','UIContextMenu','SystemNames'});
[LTIdisplayAxes,ContextMenu,SystemNames] = deal(PV{:});
if ImpFlag
   % Adding to existing IMPPLOT object
   RH0 = get(RespObj,'ResponseHandles');
else
   % New IMPPLOT object
   RH0 = {};
end

%---Get dimension info and names of new systems
[numout,numin] = size(LTIdisplayAxes);
NumOldSys = length(RH0);                      % number of existing systems
NewSystemNames = SystemNames(NumOldSys+1:end);
NumNewSys = length(NewSystemNames);           % number of added systems 

%---Assign empty system names. This is how the code knows it needs to
%----Calculate the Plot Options for this particular system
PeakRespVals = struct('System',cell(NumNewSys,1),'Time',[],'Peak',[]);
SetTimeVals = struct('System',cell(NumNewSys,1),...
   'SettlingTime',[],'Amplitude',[]);

%---Initialize ResponseHandles array and LTIresponseLine's UserData
ResponseHandles = cell(NumNewSys,1);

for ctR=1:length(ResponseHandles)  % each system
   % Get plot data
   Xarray = X{ctR};
   Yarray = Y{ctR};
   SizeArray = size(Xarray);
   NumArray = prod(SizeArray);

   % Get the style and legend
   Style = struct2cell(PlotStyle(ctR));
   [CC,LL,MM,LegendStr] = deal(Style{:});
   if NumArray>1
      ArrayDimsStr = sprintf('%dx',SizeArray);
      LegendStr = sprintf('%s array: %s',ArrayDimsStr(1:end-1),LegendStr);
   end

   %---Add legend to system name for new systems
   set(ContextMenu.Systems.Names(NumOldSys+ctR),...
      'Label',sprintf('%s (%s)',NewSystemNames{ctR},LegendStr),...
      'ForegroundColor',CC)

   LindHandle = cell(numout,numin);
   for ctin = 1:numin
      for ctout = 1:numout
         RH=cell(SizeArray);
         for ctArray=1:NumArray
            Xdata = Xarray{ctArray};
            Ydata = Yarray{ctArray};

            %---Response line UserData
            LineUd = struct('System',NewSystemNames{ctR},'Input',ctin,...
               'Output',ctout,'Array',rguihelper('ind2sub',SizeArray,ctArray));

            Xlim = get(LTIdisplayAxes(ctout,ctin),'Xlim');
            Color = get(LTIdisplayAxes(ctout,ctin),'YColor');
            RH{ctArray}(2,1)=line(Xlim,[0 0],'Parent',LTIdisplayAxes(ctout,ctin),...
               'HandleVisibility','off','HitTest','off','Visible','off',...
               'Color',Color,'LineStyle',':','Tag','ExtraTimeLine');

            %---Set visibility off, then have LTIPLOT turn systems on, as necessary
            RH{ctArray}(1,1)=line(Xdata,Ydata(:,ctout,ctin),'Color',CC,'Marker',MM,...
               'LineStyle',LL,'Tag','LTIresponseLines','Visible','off',...
               'Parent',LTIdisplayAxes(ctout,ctin),'UserData',LineUd,...
               'ButtonDownFcn','rguifcn(''showbox'',gcbf);',...
               'DeleteFcn','delresp(gcbo)');
         end
         LineHandle{ctout,ctin} = RH;
      end
   end
   ResponseHandles{ctR} = LineHandle;
end

%---Set the BackgroundAxes labels
BackAxLabels = {...
      'Title','Impulse Response',...
      'Ylabel','Amplitude',...
      'Xlabel','Time (sec)'};

if ImpFlag
   % Append data to existing IMPPLOT object
   RespObj = pvset(RespObj,'UIContextMenu',ContextMenu,...
      'ResponseHandles',[RH0;ResponseHandles],...
      BackAxLabels{:});
   ImpRespObj.PeakResponseValue = [ImpRespObj.PeakResponseValue;PeakRespVals];
   ImpRespObj.SettlingTimeValue = [ImpRespObj.SettlingTimeValue;SetTimeVals];
   ImpRespObj.response = RespObj;
else
   %---Add the Plot Option Menus
   ContextMenu.PlotOptions.PeakResponse = uimenu(ContextMenu.PlotOptions.Main,...
      'label',xlate('Peak Response'),...
      'Callback',['menufcn(''togglepeak'')']);
   ContextMenu.PlotOptions.SettlingTime = uimenu(ContextMenu.PlotOptions.Main,...
      'label',xlate('Settling Time'),...
      'Callback',['menufcn(''togglesettling'')']);

   RespObj = pvset(RespObj,'ResponseHandles',ResponseHandles,...
      'UIContextMenu',ContextMenu,BackAxLabels{:});
   ImpRespObj.PeakResponseValue = PeakRespVals;
   ImpRespObj.SettlingTimeValue = SetTimeVals;
   ImpRespObj= class(ImpRespObj,'impplot',RespObj);
end

%---Update HG pointer to Response Object
builtin('set',ContextMenu.Main,'userdata',ImpRespObj)
