subroutine regrid(t,finlev)
use gridfunctions
real t
integer level,finlev
integer ngd,igrid

integer, dimension(1) :: id
real, dimension(3,3)    :: tmin,tmax !3 grids; 3d
integer lx,ly,lz
integer nx,ny,nz,finlev_old
type (ADAPTIVE_MESH), pointer :: grid

INTERFACE
subroutine find_minmax(tmin,tmax,lx,ly,lz,nr,level)
use gridfunctions
real, dimension(:,:)    :: tmin,tmax !3 grids; 3d
integer lx,ly,lz
integer, dimension(3) :: nr
integer level
end subroutine find_minmax
END INTERFACE

finlev_old=finlev
if(finlev_old > maxlev-1) finlev_old=maxlev-1

call deallocate_fine_grids

!always start from the base grid

!write(6,*) 'REGRID finlev_old',finlev_old,' ..........................'

do level=1,finlev_old

lx=0
ly=0
lz=0

!write(6,*) 'REGRID on level',level

if(.not.associated(lp(level)%grid)) cycle
ngd=lp(level)%ngd
!write(6,*) 'continue; ngd=',ngd

grid=>lp(level)%grid

if(ngd < 1) then
  write(6,*) 'find_minmax: something wrong, ngd=',ngd
  stop
endif

do igrid=1,ngd

SELECT CASE (level)

CASE (1)

      p=>g1

CASE (2)

      SELECT CASE (igrid)
      CASE (1)
        p=>g21 
      CASE (2)  
        p=>g22
      CASE (3)
        p=>g23
      CASE DEFAULT
        write(6,*) 'find_minmax: cannot handle level',level,' grid',igrid
      END SELECT

CASE (3)

      SELECT CASE (igrid)
      CASE (1)
        p=>g31 
      CASE (2)  
        p=>g32
      CASE (3)
        p=>g33
      CASE DEFAULT
        write(6,*) 'find_minmax: cannot handle level',level,' grid',igrid
      END SELECT

CASE (4)
      
      write(6,*) 'find_minmax: cannot handle level',level
      stop

END SELECT

if(allocated(ctrest)) deallocate(ctrest)
call trunc_error(grid%nr,level)

write(6,*) allocated(g21),allocated(g22),allocated(g23)
write(6,*) allocated(g31),allocated(g32),allocated(g33)
write(6,*) level,igrid,lp(level)%ngd

if(all(ctrest(1,:,:,:) < 0.5)) then
 write(6,*) 'all ctrest < 0.5'
 deallocate(ctrest)
grid=>grid%neighbor 
 cycle
endif


do i=1,3
tmin(:,i)=grid%rmin(i)
tmax(:,i)=grid%rmax(i)
enddo


call find_minmax(tmin,tmax,lx,ly,lz,grid%nr,level)

!write(6,*) 'after minmax',lx,ly,lz
if(level <= maxlev) then 

!write(6,*) 'tmin',tmin(:,2)
!write(6,*) 'tmax',tmax(:,2)

do i=1,lx
do j=1,ly
do k=1,lz
!write(6,*) 'call allocate grid',i,j,k,'level',level+1
call allocate_fine_grid(level+1,tmin(i,1),tmax(i,1),tmin(j,2),tmax(j,2), &
                        tmin(k,3),tmax(k,3),finlev)
enddo
enddo
enddo

endif

if(ly > 0) then
do i=1,ly
write(6,*) 'grid', i, ' on level',level+1
write(6,*) tmin(i,:) 
write(6,*) tmax(i,:)
enddo
else
write(6,*) 'nothing to regrid'
endif 

grid=>grid%neighbor 

!if(.not.associated(grid)) then
!   write(6,*) 'no more grids at this level',level
!   write(6,*) igrid,' of',ngd
!endif

enddo !igrid
enddo !level

if(allocated(ctrest)) deallocate(ctrest)

!write(6,*) 'return from REGRID ........... ..........................'

return
end







