program POLALL
! Metoda NEWTON pt. polinoame: numar de 'NR' radacini.
! Prin iterare in polinomul original
! Coeficientii: a_n, ..., a_1, a_0

! FISIER DE DATE (intrare/iesire): nume dat de utilizator.
! 0) Titlul problemei (80 caractere)
! 1) n, n_rad, ktip:
!	n =grad polinom
!	n_rad =numar radacini 0<= nr <=n; nr =0: programul pune nr=n
!	ktip =cod tiparire iteratii: 0 / #0
! 2) Coeficientii polinomului: a_n, a_n-1, ..., a_1, a_0
! 3) EPS, ITMAX: Toleranta; Numarul maxim de iteratii
! 4) x(k),k=1,n_rad: Aproximatiile radacinilor (in numar de "nr")
!
! Rezultatele se scriu in fisier, dupa datele de intrare.

use dfwin

real(4), allocatable :: coef(:), coef_1(:)
real(4), allocatable :: X(:), p(:)
integer, allocatable:: IE(:), nit(:)
character(260) fname, dummy*80
character(100) text(-2:2)
logical printed_code(-2:2)

integer, allocatable:: no_div(:)
integer status
character(80) w_titlu


text(-2)='** Numitor nul'
text(-1)='** Divergenta'

text(0) ='* Toleranta EPS atinsa'
text(1) ='** Numar de iteratii depasit'
text(2) ='** Proces stationar'

!write(*,'(a\)') ' Fisier date: '
!read(*,'(a)') fname

!call GetFile(fname, status, 'Select Data File'C)
w_titlu ='Select Data File'C
call GetFile(fname, status, w_titlu)

if(status ==0) then
print '(a, \)', 'Input File: '
read *, fname
endif

OPEN(UNIT=1, FILE=fname, STATUS='OLD')

read(1,'(a80)') dummy
READ(1,*) N, N_rad, ktip
if(n_rad ==0) n_rad =n
!
allocate (coef(0:n))
allocate (x(1:n_rad), ie(1:n_rad), nit(1:n_rad), &
p(1:n_rad),STAT=ierr)

allocate (no_div(n_rad))
!
read(1,*) (coef(I), I=N,0,-1)
read(1,*) EPS, ITMAX0
READ(1,*) (X(K), K=1,N_rad)

write(*,'(a1, a80)') ' ', dummy

! Coef. derivatei:
allocate (coef_1(0:n-1))

do i = n-1, 0, -1
coef_1(i) =coef(i+1)*(i+1)
enddo


DO K =1,n_rad
X0 =X(K)
itmax =itmax0
ier =ktip

if(ier /=0) then
write(1, '(//, a, 1pg15.7)') ' Aproximatia:', x0
endif

CALL POL_direct(N, coef, coef_1, X0, EPS, ITMAX, RAD, B, IER, n_div)
    X(K) =RAD
    ie(k) =ier
    nit(k) =itmax
	p(k) =b
	no_div(k) =n_div
ENDDO


! Explore divergence:
nd =maxval(no_div)

IF(nd /=0) THEN
write(1,'(//, a)') ' Radacina	    Nr. de divergente locale'

do k=1,n_rad

if(no_div(k) /=0) then
write(1, *) x(k), no_div(k)
endif

enddo
ENDIF

! Write roots:
write(*, '(/, a)') ' ** Radacinile:'

write(1,*)
write(1, '(/, a)') '  ** Radacinile:'
write(1,'(a)') ' Radacina				 Cod	 Iteratii	p(Radacina)'

DO k=1,n_rad
write(*,*) X(K), IE(K), nit(k), '  ', p(k)
write(1,*) X(K), IE(K), nit(k), '  ', p(k)
ENDDO

printed_code =.false.
write(1, '(/, a, a)') ' Cod   Semnificatie'

do k=1,n_rad
iek =ie(k)
if(printed_code(iek)) cycle
write(1,'(I4, 3x, a)') iek, trim(text(iek))
printed_code(iek) =.true.
enddo

lf =lstrlen(fname)
write(*, '(/, a, a)') '* Fisier de iesire: ', fname(1:lf)
END


