function [sys,SystemName,PlotStyle,iextra] = rfinputs(caller,InNames,varargin)
%RFINPUTS  Parse input list for time and frequency response functions.
%
%   RFINPUTS parses the argument list for the various time and 
%   frequency response functions.
%
%   LOW-LEVEL UTILITY.

%   Copyright 1986-2000 The MathWorks, Inc.
%   $Revision: 1.9 $  $Date: 2000/06/16 21:46:34 $

% Valid syntax:
%    respfun(sys_1,PlotStyle_1,...,sys_k,PlotStyle_k,extra)
%    respfun(sys_1,...,sys_k,PlotStyleStruct,extra)

% Identify input argument of class LTI 
ni = length(varargin);
InputClass = zeros(1,ni);
for j=1:ni,
   argj = varargin{j};
   if isa(argj,'lti'),
      InputClass(j) = 1;
   elseif isa(argj,'char') & ~any(strcmpi(argj,{'inv','zoh','foh'}))
      InputClass(j) = -1;
   end
end

% Extract LTI systems and their names
isys = find(InputClass>0);
sep = isys(2:end)-isys(1:end-1);
if isempty(isys) | any(sep>2)
   error('Invalid syntax.')
end
sys = varargin(isys);
nsys = length(sys);
SystemName = cell(nsys,1);
SystemName(1:nsys) = InNames(isys);

% Find plot style specifiers if any, and build plot style structure.
% RE: PlotStyle.Color = [] for models with unspecified plot style
lastsys = isys(end);
if ni>lastsys & isa(varargin{lastsys+1},'struct')
   % Plot styles specified all at once in a structure
   istyle = lastsys+1;
   PlotStyle = varargin{istyle};
   if length(PlotStyle)~=nsys,
      error('Length of PlotStyle structure is inconsistent with number of systems.')
   elseif ~isfield(PlotStyle,'Legend')
      try
         PlotStyle(1).Legend = '';
         DefStyle = find(~cellfun('isempty',{PlotStyle.Color}));
         PlotStyle(DefStyle) = StyleFinish(PlotStyle(DefStyle));
      catch
         error('Invalid plot style structure.')
      end
   end
   
else
   istyle = find(InputClass(1:min(ni,lastsys+1))<0);
   PlotStyle = struct('Color',cell(nsys,1),'LineStyle',[],'Marker',[],'Legend',[]);
   if isequal(istyle,isys+1),
      % Color/linestyle/marker specified as strings
      StyleStr = varargin(istyle);
      DefStyle = find(~cellfun('isempty',StyleStr));
      for i=DefStyle(:)',
         % Parse color/linestyle/marker string
         [PlotStyle(i).LineStyle,CC,PlotStyle(i).Marker,msg] = colstyle(StyleStr{i});
         if ~isempty(msg)
            error(sprintf('Invalid plot style specifier "%s"',StyleStr{i}))
         end
         if isempty(CC)
            CC = 'blue';
         elseif strcmp(CC,'k'),
            CC = 'black';
         end
         PlotStyle(i).Color = CC;
      end
      PlotStyle(DefStyle) = StyleFinish(PlotStyle(DefStyle));
   elseif ~isempty(istyle)
      error('Invalid mix of LTI models and plot styles.')
   elseif any(sep>1)
      error('Invalid syntax.')
   end
end

% Extra input arguments
iextra = (max(isys)+1+(~isempty(istyle)):ni);
if length(iextra)>1 & ...
      ~any(strcmp(caller,{'ltiview';'sigma';'initial';'lsim'}))
   error('Invalid syntax.')
end

% Check system dimension compatibility and remove empty models from system list
if ~any(strcmp(caller,{'sigma';'initial';'lsim';'pzmap'}))
   refsize = size(sys{1});
   EmptySys = zeros(nsys,1);
   for j=1:nsys,
      sj = size(sys{j});
      if any(sj(1:2)~=refsize(1:2))
         error('All models must have the same number of inputs and outputs.')
      end
      EmptySys(j) = any(~sj);
   end
   EmptySys = find(EmptySys);
   sys(EmptySys) = [];
   SystemName(EmptySys) = [];
   PlotStyle(EmptySys) = [];
end

% Test for properness for the time responses
if any(strcmp(caller,{'step';'impulse';'initial';'lsim'}))
   for j=1:length(sys)
      if ~isproper(sys{j})
         error('Not supported for improper systems.')
      end
   end
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function PlotStyle = StyleFinish(PlotStyle)
% RE: All plot styles are assumed to be user specified at this point

% Load appropriate color table
rgb = isa(PlotStyle(1).Color,'double');
if rgb,
   % Colors specified as RGB triplets
   ColorTable64 = rguicolors(64);
else
   ColorTable8 = rguicolors(8);
end

% Finishing touches
for i=1:length(PlotStyle)
   % Color handling
   CC = PlotStyle(i).Color;   
   if rgb,
      % Identify color name
      Cstr = GetColorName(CC,ColorTable64);
   else
      % Get RGB value and full name for string color (one of eight basic colors)
      Cind = find(strncmpi(CC,ColorTable8(:,2),length(CC)));
      if isempty(Cind)
         error(sprintf('Invalid color specifier "%s"',CC))
      else
         [PlotStyle(i).Color,Cstr] = deal(ColorTable8{Cind(1),:});
      end
   end
   
   % Resolve unspecified line styles and markers
   if isempty(PlotStyle(i).Marker)
      PlotStyle(i).Marker = 'none';
      if isempty(PlotStyle(i).LineStyle)
         PlotStyle(i).LineStyle = '-';
      end
   elseif isempty(PlotStyle(i).LineStyle),
      PlotStyle(i).LineStyle = 'none';
   end
   
   % Build legend
   PlotStyle(i).Legend = legdstr(Cstr,PlotStyle(i).LineStyle,PlotStyle(i).Marker);
end   


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function name = GetColorName(rgbcolor,ColorTable64)

if ~isa(rgbcolor,'double') | length(rgbcolor(:))~=3
   error('RGB color must be a 3 element numeric vector.')
elseif any(rgbcolor(:)<0) | any(rgbcolor(:)>1)
   error('RGB values must be between 0 and 1.')
end

% Preprocessing
if min(rgbcolor)>0.9,
   rgbcolor = [1 1 1];
elseif max(rgbcolor)<0.5
   rgbcolor = [0 0 0];
elseif max(abs(rgbcolor-mean(rgbcolor)))<0.1
   rgbcolor = mean(rgbcolor) * [1 1 1];
end

AllRGBs = cat(1,ColorTable64{:,1});
gaps = sum(abs(AllRGBs - rgbcolor(ones(length(ColorTable64),1),:)).^2,2);
[garb,imatch] = min(gaps);

name = ColorTable64{imatch,2};




