# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command line>"
# 1 "<stdin>"
module nbound_bob_mod
! mark helix filter outputs where input is off data.
  use nhelix
  use helixcartmod
  implicit none
  contains
  subroutine nbound_bob( nd, bb,extra_mask)
    integer, dimension(:), intent( in) :: nd ! (ndim)
    type( nfilter) :: bb
    type( filter),pointer :: aa
    integer :: ip,i_n,i_a,i,ilen
    integer :: ndim,npt,lag,n_f,lag_c,i_s
    integer,allocatable,dimension(:) :: i_f,i_d,i_t,center,i_c
    integer, optional :: extra_mask(:)
    real,allocatable :: mask(:)
    integer,external :: srite
    logical :: good
    allocate( bb%mis( product (nd)))
    bb%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
    where(nd.eq.1)
      center=1
end where
    call cart2helix(nd,center,lag_c)
    ilen=npt*.1
    do i_n=1,npt
      if (mod(i_n,ilen).eq.1) then
        write(0,*) "      Bounded",nint(real(i_n)/real(npt)*100.),"%&
          & of filter"
      end if
!check location
      call helix2cart(nd,i_n,i_d)
      aa=>bb%hlx(bb%pch(i_n))
      n_f=size(aa%lag)
      i_a=1
      good=.true.
      do while (i_a <= n_f .and. .not. bb%mis(i_n) )
!upper bound
        lag=aa%lag(i_a) !the lag of the filter
        call helix2cart(nd,lag+lag_c,i_t)
        !position of coef if in center of model
        i_t= i_t-center
        !calc relative offset
        i_c=i_d-i_t
        !position of filter coef at this point
        if (any(i_c >nd ) .or. any( i_c < 1)) then
          good=.false.
          bb%mis(i_n)=.true.
! call add_nbound_zero(bb%mis(i_n)%zero, n_f, i_a,i_n)
        end if
!lower bound
        call helix2cart(nd,lag+lag_c,i_t)
        i_t= i_t-center
        i_c=i_d+i_t
        if (any(i_c >nd ) .or. any( i_c < 1)) then
          bb%mis(i_n)=.true.
! call add_nbound_zero(bb%mis(i_n)%zero, n_f, i_a,i_n)
        end if
! if(present(extra_mask)){
! if( extra_mask(i_n + lag) != extra_mask(i_n))
! call add_nbound_zero(bb%mis(i_n)%zero,n_f,i_a)
! }
        i_a= i_a+1
      end do
    end do
! allocate(mask(size(bb%mis)))
! do i_n=1,size(bb%mis){
! if(associated(bb%mis(i_n)%zero)) mask(i_n)=1.
! else mask(i_n)=0
! }
    deallocate(i_f,i_d,i_t,i_c)
  end subroutine
  subroutine add_nbound_zero(zero,nlag,index,iloc)
    logical, pointer :: zero(:)
    integer :: nlag,index,iloc
    if (.not. associated (zero)) then
! write(0,*) "ALLOCATING",nlag,iloc,index
      allocate(zero(nlag))
      zero=.false.
    end if
    zero(index)=.true.
! zero=.true.
  end subroutine
end module
