module adaptive
use types
use parameters
integer, parameter  :: AMPL=1,ESTRE=2

type ADAPTIVE_MESH
integer :: level
integer :: grid_id
type(ADAPTIVE_MESH), pointer :: neighbor
type(ADAPTIVE_MESH), pointer :: sibling
type(ADAPTIVE_MESH), pointer :: parent
type(ADAPTIVE_MESH), pointer :: child
real, dimension(3)           :: rmin
real, dimension(3)           :: rmax
integer, dimension(3)        :: nr 
real t
end type ADAPTIVE_MESH

type LEVEL_INFO
type(ADAPTIVE_MESH),pointer :: head
integer                     :: curmax
real                        :: threshold
real,dimension(0:3)         :: dr
end type LEVEL_INFO

type(LEVEL_INFO), dimension(maxlevel), SAVE :: lp

contains

subroutine allocate_LEVEL_INFO

do i=1,maxlevel
nullify(lp(i)%head)
lp(i)%curmax=0
lp(i)%dr(1)=dx/(rho**(i-1))
lp(i)%dr(2)=dy/(rho**(i-1))
lp(i)%dr(3)=dz/(rho**(i-1))
lp(i)%dr(0)=lp(i)%dr(1)*dtbydr
write(6,*) i,lp(i)%dr
enddo

lp(1)%threshold=0.25
lp(2)%threshold=0.45
lp(3)%threshold=0.65
!lp(4)%threshold=100.0
!lp(5)%threshold=100.0

return
end subroutine allocate_LEVEL_INFO


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

type(ADAPTIVE_MESH), pointer :: work

nullify(work)

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

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

     DO WHILE (associated(work))
     if(.not.associated(work%sibling)) then
         work%sibling=>mesh
         mesh%grid_id=work%grid_id+1
         work=>work%sibling%sibling
     else
         work=>work%sibling
     endif
     ENDDO
  else   
     parent%child=>mesh
     mesh%grid_id=1
  endif
else    
  nullify(mesh%parent)
  mesh%grid_id=1
  if(level <> 1) write(6,*) 'WARNING: (1) orfant grid'
endif
lp(level)%curmax=mesh%grid_id
write(6,*) 'end of allocate_ADAPTIVE_MESH:',lp%curmax
if(.not.associated(lp(level)%head)) lp(level)%head=>mesh
return 
end subroutine allocate_ADAPTIVE_MESH

end module adaptive

