function Didss = idss(Dss, Type, NoiseAdjust)
% Conversion to idpack.ssdata.
%
%  Type: 'measured', or 'split'.
%     'measured': Convert to measured model component (K=0).
%     'split':    Split model inputs so that that the last Ny inputs are
%                 treated as noise inputs. Original model must have Ny or
%                 more inputs.
%  NoiseAdjust: Adjust K, if required, to achieve predictor stability.

%   Author(s): Rajiv Singh
%   Copyright 2010-2015 The MathWorks, Inc.

% Note: Parameterization is not configured in any special way.

ni = nargin;
Split = ni>1 && strncmpi(Type,'s',1);
if ni<3, NoiseAdjust = true; end
[Ny, Nu] = iosize(Dss);
Ts = Dss.Ts;

% Reduce internal delays that are simply input or output delays. 
Dss = simplifyDelay(Dss);
if any(Dss.Delay.Output)
   minD = min(Dss.Delay.Output);
   if minD>0
      Dss.Delay.Input = Dss.Delay.Input + minD;
      Dss.Delay.Output = Dss.Delay.Output - minD;
   end
   
   if Ts==0 && any(Dss.Delay.Output)
      ctrlMsgUtils.error('Ident:transformation:CTInternalDelay','idss')
   end
end

if hasInternalDelay(Dss) || any(Dss.Delay.Output)
   if Ts~=0
      ctrlMsgUtils.warning('Ident:transformation:InternalDelaysAreStates')
      if Split && any(Dss.Delay.Input(end-Ny+1:end))
         % Error out because there must be direct feedthrough of
         % disturbance to output.
         ctrlMsgUtils.error('Ident:transformation:NonzeroNoiseInputDelay','IDSS', Ny);
         
         % User alternative:
         % Input delays corresponding to noise sources can be absorbed into
         % system states for DT systems. This would then necessitate
         % separate computation of k using Kalman estimator.
         % id = Dss.Delay.Input; id(1:Nu-Ny) = 0;
         % Dss = elimDelay(Dss,id,[],Dss.Delay.Internal);
      end
      Dss = elimDelay(Dss,[],Dss.Delay.Output,Dss.Delay.Internal);
   else
      ctrlMsgUtils.error('Ident:transformation:CTInternalDelay','idss')
   end
end

try
   [a,b,c,d] = getABCD(Dss);
catch E
   if strcmp(E.identifier,'Control:ltiobject:ssdata1')
      ctrlMsgUtils.error('Ident:transformation:ImproperModel2Idss')
   else
      throw(E)
   end
end
k = zeros(size(a,1),size(d,1));

% If inputs are not 'split', resulting noise variance is eye(Ny).
NV = eye(Ny);
if Split
   % Treat last Ny inputs as stochastic
   Nu = Nu-Ny;
   [b,d,k,NV] = idpack.ssdata.utSplitNoiseMeas(a,b,c,d,Ts,NoiseAdjust);
end

S = pmodel.ss(a,b,c,d,k);
% Copy state names and units if no extra states were added by delay.
if size(a,1)==size(Dss.a,1)
   if ~isempty(Dss.StateName)
      S.StateName = Dss.StateName;
   end
   
   if ~isempty(Dss.StateUnit)
      S.StateUnit = Dss.StateUnit;
   end
end
Didss = idpack.ssdata(S,Ts);
Didss.NoiseVariance = NV;
Didss.Delay.Input = Dss.Delay.Input(1:Nu,:);
Didss = setDefaultParSpec(Didss, Nu, size(a,1));

