program OW3Dmig_areal

! line_search = Option switch for line seaching (1=2-pt,0=simple) 
!      = 0 = none 
!      = 1 = simple 
!      = 2 = 2-point parabolic 
!      = 3 = 2-point parabolic 

use sep 
use OW_type
use OW_grabvel2_areal
use OW_exec_time
use OW_parms_areal
use OW_wei_areal
use OW_mpi
use OWmig_mod
use base_spline_mod


implicit none

real                                          :: start, finish, start1, finish1, start2, finish2
integer                                       :: ni,stat1,i,k,j
real, allocatable                             :: velint(:),vel0(:)
real, allocatable                             :: x(:)
integer                                       :: mpierr,i_r,ierr,status


!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

 call MPI_INIT_(mpierr)
 if (mpierr .ne. MPI_SUCCESS) then
    write(0,*) 'Error starting MPI program. Terminating.'
    call MPI_ABORT_(MPI_COMM_WORLD, wpar%i_mpi, mpierr)
 end if
 call sep_init()
 call owwei_mpi_init()
 call set_no_putch()
 call owparam_mig()
 call owparm_bcast_mig()
 allocate(x(img%z%n*img%xm%n*img%ym%n));x=dble(0.)
 allocate(vel0(nzold*img%ym%n*img%xm%n));vel0=0

 call init_files()

 if (wpar%i_mpi==0) then
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    ! Read velocities
    allocate(velint(v%z%n*v%xm%n*v%ym%n));velint=0
    call sreed("vel",velint,v%z%n*v%xm%n*v%ym%n*4)
    call owgrab_velim(velint,vel0,ni)
    deallocate(velint)

    do i_r=1,wpar%n_mpi-1
       write(0,*) "SENDING picks and velocity to node ",i_r
       call MPI_SEND_(vel0, nzold*img%ym%n*img%xm%n,MPI_REAL,i_r,110,MPI_COMM_WORLD,ierr)
    end do
 else
    call MPI_RECV_(vel0, nzold*img%ym%n*img%xm%n,MPI_REAL,0,110,MPI_COMM_WORLD,status,ierr)
    write(0,*) "Receiving picks and velocity at node ",wpar%i_mpi
 end if

 !----------------------------------------------
 ! Initial velocity model = background velocity
 do k=nzmin,nzmax;do j=1,img%ym%n;do i=1,img%xm%n
    x((k-nzmin)*img%ym%n*img%xm%n+(j-1)*img%xm%n+i)=(vel0((k-1)*img%ym%n*img%xm%n+(j-1)*img%xm%n+i))
 end do;end do;end do

 call steep_mpi_init()
 call fgeval(vel0=x,riteD=.true.,wsave=.true.)

 if (allocated(x)) deallocate(x)
 if (allocated(vel0)) deallocate(vel0)
 call steep_mpi_close()
 call sep_close()
 call MPI_FINALIZE_(mpierr)
end program
