Program Gauss
! Program principal pt. ELIM2
! Cu matricile: "A(n,n)" & "b(n,nb)"
!
! Intrare = Fisier de date:
! 1) Titlu: text <= 80 caractere
! 2) n, nb: nr. de ecuatii; nr. de termeni liberi.
! 3) Matricea coeficientilor "A": n x n (Se scrie asa cum e data - pe linii si coloane).
! 4) Termenii liberi "b": Se scriu pe linii: "nb" linii a "n" termeni liberi.
! 5) Cod_inversare_coeficienti, cod_Tiparire
!	Cod_inversare_coeficienti: #0: a(i,j) -> 1./a(i,j)
!	Cod_Tiparire: #0: Se tiparesc permutarile si pivotii.
! 6) Check_text: text <= 20 charactere. Primul caracter e semnificativ:
!	'C', 'c', 'P', 'p': se face proba "Ax-b".
!
real, allocatable :: A(:,:), B(:,:)
character(260) fname, titlu*80
real prag /1E-6/	! Prag pentru Pivot ~0.
integer width

real, allocatable :: a0(:,:), b0(:,:)
character(20) check_text; logical do_check; 


print '(a,\)', ' Nume fisier de intrare: '
read '(a)', fname
open(1,file=fname,status='old', form ='formatted')

read(1,'(a)') TITLU

! Citeste n, nb:
read(1,*) n,nb

allocate (A(n,n), B(n, nb))

! citeste matricea coeficientilor:
read(1,*) ((A(i,j),j=1,n),i=1,n)

! citeste vectorii termenilor liberi - in numar de NB (pe linii):
read(1,*) ((B(i,j),i=1,n),j=1,nb)

! citeste 'kod':
read(1,*) kodInv, kodPrint

! citeste "Proba"
read(1,*) check_text

do_check =check_text(1:1) =='C' .or. check_text(1:1) =='c' &
		.or. check_text(1:1) =='P' .or. check_text(1:1) =='p'

if(kodInv /=0) then
do i=1,n
do j=1,n
a(i,j) =1./a(i,j)
enddo
enddo
endif

! Pt. Proba:
if(do_check) then
allocate(a0(n,n), b0(n,nb))
a0 =a; b0 =b;
endif

	call ELIM(n, nb, A, B, prag, kod, kodPrint)

if(kod <0) then
write(1, '(/, a, 1pE8.2,a, /,a)') '* Pivot <', prag,' !',&
'* Sistemul nu se poate rezolva.'

write(*, '(/, a, 1pE8.2,a, /,a)') '* Pivot <', prag,' !',&
'* Sistemul nu se poate rezolva.'

goto 500
endif

iwnb =width(nb)

nb_do: do k =1,nb
write(1, '(/, a, I<iwnb>)') ' * Solutia pentru termenii liberi nr. ', k

	n_do: do i=1,n
	iwi =width(i)
	write(1, '(a, I<iwi>, a, G15.7)') ' x(', i, ') = ', B(i,k)
	enddo n_do
enddo nb_do

! Proba: Solutia
Check_if: IF(do_check) THEN
write(1, '(/,a)') '* Proba Ax =b:'

DO kb=1,nb
iwk =width(kb)
if(nb >1) then
write(1, '(/, a, I<iwk>, a)') 'Solutia nr. ', kb, ': A*x -b'
else
if(nb >1) write(1, '(/, a)') ': A*x -b'
endif

!x =b(1:n,kb)

do i=1,n
sum =(0.,0.)
	do k=1,n
	sum =sum +a0(i,k)*b(k,kb)		!x(k)
	enddo

write(1,*) i, sum -b0(i,kb)
enddo

ENDDO
ENDIF Check_if


500 deallocate(A, b)
if(allocated(a0)) deallocate(a0)
if(allocated(b0)) deallocate(b0)

END Program Gauss

