      subroutine totale(nflag,ncntrt,ncd,iter,nbpc,ncentr,nalpha,nbeta,
     &                  ndim,energy,diisv,dmta,dmtb,fock,coord,charge,
     &                  coordpc,pcharge,overcd,cdcoef,dmaxdm)

c  this subroutine written by alain st-amant of the department of
c  pharmaceutical chemistry, university of california, san francisco.
c  all rights reserved.  this is part of the DeFT project.

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

      include "mpif.h"

      dimension istat(mpi_status_size)

      dimension dmta(*),dmtb(*),fock(*)
      dimension coord(3,*),charge(*),coordpc(3,*),pcharge(*)
      dimension overcd(ndim,*),cdcoef(*)

      data zero,half,one,two/0.0d0,0.5d0,1.0d0,2.0d0/

      call mpi_comm_rank(mpi_comm_world,myid,ierr)
      call mpi_comm_size(mpi_comm_world,numprocs,ierr)

      esave=energy

      energy=zero

      do 1001 i=1,ncntrt*(ncntrt+1)/2
 1001 energy=energy+(dmta(i)+dmtb(i))*fock(i)

      rewind 17

      do 1002 i=1,ncd
 1002 if(myid.eq.0) call fastrd(17,overcd(1,i),ncd)

      do 1003 i=1,ncd
      do 1003 j=1,ncd
 1003 energy=energy-half*cdcoef(i)*cdcoef(j)*overcd(j,i)

      do 1004 i=1,ncentr
      do 1004 j=1,i

      rrij=dist(coord(1,i),coord(1,j))

      if(rrij.eq.zero) goto 1004

      energy=energy+charge(i)*charge(j)/rrij

 1004 continue

      if(nbpc.ne.0) then
                          do 1005 i=1,nbpc

                          do 1006 j=1,ncentr
                          if(charge(j).eq.zero) goto 1006
                          rrij=dist(coord(1,j),coordpc(1,i))
                          energy=energy+charge(j)*pcharge(i)/rrij
 1006                     continue

                          do 1005 j=1,i

                          if(i.eq.j) goto 1005

                          rrij=dist(coordpc(1,j),coordpc(1,i))
                          energy=energy+pcharge(j)*pcharge(i)/rrij

 1005                     continue
                    endif

      if(nflag.eq.1) then
                           if(myid.eq.0) write(6,1007) energy 
                           return
                     endif 

 1007 format(/,' - xc terms numerically integrated',/,
     &         ' - gradient corrections perturbatively added',
     &         ' (if requested)',//,
     &         '           gives :         total energy =',f21.9,//)

      if(myid.eq.0) write(6,1008) iter,energy,
     &                            abs(energy-esave),dmaxdm
 1008 format(/,' cycle #',i4,', energy = ',f20.9,4x,
     &         ' |delta E|      = ',e14.7,/,47x,
     &         ' max |delta P|  = ',e14.7)

      if(myid.eq.0) call flush(6)

      return
      end
