
module lopef {            # Local PEF estimation in patches.
  use patch		  # Estimate a vector of filters, one for each patch.
  use misinput
  use pef
contains
  subroutine find_lopef( wall, aa, npatch, nwall, nwind, mask) {
    optional                                 :: mask
    integer,       dimension(:), pointer     :: npatch, nwall, nwind
    real,          dimension(:), intent( in) :: wall, mask
    type( filter), dimension(:)              :: aa
    real,          dimension(:), pointer     :: windata, winmask
    integer			             :: i, stat
                        allocate( windata( product( nwind)))   # a patch
    if( present( mask)) allocate( winmask( product( nwind)))   # missing inputs	
    call patch_init( npatch, nwall, nwind)
    do i = 1, product( npatch) {                	       # do all patches
       stat = patch_lop( .false., .false., wall, windata)      # get a patch
       if( present( mask)) {
	   stat = patch_lop( .false., .false., mask, winmask)
	   call find_mask( (winmask /= 0.), aa (i))             # missing data
           }
       if( count(.not.aa(i)%mis) > size(aa(i)%lag))             # enuf eqns?
       	  call find_pef( windata, aa(i), niter=size( aa(i)%lag)) # find PEF
       else if( i > 1) 
          aa(i)%flt = aa(i-1)%flt				# use last PEF
       call patch_close()
       }
    deallocate( windata)
    if( present( mask))  deallocate( winmask)
    }
}
#       if( size(aa(i)%mis) - count(aa(i)%mis) > size(aa(i)%lag)) # enuf eqns?
