function [ext_dist] = calc_earth_mover(A1, A2, lowdim); 

len = round(size(A1,2)/lowdim);
f = (1:(len*len))*0.0;
k = 0;
for i=1:len,
  for j=1:len,
    B = A1(:,((i-1)*lowdim+1):(i*lowdim))'*A2(:,((j-1)*lowdim+1):(j*lowdim));
    S = svd(B);
    S_flag = (S < 1.0);
    k = k+1;
    f(k) =  sum(sum((acos(S).*S_flag).^(2)));
  end
end
f=  f';
%A = 0-eye(len*len, len*len);
b = f*0.0;

beq = ((1:(2*len))*0+1)*1/len;

beq = beq';

Aeq = zeros([2*len len*len]);

for i=1:len,
	Aeq(i, ((i-1)*len+1):(i*len)) = Aeq(i, ((i-1)*len+1):(i*len))*0+1;
end
for i=1:len,
	for j=1:len,
		Aeq(i+len, i + (j-1)*len) =1;
        end
end
%keyboard
[x ext_dist]= linprog(f,[],[],Aeq,beq,b);
xx=reshape(x,len,len);
dfrimI=sqrt((sum((max(xx')-1/len).^2)+sum((max(xx)-1/len).^2))/2);
disp([sprintf('Distance from shuffling is %8.6f.',dfrimI)]);
ext_dist = sqrt(abs(f'*x));
%keyboard
return;
% keyboard;
    






