! Inverse Power method - with A^-1
! A, w and z - defined in "work"

subroutine Inverse_Shift(iter, kodTest, kodPrint)
use work
real vnorm2
real lambda0	! Previous value

integer order(n)
real B(n,n)		! A^(-1)

real x(n)		! work vector
real test_val	! test value

real colin(n)
logical do_pvt


! LU decomposition:
!call LUdecomp(A, n, order, kodLU)
kod =0

! Initializeaza ORDER:
do i =1, n
order(i) =i
end do

do_pvt =.true.
kodPivot =1
call LUdecomp(A, n, order, do_pvt, kodPivot, kodLU)

if(kodLU /=0) then
print*, 'Pivot < 1e-7. Stop'
call EXIT
endif

! Define I:
B =0.
do i=1,n
B(i,i)=1
enddo

! Inverse A:
do kb =1, n
x =0.
!call LUsolve(A, B(1:n,kb), x, n, order)
call LUsolve(A, B(1:n,kb), n, x, order)
B(1:n, kb) =x
enddo

! Write B =A^(-1):
IF(koditer /=0) THEN
write(1, '(/, a)') ' A-Inverse:'
do i=1,n
write(1,*) (B(i,j), j=1,n)
enddo
ENDIF


! Normalize guess vector:
z0 =w0/vNorm2(n,w0)

! Printing:
IF(kodPrint >=2) THEN
write(1, '(/, a)') ' Guess vector:'
write(1,*) (z0(j), j=1,n)

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

! Initialize counter:
iter =0

lambda0 =0
z =z0

100 iter =iter+1

! Calculate z =A^(-1)z0
z =matmul(B,z0)

! Calculate "lambda":
! Seek the largest coordinate of vector w:
imax =maxindex(z)
lambda =z(imax)/z0(imax)

! Normalize w:
z =z/vNorm2(n,z)

! Iterations printing:
IF(kodPrint >=2) 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_val =abs(lambda -lambda0)

case default	! Test z||z0
do i=1,n
if(abs(z(i)) <TOL .and. abs(z0(i)) <TOL) then
cycle

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

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

colin(i) =colin(imax)
endif
enddo

!*
!write(1,*) colin
!*
colin =colin - colin(imax)

test_val =vNorm2(n, colin)
end select

if(test_val <= TOL) then
iter_flag =0
write(1,*) 'test_val:', test_val

RETURN

elseif(iter ==lnit) then
iter_flag =-1
write(1,*) 'test_val:', test_val
RETURN

else
z0 =z
lambda0 =lambda
GOTO 100
endif


500 continue
end subroutine Inverse_Shift
