 module rec_down

 use igrad1

 implicit none

 subroutine downrec(v,shot)

 integer				:: nx,nz,nt,nh
 real					:: dx,dz,dt
 real, dimension, allocatable		:: u(:,:,:), shotd(:,:)
 real, dimension			:: v(:,:), shot(:,:)

allocate(u(nz,nx,nt), shotd(nt,nh))

u=0;shotd=0;

do i=1,nh
	stat=igrad_lop(.true.,.false.,shotd(:,i),shot(:,i))
end do

!
! Inicio dos loops
!
do j=nt:-1:2
    do i=1:nx
        u(1,i,j)=u(1,i,j)+shotd(j,i)
        do k=1:nz
            if j==nt
                T=u(k,i,j)
            else
                T=u(k,i,j+1)-2*u(k,i,j)
            end if
            
            if i==1
                X=dx**(-2)*(u(k,i+1,j)-2*u(k,i,j))
            else if i==nx
                X=dx**(-2)*(-2*u(k,i,j)+u(k,i-1,j))
            else
                X=dx**(-2)*(u(k,i+1,j)-2*u(k,i,j)+u(k,i-1,j))
            end if
            
            if k==1
                Z=dz**(-2)*(u(k+1,i,j)-2*u(k,i,j))
            else if k==nz
                Z=dz**(-2)*(-2*u(k,i,j)+u(k-1,i,j))
            else
                Z=dz**(-2)*(u(k+1,i,j)-2*u(k,i,j)+u(k-1,i,j))
            end if
            
            u(k,i,j-1)=-T+(Z+X)*(v(k,i)*dt)**(2)
            
        end
    end
end
