subroutine Newton_Sys (n, x, lnit, xtol, t, f_bdf, kod)
! Solutia unui sistem de "n" ecuatii neliniare: F(X) =0.
! Metoda NEWTON - cu Jacobianul analitic
! Parametri:
! fcn, jfcn: nume subrutne care calculeaza F(X) si jacobianul JF(X)
!            Se declara "external" in programul apelant
! n: numarul ecuatiilor
! lnit: INTRARE/IESIRE: numarul limita/ numarul efectiv de iteratii
! x: tabloul necunoscutelor. La intrare contine aproximatiile initiale.
! f: vectorul coordonatelor functirei F(X)
! xtol: toleranta la delta_x
! kod: INTRARE: cod de tiparire iteratii: =0/#0: Da/Nu.
!   IESIRE: cod de incheiere a iteratiei:
!	0: XTOL atins
!	1: LNIT depasit
!  -1: Pivot < prag in eliminarea Gauss

implicit real(8) (a-h,o-z)

real(8) X(N), ff(n), f_bdf(N), JF(N,N), w(n)	! w = corrections to X.
real(8) A(n,n), b(n)
LOGICAL print_it
real(8) norm

real(8) prag/1E-10/		! pt. elim

!epsX(x1) =1./2**(24 -exponent(x1))

print_it =(kod /= 0)

! Iteratie:
iter =0

100 iter =iter +1

! Calculeaza F si JF:
! ff =membrii 2 - calculate de fcn;
call fcn(t, x, f_bdf)

call jfcn(t, x, jf)

! Matricea A pentru Gauss: JF+ termenii liberi:
A =jf
b =-f_bdf(:)

nb =1
kodPrint =0

call ELIM (n, nb, A, b, prag, kod, kodPrint)
if(kod ==-1) then
lnit =iter
print*, '** Matrice Jacobian singulara'
write(1,*) ' ** Matrice Jacobian singulara'

return
endif

! Corecteaza X:
w = b
x = x + w

! Tiparire valori curente
	if(print_it) then
	call fcn(n, x, f)		! Pentru F(X)
	if(iter ==1) print 90
	print 91, iter, x, f

	if(iter ==1) write(1,90)
	write(1,91) iter, x, f
	endif

90 format(' Iteratia:', t14, 'x ', t<n*16+13>, 'f')
91 format(i6, t10, <n>G16.7, t<n*16+10>, <n>G16.7)

! Test XTOL:
wnorm =norm(n, w)
IF(wnorm <= XTOL) THEN
kod =0
lnit =iter
!if(.not. print_it) call fcn(n, x ,f)
! Tiparire valori curente
!	print*,' Norma corectiei:', wnorm
!	write(1,*) ' Norma corectiei:', wnorm

if(.not. print_it) then
!call fcn(n, x ,f)			! Pentru F(X)
!print *, iter, x, f
endif

ELSEIF(iter == lnit) THEN
kod =1
!	print*,' Norma corectiei:', wnorm
!	write(1,*) ' Norma corectiei:', wnorm

if(.not. print_it) then
!call fcn(n, x, f)
!print *, iter, x, f
endif

ELSE	! Noua iteratie
goto 100

ENDIF

END subroutine Newton_Sys

