!	kod	: -INTRARE: cod de tiparire a iteratiilor: 0 = Nu; #0 = Da.
!       : -IESIRE : cod de terminare/eroare:
!		 0:	toleranta "eps" atinsa;
!		 1:	depasirea nr.maxim de iteratii admis "lnit";
!        2: Proces stationar;
!		-1: divergenta
!       -2:	derivata functiei in X0 este ~ nula.

subroutine LAG(x01, eps, niter, z, kod1, kod_print)
use comun


!real(4) coef(0:n)
!real(4) coef_1(0:n-1), coef_2(0:n-2)

complex(4) x01, z
complex(4) sH, cor
complex(4) den_plus, den_minus, den
complex(4) zpolval, polval_0, polval_1, polval_2
logical is_Complex
integer width

complex(4) aa(0:niter)	! Tablou pentru toate val. - pt. proces stationar
integer period_z, per
character(40) stat_text, cor_text
character(20) iter_text, iterx_text, rad_text
logical PrintIterations

if(rom) then
iter_text =' Iteratia'
iterx_text =' Iteratia     x'
stat_text =' ** Proces stationar de perioada ='
cor_text =' Corectia ='
rad_text ='Radacina nr.'
else
iter_text =' Iteration'
iterx_text =' Iteration    x'
stat_text =' ** Stationary Process of Period ='
cor_text =' Correction ='
rad_text ='Root No.'
endif


nlim =niter
z =x01
cor =1.

aa(0) =x01

!iter1 =0
PrintIterations =kod_print /=0

do_1: do iter1 =1, nlim
!iter1 =iter1+1

polval_0 =zpolval(n, coef, z)
polval_1 =zpolval(n-1, coef_1, z)
polval_2 =zpolval(n-2, coef_2, z)

!H =(n-1)*((n-1)*polval_1*polval_1 -n*polval*polval_2)
sH =csqrt( (n-1)*((n-1)*polval_1*polval_1 -n*polval_0*polval_2) )

den_plus  =polval_1 +sH
den_minus =polval_1 -sH

if(abs(den_plus) > abs(den_minus)) then
den =den_plus
else
den =den_minus
endif

cor =n*polval_0/den
z =z -cor

! Print iterations:
iwiter =width(iter1)
if(PrintIterations) then

if(iter1 ==1) then
write(1,'(/,a, I3)') trim(rad_text), i_rad
if(i_rad ==1) write(1, '(a)') trim(iterx_text)
endif

    if(is_Complex(cor)) then
    write(1,90) iter1, z
    else
    write(1,91) iter1, real(z)
    endif
endif

90	format(I9, t13, (1pG14.7,1pG14.7))
91	format(I9, t13, 1pG14.7)

! Test proces stationar:
aa(iter1) =z		! pt. stationar
per =period_z(iter1, aa, ii)

IF(abs(cor) <=eps) THEN
kod1 =0
if(kod_print /=0) then
   if(is_Complex(cor)) then
write(1, ' (a, (1pE10.3,1pe10.3) )') trim(cor_text), cor
    else
 write(1, '(a, 1pE10.3, 3x, a, I<iwiter>)') trim(cor_text), real(cor)
   endif
endif

niter =iter1
exit do_1

ELSEIF(per >0) THEN
kod1 =2
iwiter =width(iter1)
iwper =width(per)
iwii =width(ii)
	write(1, '(/, a, I<iwiter>, a, \)') trim(iter_text)//' ', iter1,': '
	write(1, '(a, I<iwiter>, a, I<iwii>, a)') ' z(', iter1, ') = z(', ii, ')'
	write(1, '(a, I<iwper>)') trim(stat_text)//' ', per

niter =iter1
exit do_1

ELSEIF(iter1 ==nlim) THEN
kod1 =1
ENDIF

enddo do_1

end
