function StepRespObj = stepplot(RespObj,Systems,X,Y,PlotStyle);
%STEPPLOT Create a Step 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.19 $  $Date: 2000/06/19 21:02:58 $

ni = nargin;

%---Properties
StepRespObj = struct(...
   'PeakResponse','off',...
   'PeakResponseValue',[],...
   'RiseTime','off',...
   'RiseTimeLimits',[],...
   'RiseTimeValue',[],...  
   'SettlingTime','off',...
   'SettlingTimeThreshold',[],...
   'SettlingTimeValue',[],...
   'SteadyState','off',...
   'SteadyStateValue',[]);

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

%---Initialize StepRespObj
StepFlag = isa(RespObj,'stepplot');
if StepFlag
   StepRespObj = RespObj;
   RespObj = StepRespObj.response;
else
   Preferences = get(RespObj,'Preferences');
   StepRespObj.RiseTimeLimits = Preferences.RiseTimeLimits;
   StepRespObj.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 StepFlag
   % Adding to existing STEPPLOT object
   RH0 = get(RespObj,'ResponseHandles');
else
   % New STEPPLOT 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

%---Set initial values for STEPPLOT-specific properties
%--- Assign empty system names. This is how the code knows it needs to calculate
%--- the Plot Options for this particular system (plus the true names are only 
%--- are not yet available in the Viewer case...)
SteadyStateVals = struct('System',cell(NumNewSys,1),...
   'Time',[],'Amplitude',[]);
PeakRespVals = struct('System',cell(NumNewSys,1),...
   'Time',[],'Peak',[]);
RiseTimeVals = struct('System',cell(NumNewSys,1),...
   'RiseTime',[],'Amplitude',[]);
SetTimeVals = struct('System',cell(NumNewSys,1),...
   'SettlingTime',[],'Amplitude',[]);

%---Initialize ResponseHandles array 
ResponseHandles = cell(NumNewSys,1);

for ctR=1:length(ResponseHandles)  % for each new system
   % Get plot data
   Xarray = X{ctR};
   Ytemp = Y{ctR};
   Yarray = Ytemp{1};
   K = Ytemp{2};
   SteadyStateVals(ctR).Amplitude = K;
   TempKtime = zeros(size(K));
   SizeK=size(K);
   for ctTime = 1:max([1, prod(SizeK(3:end))])
      TempKtime(:,:,ctTime)= Xarray{ctTime}(end);
   end
   SteadyStateVals(ctR).Time = TempKtime;

   % Get system dimensions
   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)

   %---Create additional response lines
   LineHandle = 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));

            %---Only add DCgain line for non-array LTI objects
            if isequal(NumArray,1)
               Karray=K(:,:,ctArray);
               Color = get(LTIdisplayAxes(ctout,ctin),'YColor');
               RH{ctArray}(2,1) = line([0 1],[Karray(ctout,ctin) Karray(ctout,ctin)],...
                  'Parent',LTIdisplayAxes(ctout,ctin),'Tag','ExtraTimeLine',...
                  'Visible','off','HandleVisibility','off','HitTest','off',...
                  'Color',Color,'LineStyle',':');
            end

            %---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','Step Response',...
      'Ylabel','Amplitude',...
      'Xlabel','Time (sec)'};

if StepFlag
   % Append data to existing STEPPLOT object
   RespObj = pvset(RespObj,'UIContextMenu',ContextMenu,...
      'ResponseHandles',[RH0;ResponseHandles],...
      BackAxLabels{:});
   StepRespObj.SteadyStateValue = [StepRespObj.SteadyStateValue;SteadyStateVals];
   StepRespObj.PeakResponseValue = [StepRespObj.PeakResponseValue;PeakRespVals];
   StepRespObj.RiseTimeValue = [StepRespObj.RiseTimeValue;RiseTimeVals];
   StepRespObj.SettlingTimeValue = [StepRespObj.SettlingTimeValue;SetTimeVals];
   StepRespObj.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'')']);

   ContextMenu.PlotOptions.RiseTime = uimenu(ContextMenu.PlotOptions.Main,...
      'label',xlate('Rise Time'),...
      'Callback',['menufcn(''togglerise'')']);
   ContextMenu.PlotOptions.SteadyState = uimenu(ContextMenu.PlotOptions.Main,...
      'label',xlate('Steady State'),...
      'Callback',['menufcn(''togglesteady'')']);

   RespObj = pvset(RespObj,'ResponseHandles',ResponseHandles,...
      'UIContextMenu',ContextMenu,BackAxLabels{:});
   StepRespObj.SteadyStateValue = SteadyStateVals;
   StepRespObj.PeakResponseValue = PeakRespVals;
   StepRespObj.RiseTimeValue = RiseTimeVals;
   StepRespObj.SettlingTimeValue = SetTimeVals;
   StepRespObj= class(StepRespObj,'stepplot',RespObj);
end

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