subroutine secant(x_1, x0, x1, eps, nit, rad, kod, aa)
! Solutia ecuatiei f(x)=0.
! Metoda "Secanta-modificata": ordin =1.839
! 
! Parametri:
! x_1, x0, x1: 3 aproximatii initiale;
! Metoda: {x_1, x0, x1} --> x2

! eps: toleranta;
! nit: numarul limita de iteratii (intrare)/numarul efectiv (iesire);
! rad: solutia;
! kod - intrare: kod de tiparire (#0) sau nu (=0) a iteratiilor.
!       kod >=2: se tipareste si corectia curenta.
! kod - iesire: cod de incheiere a iteratiei:
!	0: s-a atins toleranta "eps"
!	1: s-a depasit "nit"
!   2: proces stationar
!  -1: procesul este divergent.
!  -2: numitor nul
logical print_it
integer width

real aa(0:nit)	! Tablou pentru toate val. - pt. proces stationar
integer period, per
real num
real eps_f/2E-7/

kod_print =kod
print_it =kod_print /=0
if(print_it) then
print *
    if(kod_print >=2) then
    write(1, '(a)') ' Iteratia    x                 Corectia'
    else
    write(1, '(a)') ' Iteratia    x'
    endif
endif

! Initialize:
aa =0.
aa(0) =x0

iter=0

100	iter=iter+1

! Test numitor nul:
num =DivDif2(x0, x1) +(x1 -x0)*DivDif3(x_1, x0, x1)
if(abs(num) <= eps_f) then
write(1,*) 'numitor:', num;
write(*,*) 'numitor:', num;

kod =-2

x_1 =x0
x0 =x1
x1 =x2

goto 500
endif

!x2 =x1 -f(x1)*(x1-x0)/(f(x1)-f(x0))
!x2 =x1 -f(x1) / ( DivDif2(x0, x1) +(x1 -x0)*DivDif3(x_1, x0, x1) )
x2 =x1 -f(x1)/num

iwi =width(iter)
	if(print_it) then
	print 90, iter, x2
	write(1,90) iter, x2
	    if(kod_print >=2) then
	    write(1,'(4x, 1pE11.4, \)') x2-x1
	    endif
	endif

90	format(/, I9, t13, 1pG14.7, \)

! EPS = atins:
IF(abs(x2-x1) <= eps) THEN
kod =0
goto 500
ENDIF

! Stationar:
! Test Stationar:
aa(iter) =x2		! pt. stationar
per =period(iter, aa, i)

IF(per >0) then
iwiter =width(iter)
iwi =width(i)
iwper =width(per)

	print '(/, a, I<iwiter>, a, I<iwi>, a)', ' x(', iter, ') = x(', i, ')'
	print '(a, I<iwper>)', ' ** Proces stationar de perioada ', per

	write(1, '(/, a, I<iwiter>, a1, \)') ' Iteratia ', iter,': '
	write(1, '(a, I<iwiter>, a, I<iwi>, a)') ' x(', iter, ') = x(', i, ')'
	write(1, '(a, I<iwper>)') ' ** Proces stationar de perioada = ', per

kod =2
goto 500
ENDIF


! Divergenta locala:
IF(abs(x2-x1) > abs(x1-x0)) THEN
!kod =-1

if(print_it) then
print *, ' ** Divergenta locala'
write(1, '(a)') ' ** Divergenta locala'
endif

ENDIF

! Test numar de iteratii:
IF(iter < nit) THEN
goto 200

ELSE
	if(abs(x2-x1) > abs(x1-x0)) then
	kod =-1		! Divergenta
	else
	kod =1		! nit depasit
	endif

goto 500
ENDIF


200 continue		! Iterare - nou pas
x_1 =x0
x0 =x1
x1 =x2
goto 100


500 continue
rad =x2
nit = iter

if(.not. print_it .and. kod ==2 .and. per <=50) then
write(1,*)
do ii =i, iter
write(1, '(I6, t14, G16.7)') ii, aa(ii)
enddo
endif

dif =x2 -x1

print '(/, a, 1pg14.7)',' Corectia curenta = ', dif

if(print_it .or. kod ==2) write(1,'(/)')
write(1, '(a, 1pg14.7)') ' Corectia curenta = ', dif

END subroutine secant


