! ************************************************************* 
!
!   This is a software package CIAO
!
!     developed as a part of the national project "Research and 
!     Development of Innovative Simulation software",which is   
!     supported by the next-generation IT program of MEXT of Japan
!
!   latest version: 
!
!     4.0:  2013/01/17 
!           codes for spin-polarized pseudopotential generation are added
!
! ************************************************************* 
!
!  Software name : CIAO (Code for Investigating Atomic Orbitals)
!  Subroutine(s) : check_conv
!  Author(s)     : Masakuni Okamoto (August 25, 2003)
!
!  The license of the code and contact address :
!  See the files, COPYRIGHT and LICENSE (or LICENSE_J.pdf)
!
!=====================================================================
   subroutine check_conv(ier,is_conv,loop_scf)
!=====================================================================
!
!  Checks convergence of SCF calculation
!
!  M. Okamoto
!
!---------------------------------------------------------------------  
   use parameters   
   implicit none
   integer,intent(out)   :: ier
   integer,intent(inout) :: is_conv
   integer,intent(in)    :: loop_scf
   integer :: ishell, i
   real(8) :: dee_max, de, tmp
   ier = 0
   is_conv = NO
   do i = nsave_dee-1,1,-1
      dee_save(i+1) = dee_save(i)
   end do
   dee_save(1) = abs((etot_sum-etot_old)/etot_old)
   write(IFLOG,10) '### ETOT ### etot,dee ...', &
      loop_scf, etot_sum, dee_save(1)
   dee_max = dee_save(1)
   if ((loop_scf > nsave_dee).and.(nsave_dee >= 2)) then
      do i = 2,nsave_dee
         dee_max = max(dee_save(i),dee_max)
      end do
   end if
   de = abs(engy(1)-engy_old(1))
   do ishell = 1,nshell
      if (is_solve(ishell) /= 0) then
      tmp = abs(engy(ishell)-engy_old(ishell))
      de  = max(de,tmp)
      end if
   end do
   write(IFLOG,10) '#### DE #### de .........', &
      loop_scf, de
   if ((loop_scf > nsave_dee).and.(dee_max < dee_conv)) then
      is_conv = YES
      write(IFLOG,20) &
        'SCF calculation converged after',loop_scf,'iterations.'
      write(IFSUM,*)
      write(IFSUM,20) &
        'SCF calculation converged after',loop_scf,'iterations.'
   end if
   if (loop_scf > loop_conv) then
      write(IFLOG,30) &
       '### ERROR ### SCF loop count exceeded the limit',loop_conv,'.'
      write(IFSUM,*)
      write(IFSUM,30) &
       '### ERROR ### SCF loop count exceeded the limit',loop_conv,'.'
      ier = 1 ; go to 99
   end if
10 format(1x,a25,i7,2(1pe25.15))
20 format(1x,a31,(1x,i4,1x),a11)
30 format(1x,a47,(1x,i4),a1)
99 continue
   end subroutine check_conv
