module OW_combine

use OW_type
use OW_parms_areal

implicit none

contains

!------------------------------------------------------
subroutine owcombine(iwb,intmp_,inset_,nodes_,rand1_,igapx_,igapy_)

integer						:: igapx_,igapy_,iwb
integer,optional					:: nodes_
real						:: rand1_(sog%xm%n,sog%ym%n,wblock%blen(iwb))
integer						:: iw,iz,jxs,ixs,jys,iys,ihx,ihy,kxs,kys
real						:: start,finish
complex 						:: inset_(:,:,:,:)
real						:: intmp_(:,:,:,:,:)
integer, external 					:: omp_get_thread_num,omp_get_num_threads

   !$OMP parallel do private (   iw,iz,ixs,jxs,iys,jys,kxs,kys) schedule(dynamic,1) num_threads(nodes_)
   do iw = 1,wblock%blen(iwb)
      do ixs=igapx_,sog%xm%n-1,ngapx
         jxs=ixs+padtracesx+tapertrx
         kxs=int((ixs-1)/ngapx/1.)+1
         do iys=igapy_,sog%ym%n-1,ngapy
            jys=iys+padtracesy+tapertry
            kys=int((iys-1)/ngapy/1.)+1
            do iz=1,nz
               inset_(jxs:jxs+sog%shx%n-1,jys:jys+sog%shy%n-1,iz,iw)=&
               inset_(jxs:jxs+sog%shx%n-1,jys:jys+sog%shy%n-1,iz,iw)+&
                    cmplx(intmp_(kxs,:,kys,:,iz),0)*exp(cmplx(0,eps*rand1_(ixs,iys,iw)))
            end do
         end do
      end do
   end do
   !$OMP end parallel do

   if (exist_file("inset").and.iwb==1) then
     call to_history("n1",nx,"inset"); call to_history("d1",sog%shx%d,"inset"); call to_history("o1",xmin,"inset")
     call to_history("n2",ny,"inset"); call to_history("d2",sog%shy%d,"inset"); call to_history("o2",ymin,"inset")
     call to_history("n3",nz,"inset") ; call to_history("d3",sog%z%d,"inset") ; call to_history("o3",sog%z%o,"inset")
     call to_history("n4",1,"inset"); call to_history("d4",1.,"inset"); call to_history("o4",0.,"inset")
     call to_history("n5",1,"inset"); call to_history("d5",1.,"inset"); call to_history("o5",0.,"inset")  
     call to_history("esize",4,"inset")
     call to_history("label1","cmp_x","inset")
     call to_history("label2","cmp_y","inset")
     call to_history("label3","depth","inset")
     call srite("inset",real(inset_(:,:,:,1)),4*nx*ny*nz)
   end if

end subroutine 
!---------------------------------------
end module
