! Power method
! A, w and z - defined in "work"
! Test on:
! kodTest =0: lambda
! kodTest #0: z || z0

subroutine Power(iter, kodTest, ikod, kodNorm, iter_flag, test_val)
use work
real lambda0	! Previous value

integer width
real colin(n); logical mask(n);

colin =0.

! Printing:
IF(ikod /=0) THEN
write(1, '(/, a)') ' Guess vector:'
write(1,*) (w0(j), j=1,n)

itl =14+n*15
write(1, '(/, a, t14, a, t<itl>, a)') ' Iteration', 'Current_vector', 'Current_lambda'
ENDIF

! Normalize guess vector - infinity_norm:
if(kodNorm <=1) then
z0 =w0/vNorm$(n, w0)
else
z0 =w0/vNorm2(n, w0)
endif

lambda0 =0

! Initialize counter:
iter =0

100 iter =iter+1

! Calculate z =Aw
z =matmul(A,z0)


! Calculate "lambda":
imax =maxindex(z)
lambda =z(imax)/z0(imax)

! Normalize z:
if(kodNorm <=1) then

	if(kodTest >=2) test_val2 =vNorm$(n, z-lambda*z0)
z =z/vNorm$(n,z)

else
	if(kodTest >=2) test_val2 =vNorm2(n, z-lambda*z0)
z =z/vNorm2(n,z)

endif


! Iterations printing:
IF(ikod /=0) THEN
write(1, '(I10, <n>g15.7, g15.7)') iter, (z(j), j=1,n), lambda	

ENDIF

! Do at least 2 iterations:
if(iter ==1) then
z0 =z
lambda0 =lambda
goto 100
endif


! Test on |lambda-lambda0| or z||z0:
SELECT CASE(kodTest)

CASE(:0)		! Test "lambda":
test_val =abs(lambda -lambda0)

CASE(1)	! Test z||z0

	IF(kodNorm <=1) THEN

do i=1,n
if(abs(z(i)) <TOL .and. abs(z0(i)) <TOL) then
colin(i) =sign(1., lambda)

else
colin(i) =z(i)/z0(i)
endif

enddo


colin =colin -colin(imax)
test_val =vNorm$(n, colin)

	ELSE
is =sign(1., lambda)
colin =z -is*z0
!write(1,*) 'colin:', colin

test_val =vNorm2(n, colin)
	ENDIF

CASE(2:)	! Test A*z-lambda*z

test_val =test_val2

END SELECT

if(test_val <=TOL) then
iter_flag =0
RETURN

elseif(iter ==lnit) then
iter_flag =-1
RETURN

else
z0 =z
lambda0 =lambda
GOTO 100
endif


end subroutine Power
