C$Procedure FILTER  (Calculates minimal numbers of coefficients to meet
C                    required accuracy)
      SUBROUTINE FILTER ( ITYPE, IVEL, TOL, D, DM, NC)
C Abstract
C     Calculation of minimal number of polynomial coefficients to
C    satisfy given accuracy
C
C$ Declarations
C

      IMPLICIT          NONE
      
      INCLUDE           'ckparam.inc'

      INTEGER           ITYPE  ( * )
      INTEGER           IVEL
      DOUBLE PRECISION  TOL    ( * )
      DOUBLE PRECISION  D      ( QAVSIZ, * )
      DOUBLE PRECISION  DM     ( QAVSIZ, * )
      INTEGER           NC     ( * )

C$ Detailed_Input
C
C      ITYPE   array of criterias for each parameter:
C                ITYPE = 1  mean root deviations
C                ITYPE = 2  module of maximum deviation
C      IVEL    flag if andular velocities are included
C               (IVEL = 1) or not (IVEL = 0)
C      TOL     vector of tolerance (for each component)
C      D       array with mean root deviations
C      DM      array with modules of maximum deviations
C
C$ Detailed_Output
C
C      NC      array with minimal number of coefficients for
C              each parameter
C
C$ Local Parameters

C
C     Parameters from 'ckparam.inc'
C
C     CK4MXD         Max degree of Chebyshev polynomials.
C
C     QSIZ           count of the quaternion components.
C
C     QAVSIZ         count of the quaternion and angular rate 
C                    components together.
C

C
C     Local parameters.
C
C     NCOEFF         Max number of coefficients in each polynomial.
C
C
      INTEGER               NCOEFF
      PARAMETER           ( NCOEFF = CK4MXD + 1 )

C
C     Local variables.
C
      INTEGER           NPAR
      INTEGER           I
      INTEGER           J
      
      LOGICAL           RETURN


      IF ( RETURN () ) THEN
         RETURN
      ELSE
         CALL CHKIN ( 'FILTER' )
      END IF

C
C     Determine number of parameters (QAVSIZ if angular velocities are
C     included or QSIZ if not included)
C
      IF ( IVEL .EQ. 1 ) THEN
         NPAR = QAVSIZ
      ELSE
         NPAR = QSIZ
      END IF

C
C     Cycle for components
C
      DO I = 1,NPAR

         J = 1

C
C     Cycle for number of coefficients
C     Mean root deviation as a criterion
C

         IF ( ITYPE ( I ) .EQ. 1 ) THEN

            DO WHILE ( ( D( I, J ) .GT. TOL( I ) )
     .                  .AND. ( J .LT. NCOEFF ) )
               J = J + 1

            END DO

            NC(I) = J

         ELSE

C
C     max. module of deviat. as a criterion
C     ( case ITYPE(I) = 2)
C
            DO WHILE ( ( DM( I, J ) .GT. TOL( I ) )
     .                    .AND. ( J .LT. NCOEFF ))

               J = J + 1

            END DO

            NC(I) = J

         END IF

      END DO
      
      CALL CHKOUT ( 'FILTER' )
      RETURN
      END
