      program jacobi
      use mod_script
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!     diagonalisation jacobi d'une matrice de casdi (calcul='M')
!     '&JACOBI
!     mat=fichier 'prefix.mat'
!     ndim= dimension de la matrice (facultatif, recalcule si =0)
!     nvec
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
      implicit real(8) (a-h,o-z)
      integer,parameter :: ngru3=2048
      real(4) a(ngru3)
      integer,dimension(ngru3) :: imat,jmat
      character(10000) namel
      character(80) mat
      double precision,allocatable,dimension(:,:) :: aa,v,v1
      double precision,allocatable,dimension(:) :: e
      !
      ndim=0
      imat=0
      jmat=0
      nvec=10
      call LECNAM('&JACOBI ',namel,5,ierr,1)
      call namela(namel,mat,'MAT')
      call nameli(namel,NDIM,'NDIM',4)
      call nameli(namel,NVEC,'NVEC',4)
      !
      open(1,file=mat,status='old',form='unformatted')
      if(ndim==0) then
         do
            read(1)imat,jmat
            ifin=ngru3
            if(imat(ifin)==-1) ifin=jmat(ifin)
            ndimv=ndim
            ndim=max(ndim,maxval(imat(1:ifin)))
            ndim=max(ndim,maxval(jmat(1:ifin)))
            if(ndim.ne.ndimv) print*,'ndim',ndim
            if(imat(ngru3)==-1) exit
         enddo
         print*,'ndim retrouve grace au fichier mat',ndim
      endif
      allocate (aa(ndim,ndim),v(ndim,ndim))
      allocate (e(ndim))
      rewind 1
      aa=0.d0
      do
         read(1)imat,jmat,a
         ifin=ngru3
         if(imat(ifin)==-1) ifin=jmat(ifin)
         do k=1,ifin
            i=imat(k)
            j=jmat(k)
            print*,i,j,a(k)
            aa(i,j)=aa(i,j)+a(k)
            aa(J,i)=aa(J,i)+a(k)
         enddo
         if(imat(ngru3)==-1) exit
      enddo
      call mscript(aa)
      call hdiag(aa,v,ndim,ndim)
      call mscript(aa)
      print*,'essai'
      call script(aa,ndim,ndim,ndim,ndim)
      kk=0
      do k=ndim,1,-1
         kk=kk+1
         e(kk)=aa(k,k)
         print*,'k,kk,e',k,kk,e(kk),aa(k,k)
      enddo
      print*, 'energies'
      print*, e
      print'(10f8.4)',e(1:nvec)
      v=v(:,(/(k,k=ndim,1,-1)/))
      call mscript(v(:,1:nvec))
      end

            

      
