program OWmig2d_par
!#############
!####
!Serio bug no programa
!ainda sem solucao


use sep 
!use omp_lib
use OW_pspi
use OW_fftw
use OW_type
use OW_grabvel
use OW_exec_time
use OW_parms
use OW_image
use OW_sumimg


implicit none

real						:: start, finish
integer						:: ixs,ni,isp,i,stat
real, allocatable					:: velint(:,:),vel(:,:)
complex, allocatable				:: recv(:,:),source(:),GSS(:,:,:),GRR(:,:,:)

 call sep_init()
 call sep_begin_prog()

!---------------------------------------
! IO
!
 call owparam()

!----------------------------------------------------
! Memory Allocation
!
allocate(recv(rec%h%n,rec%w%n),source(sou%w%n),velint(v%z%n,v%xm%n))
allocate(vel(img%z%n,kxm%n))

!--------------------------------------------------
! Reading source fctn and velocity
 call sreed("sou",source,sou%w%n*8)
 call sreed("vel",velint,v%z%n*v%xm%n*4)

!--------------------------------------------------
!
!
write(0,*) "DOWNWARD CONTINUES SOURCES AND RECEIVERS"
write(0,*) "========================================"

open(unit=2,file='log1.txt')
open(unit=3,file='log2.txt')

!--------------------------------------------------
! shot position in the acq.geom.
isp = abs(floor(rec%h%o/rec%h%d)) + 1
write(0,*) isp

!--------------------------------------------------
! Migrating
!
!-----------------------------------------------------------------------------------------------      
shot:do ixs=1,rec%x%n

    start=0.;finish=0. 
    call owexec_time(start)
    call sreed("in",recv,8*rec%h%n*rec%w%n)
    call owgrab_vel(ixs,velint,vel,ni)

    do i=1,size(vel(1,:))
       vel(:,i)=velint(:,1)
    end do

    if (ixs==1.and.exist_file("velo")) then
       call to_history("n2",rec%h%n,"velo");call to_history("d2",rec%h%d,"velo");call to_history("o2",owrk,"velo")
       call to_history("n1",img%z%n,"velo");call to_history("d1",img%z%d,"velo");call to_history("o1",img%z%o,"velo")
       call to_history("esize",4,"velo")
       call srite("velo",vel,4*img%z%n*rec%h%n)
    end if

    call owpspi_init(isp,ni,ixs,wbott)
    call owpspi(recv,source,vel)
    call owexec_time(finish)
    write(0,*) " DONE SHOT # ",ixs," OUT OF ",rec%x%n," in ", (finish - start)/60.," (min)"

!    if (exist_file("GS").and.ixs==1) then
!       do iw=1,rec%w%n
!          call srite("GS",GSS(:,:,iw),8*img%xm%n*img%z%n)
!       end do
!    end if
!    if (exist_file("GR").and.ixs==1) call srite("GR",GRR,8*img%xm%n*img%z%n*rec%w%n)
!    if (exist_file("GS").and.ixs==1) deallocate(GSS)
!    if (exist_file("GR").and.ixs==1) deallocate(GRR)


end do shot
close(2)
close(3)
call sep_end_prog()
end program OWmig2d_par
