function [Hq maxloss] = exactlocal(B,Juu,Gy,Gdy)
%Function that solves the exact local method for selection of optimal CV's.
%Run script main.m
%DEH - 2010

[ny,nu]= size(Gy);
nd = size(Gdy,2);
Juuhalf = sqrtm(Juu);
Jn = []; Fn = []; GnyT = [];

GnyT = zeros(nu*nu,nu*ny);
Fn = zeros(nu*ny,nu*(ny+nd));
for i = 1:nu
    GnyT((i-1)*nu+1:i*nu,(i-1)*ny+1:i*ny) = Gy';
    Jn = [Jn;Juuhalf(i,:)'];
    Fn((i-1)*ny+1:i*ny,(i-1)*(ny+nd)+1:i*(ny+nd)) = B;
end

if nnz(Gy(:,1)) == 0 || nnz(Gy(:,2)) == 0
    Hq = NaN*ones(nu,ny);
    maxloss = NaN;
    avgloss = NaN;
else
options = optimset('quadprog');
options = optimset(options,'TolPCG',1e-10,'TolCon',1e-10,'Display','iter');
xn1 = quadprog(Fn*Fn',zeros(size(Fn*Fn',1),1),[],[],GnyT,Jn,[],[],[],options);
Hq = reshape(xn1,ny,nu)';

%normalizing so Euclidean norm of each row = 1
Hq = [Hq(1,:)./sqrt(sum(Hq(1,:).^2)); Hq(2,:)./sqrt(sum(Hq(2,:).^2))]; 

maxloss = 0.5*norm(sqrtm(Juu)*inv(Hq*Gy)*(Hq*B))^2;

end