subroutine regrid(lp,curlev,finlev)
!---------------------------------------------------------------------------
! regridding driver: replaces all meshes at level curlev+1 up to finlev
! by a new structure. Depending on truncation errors at given time, the
! new structure may be empty (i.e. no meshes at level curlev+1 or finer)
! or new meshes are created up to level finlev+1 (but no finer than maxlev)
!
! curlev: level of the mesh hierarchy at which the routine is called
! finlev: the finest refinement level currently defined
!         it is updated by subroutine rgrid 
!
! user and/or application dependent code is buried in subroutines
! flag candidates (truncation error estimation) and 
! rgrid2 (data initialization/boundary conditions on newly ceated meshes)
!
! AUTHOR: Tom Haupt, NPAC at Syracused University, haupt@npac.syr.edu
!---------------------------------------------------------------------------

use types
use amr
type(LEVEL_INFO), dimension(maxlev) :: lp
integer(I4B) curlev,finlev
       
INTERFACE

       subroutine flag_candidates(lp,curlev,finlev)
       use types
       use amr
       type(LEVEL_INFO), dimension(maxlev) :: lp
       integer(I4B) curlev,finlev   
       end subroutine flag_candidates

       subroutine rgrid2(lp,curlev,finlev)
       use amr
       use types
       type(LEVEL_INFO), dimension(maxlev) :: lp
       integer(I4B) curlev,finlev
       end subroutine rgrid2

END INTERFACE

if(curlev.eq.maxlev) then
  write(6,*) 'REGRID: should not be calling routine',&
             ' at finest allowable level'
  write(6,*) curlev,maxlev
  stop
endif

! get rid off the cluster structure from the previous regridding
! ----------------------------------------------------------------
  call clear_cluster_structure(lp)

! select regions for regridding and create a new cluster structure
! ---------------------------------------------------------------- 
  call flag_candidates(lp,curlev,finlev)

! use the cluster structure as a temlate to generate new mesh
! structure and initialize data on now meshes
! ----------------------------------------------------------------
call rgrid2(lp,curlev,finlev)

return
end





