      Subroutine FilterRegres(nobs,ny,yobs,nx,xobs,weity0,
     &weitx,ndim,beta,betamin,betamax,xmin,xmax,
     &iderivative,iregrestype,shorty,shortx,fatbeta)
      implicit none
!Generic Regression with outlier filtering. Use the subroutine GenericRegres. 
!iregrestype=0, ordinary distance regression
!iregrestype=1, orthogonal distance regression. Direct search methods
!  determine the shortest distance within the iteration
!iregrestype=2, orthogonal distance regression. Direct search methods
!  expand the parameter vector to include x positions.
!iregrestype=-1, implicit regression
!iderivative=0, no derivatives provided, using central finite difference
!iderivative=1, derivatives provided.
!If the weity0(i,j) is modified on exit, the corresponding point is detected
!as an outlier
      integer nobs,ny,nx,iderivative,ndim,iregrestype
      double precision yobs(nobs,ny),xobs(nobs,nx),weity0(nobs,ny),
     &weity(nobs,ny),weitx(nobs,nx),xmin(nobs,nx),xmax(nobs,nx),
     &beta(ndim),betamin(ndim),betamax(ndim),shorty(nobs,ny),
     &shortx(nobs,nx),fatbeta,dif_y(nobs),tiny
      parameter(tiny=1.0d-9)
!
      integer i,j,k,m,isoutlier_2sides,iok,ivector(nobs)
!-----------------------------------------------------
      do i=1,nobs
        do j=1,ny
          weity(i,j)=weity0(i,j)
        enddo
      enddo
10    call GenericRegres(nobs,ny,yobs(1:nobs,1:ny),nx,xobs(1:nobs,1:nx),
     &weity(1:nobs,1:ny),weitx(1:nobs,1:nx),ndim,beta,betamin,betamax,
     &xmin(1:nobs,1:nx),xmax(1:nobs,1:nx),iderivative,iregrestype,
     &shorty(1:nobs,1:ny),shortx(1:nobs,1:nx),fatbeta)
      k=0
      do j=1,ny
        iok=0
        do i=1,nobs
          if(dabs(weity(i,j)).gt.tiny)then
!do not consider points with weit = 0 for the purpose of identifying outliers
            iok=iok+1
            ivector(iok)=i
            dif_y(iok)=weity(i,j)*(yobs(i,j)-shorty(i,j))
          endif
        enddo
        m=isoutlier_2sides(iok,dif_y)
        if(m.gt.0)then
          k=k+1
          weity(ivector(m),j)=0.0d0
        endif
      enddo
      if(k.gt.0)goto 10
      return
      end subroutine FilterRegres
!$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
