function uhat=latticedecode(x,H)
% INPUTS: H is an n*n-dimensional lower-triangular matrix with positive
% diagonal elements, such that H=inv(G), where G is the generator matrix of
% the lattice. x is the 1*n-dimensional row vector that you wish to decode.
% OUTPUT: uhat is a 1*n-dimensional vector such that uhat*inv(H)=uhat*G is
% the lattice vector closest to x.
%
% (c) Thomas Eriksson 2009 thomase@chalmers.se
n=size(H,1);
bestdist=999999999999;
k=n;
dist=zeros(n,1);
e=zeros(n,n);
e(k,:)=x*H;
u=round(diag(e));
y=(e(k,k)-u(k))/H(k,k);
step=zeros(n,1);
step(k)=sgn(y);
while 1
newdist=dist(k)+y^2;
if newdist