module adaptive
type ADAPTIVE_MESH
integer :: level
integer :: grid_id
integer :: curmax
type(ADAPTIVE_MESH), pointer :: neighbor
type(ADAPTIVE_MESH), pointer :: parent
type(ADAPTIVE_MESH), pointer :: child
real, dimension(2) :: rmin
real, dimension(2) :: rmax
integer, dimension(2) :: nr
real, dimension(0:2) :: dr 
end type ADAPTIVE_MESH

contains
subroutine allocate_ADAPTIVE_MESH(level,parent,mesh,rmin,rmax,nr,dr)
integer level
type(ADAPTIVE_MESH), pointer  :: parent, mesh
real, dimension(2) :: rmin,rmax
integer, dimension(2) :: nr
real, dimension(0:2) :: dr

type(ADAPTIVE_MESH), pointer :: work

nullify(work)

allocate(mesh)
mesh%parent=>parent
nullify(mesh%child)
nullify(mesh%neighbor)
mesh%rmin=rmin
mesh%rmax=rmax
mesh%nr=nr
mesh%dr=dr
mesh%level=level

if(associated(parent)) then
  if(associated(parent%child)) then 
     work=>parent%child

     DO WHILE (associated(work))
     if(.not.associated(work%neighbor)) then
         work%neighbor=>mesh
         mesh%grid_id=work%grid_id+1
         nullify(work)
     else
         work=work%neighbor
     endif
     ENDDO
  else   
     parent%child=>mesh
     mesh%grid_id=1
  endif
else    
  nullify(mesh%parent)
  if(level <> 1) write(6,*) 'WARNING: (1) orfant grid'
endif
mesh%curmax=mesh%grid_id

return
end subroutine allocate_ADAPTIVE_MESH

end module adaptive
