      SUBROUTINE STATS(B,FMOD,LEN,BAVE,FMAG,RMS,IFMAG,BAD)
C
      INTEGER*4 IAV(3),IRMS(3),IFMAG
      REAL*4 B(3,LEN),FMOD(LEN),BAVE(3),FMAG,RMS(3)
C
C INITIALIZE VARIABLES
C
      DO IAX = 1,3
       IAV(IAX) = 0
       IRMS(IAX) = 0
       BAVE(IAX) = 0.0
       RMS(IAX) = 0.0
      END DO
      IFMAG = 0
      FMAG = 0.0
C
      DO I = 1,LEN
C
C ACCUMULATE COMPONENT AVERAGES
C
       DO IAX = 1,3
        IF (B(IAX,I).NE.BAD) THEN
         BAVE(IAX) = BAVE(IAX) + B(IAX,I)
         IAV(IAX) = IAV(IAX) + 1
        END IF
       END DO
C
C ACCUMULATE FIELD MAGNITUDE
C
       IF (FMOD(I).NE.BAD) THEN
        FMAG = FMAG + FMOD(I)
        IFMAG = IFMAG + 1
       END IF
C
      END DO
C
C CALCULATE FIELD MAGNITUDE
C
      IF (IFMAG.GT.0) THEN
       FMAG = FMAG/REAL(IFMAG)
      ELSE
       FMAG = BAD
      END IF
C
C CALCULATE FIELD COMPONENT AVERAGES
C
      DO IAX = 1,3
C
       IF (IAV(IAX).GT.0) THEN
        BAVE(IAX) = BAVE(IAX)/REAL(IAV(IAX))
       ELSE
        BAVE(IAX) = BAD
       END IF
C
C ACCUMULATE RMS OF FIELD COMPONENTS
C
       DO I = 1,LEN
C
        IF (B(IAX,I).NE.BAD.AND.BAVE(IAX).NE.BAD) THEN
         RMS(IAX) = RMS(IAX) + (B(IAX,I)-BAVE(IAX))**2
         IRMS(IAX) = IRMS(IAX) + 1
        END IF
C
       END DO
C
C CALCULATE RMS OF FIELD COMPONENTS
C
       IF (IRMS(IAX).GT.0) THEN
        RMS(IAX) = SQRT(RMS(IAX)/REAL(IRMS(IAX)))
       ELSE
        RMS(IAX) = BAD
       END IF
C
      END DO
C
      RETURN
      END
