function model = mpc_chkcustomdistmodel(model,required_outputs,required_ts,type,varargin)
% MPC_CHKOUTDISTMODEL check a custom output or input disturbance model and
% convert it to discrete-time, state-space, delay-free form.  If optional
% scaling factor is provide, return a dimensionless model.

% A. Bemporad, N L Ricker, R. Chen
% Copyright 2001-2014 The MathWorks, Inc.

verbose = mpccheckverbose;

% convert static gain to LTI
if isa(model,'double')
    if ~isreal(model)
        ctrlMsgUtils.error('MPC:utility:ComplexODModel')
    end
    model = ss(model);
end

% convert id model to SS:
if isa(model,'idParametric')
    if verbose
        fprintf('-->%s\n',ctrlMsgUtils.message('MPC:object:ConvertIDToSS'));
    end
    model = ss(model);
end

% error out if not an LTI:
if ~isa(model,'lti')
    ctrlMsgUtils.error('MPC:utility:InvalidDistModel',type,required_outputs);        
end

% error out if not an LTI:
outnum = size(model,1);
if outnum ~= required_outputs
    ctrlMsgUtils.error('MPC:utility:InvalidDistModel',type,required_outputs);        
end

% convert LTI to SS
if ~isa(model,'ss')
    model=ss(model);
    if ~isempty(model)
        % Use DARE to test detectability
        if ~mpc_chkdetectability(model.A,model.C,model.Ts)
            model = sminreal(model);
        end
    end
end

% convert to discrete time (required_ts)
nts = model.Ts;
if nts==0
    model = c2d(model,required_ts);  
elseif abs(required_ts-nts)>1e-10
    % required_ts is different from nts
    if verbose
        fprintf('-->%s\n',ctrlMsgUtils.message('MPC:object:ResampleUMDModel',type,sprintf('%0.4g',required_ts)));
    end
    try
        model = d2d(model,required_ts);
    catch ME
        ctrlMsgUtils.error('MPC:utility:InvalidDistModelD2D',ME.message);        
    end
    % takes out possible imaginary parts
    set(model,'a',real(model.a),'b',real(model.b));
end

% convert delay to states
if hasdelay(model)
    if verbose     
        fprintf('-->%s\n',ctrlMsgUtils.message('MPC:object:ConvertDelayToSS',type));
    end
    model = absorbDelay(model);
end   

% convert to dimensionless if scale factor is provided
if nargin==5
    % Convert to dimensionless form for storage in MPCstruct.  
    %
    % If "type" is 'Input', the "model" has units consistent with the plant
    % input disturbances.  Thus "scalefactor" must contain the scale
    % factors for those inputs. 
    %
    % If "type" is 'Output', the "model" has units consistent with the
    % plant model outputs.  Thus "scalefactor" must contain the scale
    % factors of all the outputs.
    scalefactor = varargin{1};
    ScaleM = diag(1./scalefactor);
    model.c = ScaleM*model.c;
    model.d = ScaleM*model.d;
end