function [Mdis,Ndis,Vdis,numdis,maxdis]=mpc_discreteconstraints(dset,dvalues,I2Jm,moves)
%#codegen
% Compute data required to enforce discrete constraints on optimization
% variables.
%
% Mdis = transformation matrix to impose discrete constraints:
%        Change of variables: w=Mdis*z where w(i) can only take a finite 
%        set Ndis(i) of values (if Ndis(i)>0). 
%        The values are stored in Vdis(sum(Ndis(1:i-1)+1:sum(Ndis(1:i))
%        Mdis is TotalFreeMoves-by-TotalFreeMoves
% numdis = number of discrete variables (=sum(Ndis>0))
% maxdis = max number of discrete values a variable can take (=max(Ndis))

%   Author: A. Bemporad
%   Copyright 1986-2020 The MathWorks, Inc.

nu=numel(dset);
nmoves=numel(moves);
nz=nu*nmoves;
Mdis=zeros(nz,'like',I2Jm);
Ndis=zeros(nz,1,'like',int16(1));
Vdis=zeros(numel(dvalues)*nmoves,1,'like',I2Jm);
j=0;
k=0;
h=0;
for t=1:nmoves
    nv=0;
    for i=1:nu
        di=dset(i);
        j=j+1;
        if di>0
            Mdis(j,:)=I2Jm(k+i,:);
            Vdis(h+1:h+di)=dvalues(nv+1:nv+di);
            nv=nv+di;
            h=h+di;
        else
            Mdis(j,:)=[zeros(1,j-1) 1 zeros(1,nz-j)];
        end
        Ndis(j)=int16(di);
    end
    k=k+nu*moves(t);
end

numdis=sum(Ndis>0);
maxdis=max(Ndis);
