function [H,loss,HGy,nmes,ct]= cplex_miqp_decentralized_less_final(Gy,Gdy,Juu,Jud,Wd,Wn,nm,bsy,bsu,bigM,StructCon,Con,fun)
% Use the function cplexmiqp_miqp_full_decentralized to solve a mixed-integer quadratic
% programming problem associated to decentralized structure H case in Self Optimizing Control

[ny,nu]= size(Gy);
nd = size(Gdy,2);
Juuhalf = sqrtm(Juu);
C = inv(Juu)*Jud;
B = [(Gy*C - Gdy)*Wd Wn];
Jn = []; Fn = []; GnyT = [];
for i = 1:nu
    GnyT = daug(GnyT,Gy');
    Jn = [Jn;Juuhalf(:,i)];
    Fn = daug(Fn,B);
end
Jn = Jn;
Fxb = Fn*Fn';
F    = 2*daug(Fxb,zeros(ny,ny));
c    = zeros(size(F,1),1);
M = [];
for i = 1:ny
    M1 = bigM*ones(nu,1);
    M = daug(M,M1);
end
P = []; Hmin = [];
for k = 1:nu
    Hmin = [Hmin;ny*(k-1)+1:ny*k];
end
zy = reshape(Hmin,1,nu*ny);

for zzy = 1:nu*ny
    i = zy(zzy);
    P = [P;zeros(1,i-1) ones(1,1) zeros(1,nu*ny-i)];
end
A1 = [-P -M;P -M];

Aeqs = fun(ny,nu,bsy,bsu);
StCon = [Aeqs zeros(size(Aeqs,1),ny)];

localM = 1e1;
GnewyT = [GnyT zeros(nu*nu,ny)];


localStCon =[zeros(1,ny*nu) ones(1,ny)];


x_L  = [-Inf*ones(nu*ny,1);zeros(ny,1)];
x_U  = [Inf*ones(nu*ny,1);ones(ny,1)];


Aineq = [-P -M;P -M;GnewyT];
Aeq = [StCon;StructCon;localStCon];
bineq = [zeros(2*nu*ny,1);Jn];
beq = [zeros(size(Aeqs,1),1);Con;nm];


for xy = 1:ny*nu
    str(1,xy)='C';
end
for xy = 1:ny
    str(1,ny*nu+xy)='B';
end

ctype = char(str);

options = cplexoptimset;
options.MaxTime = 1200;
options.Diagnostics = 'off';

[x, fval, exitflag, output] = cplexmiqp(F, c, Aineq, bineq, Aeq, beq,...
    [ ],[ ],[ ],x_L,x_U,ctype,[],options);
xn = x;
ct = output.time;
ny = size(Gy,1);
nd = size(Gdy,2);
H = reshape(xn(1:ny*nu),ny,nu)';
C = inv(Juu)*Jud;
F = [(Gy*C - Gdy)*Wd Wn];
loss = norm(sqrtm(Juu)*inv(H*Gy)*(H*F),'fro')^2/(6*(nm+nd));
HGy = H*Gy;
no = (1:ny)'; nsy = xn(nu*ny+1:nu*ny+ny).*no;
nsy(find(abs(nsy) < 1e-3)) = 0;
nmes = round(nonzeros(nsy));

