module nbound{          # mark helix filter outputs where input is off data.
use nhelix
use helixcartmod
contains 
  subroutine nboundn ( nd,  aa){
    integer, dimension(:), intent( in) :: nd # (ndim)
    type( nfilter)                     :: aa
    integer                            :: ip,i_n,i_a
		integer                            :: ndim,npt,lag,n_f,lag_c,i_s
		integer,allocatable,dimension(:)   :: i_f,i_d,i_t,center,i_c
		real,allocatable :: mask(:)
    allocate( aa%mis( product (nd))); aa%mis = .false.


		
	ndim=size(nd)
	npt=product(nd)
	allocate(i_f(ndim),i_d(ndim),i_t(ndim),center(ndim),i_c(ndim))
	center=nd/2
	call cart2helix(nd,center,lag_c)
#	allocate(mask(npt))

	n_f=size(aa%hlx(1)%lag)
	do i_n=1,npt{
 	 	#check location
	  call helix2cart(nd,i_n,i_d)
  	do i_a=1,n_f{
			lag=aa%hlx(aa%pch(i_n))%lag(i_a)
      i_s = i_n - lag
      call helix2cart(nd,i_s,i_f)
      call helix2cart(nd,lag+lag_c,i_t)
      i_t-=center
      i_c=i_d-i_t
      if(any(i_c >nd ) || any( i_c < 1)){
				 aa%mis(i_n)=.true.
			}
    }
  }
	deallocate(i_f,i_d,i_t,i_c)
#	mask=0.
#	where(aa%mis) mask=1.
#	if(nd(1)==12) call srite("mask.H",mask,size(mask)*4)
#	deallocate(mask)



	

#    do ip = 1, size( aa%hlx) { 
#        where( aa%hlx( ip)%mis) aa%mis = .true.
#        deallocate( aa%hlx( ip)%mis)
#           nullify( aa%hlx( ip)%mis)
#		write(0,*) "done ip",ip
#    }
  }
}
