function [zopt,epsslack,how]=mpconline(MuKduINV,KduINV,Kx,Ku1,Kut,Kr,zmin,rhsc0,Mlim,Mx,Mu1,Mvv,...%Mdd
    rhsa0,TAB,Jm,DUFree,xk,uk1,utarget,r,vKv,...%dKd,
    nu,p,degrees,optimalseq,isunconstr);

% Compute the optimal input sequence by solving a QP problem or analytically

%   Copyright (c) 1998 by Alberto Bemporad, August 24, 1998
%   $Revision: 1.00 $  $Date: 1998/08/24 $
%   $Revision: 1.10 $  $Date: 2001/03/09 $   Added MAXITER

if isunconstr,
    
    % Unconstrained MPC
    
    zopt=-KduINV*(Kx'*xk+Ku1'*uk1+Kut'*utarget+...
        Kr'*r+vKv');%+dKd');
    
    epsslack=0;
    
    how='feasible';
    return
end

% Constrained MPC

% Form matrices for DANTZGMP routine (tableau)
rhsc=rhsc0+Mlim+Mx*xk+Mu1*uk1+Mvv;%+Mdd;
rhsa=rhsa0-[(xk'*Kx+r'*Kr+uk1'*Ku1+vKv+...%dkd+...
        utarget'*Kut),0]';

basisi=[KduINV*rhsa;
    rhsc-MuKduINV*rhsa];

nc=size(rhsc,1);

ibi=-[1:degrees+1+nc]';
ili=-ibi;
maxiter=100; % Max number of iterations allowed
% Get the parameters sent to dantzgmp to the workspace
%if exist('TAB.mat')
%else 
    save TAB TAB
    save basisi basisi
    save ibi ibi
    save ili ili
    save maxiter maxiter
    %end
    
 
% Solves QP
[basis,ib,il,iter]=dantzgmp(TAB,basisi,ibi,ili,maxiter);

%% QP.M solution. Find matrices for QP problem
%%
%H=inv(KduINV);
%f=xk'*Kx+r'*Kr+uk1'*Ku1+vKv+...%dkd+...
%   utarget'*Kut;
%
% .... (to be continued) ....

% TEST: compute max number of iterations
%global ITER
%ITER=max(ITER,iter);

if iter > maxiter,
    disp('Warning: Maximum number of iterations exceeded.')
    disp('         Solution is unreliable. Augment MAXITER. ');
    
elseif iter < 0
   % This should never happen, because there's a slack variable !!!
   % It's just for robustness of the code...
    
    how='infeasible';
    disp('Warning: The constraints are overly stringent. No feasible solution.')
    disp('         Previous optimal sequence will be used.');
    duold=Jm*optimalseq;
    zopt=[duold(1+nu:nu*p);zeros(nu,1)]; % shifts
    
    % Rebuilds optimalseq from zopt
    %free=find(kron(DUFree(:),ones(nu,1))); % Indices of free moves
    free=find(DUFree(:));
    epsslack=Inf; % Slack variable for soft output constraints
    zopt=zopt(free);
    return
end    

% Extract the solution to the QP problem
how='feasible';
zopt=zeros(degrees+1,1);
for j=1:degrees+1
    if il(j) <= 0
        zopt(j)=zmin(j);
    else
        zopt(j)=basis(il(j))+zmin(j);
    end
end
epsslack=zopt(degrees+1); % Slack variable for soft output constraints
zopt=zopt(1:degrees);

% end MPC2.M