function [x, iter] = eigvechess(H, sigma, x0, tol, maxiter)
%eigvechess Inverse iteration that computes an eigenvector
%given an eigenvalue of the upper Hessenberg matrix H.
%
%   [x iter] = eigvechess(H,sigma,x0,tol,maxiter) computes an
%   eigenvector corresponding to the approximate eigenvalue sigma
%   of the upper Hessenberg matrix H using the inverse iteration method.
%   x0 is the initial approximation, sigma is the approximate
%   eigenvalue, tol is the desired error tolerance, and maxiter is
%   the user-supplied number of iterations.
%   If the algorithm converges, iter contains the number of iterations
%   required. If the method does not attain the error tolerance,
%   iter = -1.

[m, n] = size(H);
if m ~= n
	disp('The matrix is not square.');
	return;
end

xprev = x0;
I = eye(n,n);
[L, U, P] = luhess(H-sigma*eye(n));

for i = 1:maxiter
	% generate the next approximation
   xnew = lusolve(L,U,P,xprev);
	%create a normalized vector xnew by dividing xnew
	%by its magnitude.
	xnew = xnew/norm(xnew);
	% see now close we have come so solving Hx = sigma*x
	if norm((H - sigma*I)*xnew) < tol
		iter = i;
		x = xnew;
		return;
	end
	xprev = xnew;
end

iter = -1;
x = xnew;