function [Gamma,D] = adv(X,Y,cost)
% cost must be a vector of length bits

% Assume they have the same number of bits
[nx, bits]=size(X);
[ny, bits]=size(Y);

% symmetrizing, we will have n x n matrices
n=nx+ny;

% the length of the matrix as a vector
s=n^2;

% First we make the F matrix
F=[zeros(nx,nx) ones(nx,ny);ones(ny,nx) zeros(ny,ny)];

% We will also make use of the complement of F
FC=ones(n,n)-F;

% Now we make the positional matrices
D=zeros(s,bits);
for j=1:nx
 for i=1:ny
   D(j*nx+(j-1)*ny+i,:)= X(j,:)~= Y(i,:);
 end
end
for j=1:ny
 for i=1:nx
   D(n*nx+(j-1)*n+i,:)= Y(j,:) ~= X(i,:);
 end
end

% Target vector c
c=[ones(n,1); zeros((bits+1)*s,1)];

% Constraint Ax=b
A=zeros(1+(bits+1)*s,n+(bits+1)*s);
b(1,1)=1;
b(2:1+(bits+1)*s)=zeros((bits+1)*s,1);

% First we say that Z.*F=1
A(1,n+1:n+s)=vec(F)';

% Now we say that Z is 0 when F is 0
VFC=vec(FC);
for i=1:s
 A(1+i,n+i)=VFC(i);
end

% The semidefinite constraints
for j=1:bits
  for i=1:s
    A(j*s+1+i,n+i)=-1/cost(j)*D(i,j);
    A(j*s+1+i,j*s+n+i)=-1;
  end
end

% the diagonal elements
for j=1:bits
  for i=0:n-1
    A(j*s+2+i*(n+1),i+1)=1;
  end
end

% nonnegativity and semidefinite constraints
K.f=n;
K.l=s;
K.s=n*ones(1,bits);


% We run sedumi
[x,y,info]=sedumi(A,b,c,K);
disp('Adversary bound calculated');
bound=1/(c'*x)
disp('The adversary matrix is');
a = x(1:n).^-.5;
Z=mat(x(n+1:n+s));
Gamma=Z.*(a*a').*F;

