      SUBROUTINE DTREND(Q,NQ)   
C   
C     ROUTINE TO REMOVE ALL LOW FREQUENCY TRENDS IN Q. THE TECHNIQUE
C     INVOLVES CHOOSING A SMOOTHING LENGTH. THEN, ARRAY Q IS SMOOTHED   
C     WITH THIS SMOOTHING LENGTH AND THE RESULT IS DIVIDED INTO THE 
C     UNSMOOTHED ARRAY Q TO LEAVE THE HIGH FREQUENCIES INTACT. IN FACT  
C     THE WAY I HAVE IMPLEMENTED IT IS TO STORE NSMOTH POINTS OF Q IN   
C     ARRAY RING AND SUCCESSIVELY UPDATE THIS RING AS THE SMOOTHING 
C     PROCEEDS. 
C   
C     LATER ADDITION: IF NSMOTH<0, SUBTRACT THE SMOOTHED VERSION
C     RATHER THAN DIVIDE IT
C
      DIMENSION Q(1),RING(5000)  
      ISUB=0
      READ *,NSMOTH 
      IF(NSMOTH.LT.0)THEN
C
C       THIS OPTION SUBTRACTS THE SMOOTHED SPECTRUM INSTEAD OF
C       DIVIDING IT OUT (ISUB=0)
C
        ISUB=1
        NSMOTH=-NSMOTH
      END IF
      IF(NSMOTH.EQ.999)THEN
C
C       THIS OPTION REPLACES THE DATA BY THE SMOOTHED SPECTRUM
C
        READ *,NSMOTH
        ISUB=-1
      END IF
      IF(NSMOTH.GT.1000)NSMOTH=1000   
      IF(NSMOTH.EQ.0)NSMOTH=25  
      IF(NSMOTH.GT.NQ)NSMOTH=NQ 
      NSMOTH=(NSMOTH/2)*2+1 
      PRINT 10,NSMOTH   
   10 FORMAT(12X,'DETRENDING WITH A SMOOTHING LENGTH OF ',I5)   
      IF(ISUB.EQ.1)PRINT 11
   11 FORMAT(12X,'SUBTRACTING THE SMOOTHED SPECTRUM')
      IF(ISUB.EQ.0)PRINT 12
   12 FORMAT(12X,'DIVIDING THE SMOOTHED SPECTRUM')
C   
C     FIRST FILL THE RING WITH NSMOTH POINTS OF Q AND SUM IT
C   
      RINGSM=0.0
      DO 20 I=1,NSMOTH  
        RINGSM=RINGSM+Q(I)  
        RING(I)=Q(I)
   20 CONTINUE  
      IEND=1
      IBEG=NSMOTH   
C   
C     NOW DO THE SMOOTHING  
C   
      DO 50 I=1,NQ  
        IF(I.LE.NSMOTH/2+1.OR.I.GE.NQ-NSMOTH/2)THEN 
          IF(ISUB.EQ.0)THEN
            Q(I)=Q(I)*NSMOTH/RINGSM   
          ELSE IF(ISUB.EQ.1)THEN
            Q(I)=Q(I)-RINGSM/NSMOTH
          ELSE IF(ISUB.EQ.-1)THEN
            Q(I)=RINGSM/NSMOTH
          END IF
          GO TO 50  
        ELSE
C   
C         KNOCK OFF THE END POINT FROM THE RING 
C   
          RINGSM=RINGSM-RING(IEND)  
          IEND=IEND+1   
          IF(IEND.GT.NSMOTH)IEND=1  
C   
C         ADD THE NEW POINT TO THE RING 
C   
          IBEG=IBEG+1   
          IF(IBEG.GT.NSMOTH)IBEG=1  
          RING(IBEG)=Q(I+NSMOTH/2)  
          RINGSM=RINGSM+RING(IBEG)  
          IF(ISUB.EQ.0)THEN
            Q(I)=Q(I)*NSMOTH/RINGSM   
          ELSE IF(ISUB.EQ.1)THEN
            Q(I)=Q(I)-RINGSM/NSMOTH
          ELSE IF(ISUB.EQ.-1)THEN
            Q(I)=RINGSM/NSMOTH
          END IF
        END IF  
   50 CONTINUE  
      RETURN
      END   
