!!
!! The routine stacks cmp data
!!
!!

  program Stack

  use sep

  implicit none
  
  integer	  		    :: k,if2,if1
  integer                           :: i1,i2,i3,n1,n2,n3
  real                              :: o1,o2,o3,d1,d2,d3,ang1,ang2
  real,dimension(:,:),allocatable   :: cdp,dado

  call sep_init()
  call sep_begin_prog()

  call from_param("n1",n1)
  call from_param("n2",n2)
  call from_param("n3",n3)
  call from_param("d1",d1)
  call from_param("d2",d2)
  call from_param("d3",d3)
  call from_param("o1",o1)
  call from_param("o2",o2)
  call from_param("o3",o3)


  !! write info out to history file
  call to_history("n1",n1)
  call to_history("n2",1)
  call to_history("n3",n3)
  call to_history("d1",d1)
  call to_history("d2",d2)
  call to_history("d3",d3)
  call to_history("o1",o1)
  call to_history("o2",o2)
  call to_history("o3",o3)

  call from_param("ang1",ang1)
  call from_param("ang2",ang2)
 write (0,*) ang1,ang2
  if (ang1.ne.0.0.or.ang2.ne.0.0) then 
	if2=int((abs(o2)-ang2)/d2)
	if1=int((abs(o2)-ang1)/d2)
  else
	if2=0;if1=0
  endif

!
!! allocate working space
  allocate(cdp(n1,n2),dado(n1,n3))
 
!!
!! 
!!
  do i3=1,n3
	call sreed_window("in",3,(/n1,n2,n3/),(/n1,n2,1/),(/0,0,i3-1/),(/1,1,1/),4,cdp)
  	if (mod(i3,10).eq.1) write(0,*) "CMP  ", i3, " of ", n3
  	do i1=1,n1
	      	k=0
		do i2=1,n2
			if (((i2.ge.if2).and.(i2.lt.if1)).or.((i2.le.if2+int(n2/2)).and.(i2.gt.if1+int(n2/2)))) then
				if (cdp(i1,i2).ne.0.) then
					k=k+1
				end if
				dado(i1,i3)=dado(i1,i3)+cdp(i1,i2)
			end if
		end do
		dado(i1,i3)=dado(i1,i3)/sqrt(float(k))
  	end do
  end do
!!  call srite_window("out",2,(/n1,n3/),(/n1,1/),(/0,i3-1/),(/1,1/),4,dado)
  call srite("out",dado,n1*n3*4)


!! clean up
  deallocate(cdp,dado)

  call sep_end_prog()
  end program Stack
