subroutine regrid()
!---------------------------------------------------------------------------
! 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)
!
!---------------------------------------------------------------------------

use types
use amr
       
INTERFACE

       subroutine flag_candidates()
       use types
       use amr
       end subroutine flag_candidates

       subroutine rgrid2()
       use amr
       use types
       end subroutine rgrid2



END INTERFACE

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


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

! select regions for regridding and create a new cluster structure
! ----------------------------------------------------------------

write(6,*) 'regrid: done with clear_cluster_structure'


  call flag_candidates()

write(6,*) 'done with flag_candidates'

if(verbose) then
write(67,*) 'base level'
write(67,*) lp(crslev)%ml%grid%gfcn(1)%tlev(1)%data(:,4,4)
write(67,*) 'level',curlev
write(67,*) lp(curlev)%ml%grid%gfcn(1)%tlev(1)%data(:,4,4)
endif

if(associated(lp(curlev+1)%clhead)) then
   if(verbose) then
!write(67,*) 'new cluster',lp(curlev+1)%clhead%clrmin,lp(curlev+1)%clhead%clrmax
   endif
else
   if(verbose) then
      write(67,*) '<<< no new clusters >>>'
   endif
   return
endif


! use the cluster structure as a template to generate new mesh
! structure and initialize data on now meshes
! ----------------------------------------------------------------
write(*,*) 'regrid: calling rgrid2'

call rgrid2()

write(*,*) 'regrid: done with rgrid2'


if(.not.verbose) then
write(67,*) 'new structure at level',curlev+1
write(67,*) lp(curlev+1)%ml%grmin
write(67,*) lp(curlev+1)%ml%grmax
write(67,*) lp(curlev+1)%ml%gnr
write(67,*) 'x-coord'
write(67,*) lp(curlev+1)%ml%grid%c(1)%coord
write(67,*) 'y-coord'
write(67,*) lp(curlev+1)%ml%grid%c(2)%coord
do i=1,lp(curlev+1)%ml%gnr(2)
write(67,*) lp(curlev+1)%ml%grid%gfcn(1)%tlev(1)%data(:,i,1)
enddo
endif
write(67,*) ' ---- end of regridding ----'

return
end





