! Descompunerea Cholesky: A=L*L_T =S_T*S
! Matricea A = simetrica + pozitiv definita
! Elementele lui L se determina pe coloane.
! Matricea L in locatiile matricii A (stocare compacta)
!
subroutine cholesky_S(n, a, kod)
!common n
real(4) a(n*(n+1)/2)	! A ~S
real(4) sii, sij
integer width


kod =0

! Linia 1:
! Calculeza pentru j=1: S(1,1) and S(1,j):
a(1) =sqrt(a(1))

do j =2,n
jj =loca(1,j)
a(jj) = a(jj)/a(1)
enddo

! Liniile 2-n:
ROW_DO: do i =2,n
sii =0.
	do k =1,i-1
	ki =loca(k,i)
	sii =sii +a(ki)**2
	enddo

ii =loca(i,i)
sii= a(ii) -sii

	! Test pozitiv definita:
	if(sii <=0) then
	iwj =width(j)
	print '(/, a)', ' * Matricea nu este pozitiv definita:'
	print '(a, I<iwj>, a, I<iwj>, a, I<iwj>, a, 1pg15.7)', ' Linia ', i, ': s(', i, ',', i, ') =', sii

	write(1, '(/, a)') ' * Matricea nu este pozitiv definita:'
	write(1, '(a, I<iwj>, a, I<iwj>, a, I<iwj>, a, 1pg15.7)') ' Linia ', i, ': s(', i, ',', i, ') =', sii

	kod =-1
	RETURN
	endif

sii = sqrt(sii)
a(ii) =sii

Col_do: do j =i+1, n
sij =0
	do k= 1,i-1
	ki =loca(k,i); kj =loca(k,j);
	sij = sij +a(ki)*a(kj)
	end do

ij =loca(i,j)
sij =(a(ij) -sij)/sii
a(ij) =sij
enddo Col_do

ENDDO ROW_DO

END subroutine cholesky_S
