function [INDX,w,FocusInfo,InfFlag] = sectorresp(D,~,W1,W2,wspec,isPlotted)
% Computes relative sector indices as a function of frequency. 
%
%  [INDX,W,FOCUSINFO] = sectorresp(D,M0,W1,W2,WSPEC,ISPLOTTED) computes 
%  the sector index for a single MIMO model D over some user-defined or 
%  auto-generated frequency grid W. For the R-index (M0=[]), INDX is of 
%  size Nu-by-Nf and contains the generalized singular values of
%  (W1'*H(jw),W2'*H(jw)) at each frequency. 
%
%  WSPEC specifies the frequency grid or range as follows:
%             [] :  none (auto-selected)
%    {fmin,fmax} :  user-defined frequency range (grid spans 
%                   this range)
%         vector :  user-defined frequency grid
%
%  ISPLOTTED is true when the data is used for plotting and false 
%  otherwise (interpolation is used only when ISPLOTTED=true).
%  See FREQFOCUS for details on the contents of FOCUSINFO.

%   Copyright 1986-2016 The MathWorks, Inc.
Ts = abs(D.Ts);
RealFlag = isreal(D);
[w,Focus] = parseFreqSpec(D,wspec,RealFlag && isPlotted);
AutoGrid = isempty(w);   
AutoFocus = any(isnan(Focus));

% Check if H2(s) = W2'*H(s) is minimum phase
InfFlag = ~hasSectorResp(D,W1,W2,Focus);
if InfFlag
   INDX = [];  w = [];  FocusInfo = [];  
   return
end

% Generate frequency grid if none specified
if AutoGrid
   % Use model dynamics to generate grid
   [z,p] = iodynamics(D);
   OPTS = struct('Focus',Focus,'Negative',~RealFlag,...
      'Decades',AutoFocus && ~isPlotted);
   w = freqgrid(z,p,Ts,4,OPTS);
else
   z = [];  p = [];
end

% Compute response and singular values
h = fresp(D,w);
INDX = ltipack.getINDEX(h,W1,W2);

% Pick frequency focus
FocusInfo = freqfocus(Focus,4,w,permute(h,[3 1 2]),z,p,Ts,0,[]);

% Sort frequencies if response is plotted
if isPlotted
   [w,is] = sort(w);  INDX = INDX(:,is);
end
