      SUBROUTINE AVGTNDG(SCF,DGDT,SGPR,PGVB,PGCB,PGMB,GCNC,DT, &
                         KOUNT,ICFRQ,IAVGPRD,IUPDATP,NRMFLD,ILGA,LEVA)
!-----------------------------------------------------------------------
!     PURPOSE:
!     --------
!     TIME-AVERAGED TENDENCIES FOR AEROSOL UPTAKE OF GAS-PHASE SPECIES.
!     INSTANTANEOUSLY CALCULATED TENDENCIES ARE AVERAGED AND SAVED.
!     RESULTS ARE SUBSEQUENTLY SCALED TO ALLOW UPDATES TO PAM TRACERS
!     ON A PER-TIME-STEP BASIS.
!
!     HISTORY:
!     --------
!     * DEC 29/2010 - K.VONSALZEN   NEW.
!
!-----------------------------------------------------------------------
!
      USE SDPARM
!
      IMPLICIT REAL (A-H,O-Z), INTEGER (I-N)
!
      REAL, INTENT(INOUT), DIMENSION(ILGA,LEVA) ::SCF,DGDT
      REAL, INTENT(INOUT), DIMENSION(ILGA,LEVA) :: PGVB
      REAL, INTENT(INOUT), DIMENSION(ILGA,LEVA,NRMFLD) :: PGMB
      REAL, INTENT(IN), DIMENSION(ILGA,LEVA) :: SGPR,GCNC
      INTEGER, INTENT(INOUT), DIMENSION(ILGA,LEVA,NRMFLD) :: PGCB
!
      REAL, DIMENSION(ILGA,LEVA) :: PGVM
      REAL, DIMENSION(ILGA,LEVA,NRMFLD) :: PGMM
      INTEGER, DIMENSION(ILGA,LEVA,NRMFLD) :: PGCM
!
!-----------------------------------------------------------------------
!
      IF ( MOD(KOUNT,ICFRQ) /= 0 ) THEN
        DGDT=YNA
      ENDIF
!
!     * RETRIEVE MEAN AND ACCUMULATED RESULT AND COUNTER FROM
!     * PREVIOUS TIME STEP.
!
      PGVM=PGVB
      PGCM=PGCB
      PGMM=PGMB
!
!     * LOOP OVER ALL FIELDS INVOLVED IN CALCULATION OF RUNNING
!     * MEAN RESULTS.
!
      NRMFLDL=CEILING(REAL(IAVGPRD)/REAL(IUPDATP))
      DO IND=1,NRMFLDL
        IOFF=(KOUNT+IAVGPRD-1)-(IND-1)*IUPDATP
        IF ( IOFF >= 1 .AND. MOD(IOFF,IAVGPRD)==0 ) THEN
!
!         * RUNNING MEAN TENDENCIES.
!
          WHERE ( PGCM(:,:,IND) > 0 )
            PGVM(:,:)=PGMM(:,:,IND)/REAL(PGCM(:,:,IND))
          ELSEWHERE
            PGVM(:,:)=YNA
          ENDWHERE
!
!         * RESET ACCUMULATED RESULT AND COUNTER.
!
          PGMM(:,:,IND)=0.
          PGCM(:,:,IND)=0
        ENDIF
!
!       * ACCUMULATE INSTANTANEOUS RESULT AND ADVANCE COUNTER.
!
        WHERE ( ABS(DGDT(:,:)-YNA) > YTINY )
          PGMM(:,:,IND)=PGMM(:,:,IND)+(DGDT(:,:)-SGPR(:,:))
          PGCM(:,:,IND)=PGCM(:,:,IND)+1
        ENDWHERE
      ENDDO
!
!     * SAVE MEAN AND ACCUMULATED RESULTS AND COUNTER.
!
      PGVB=PGVM
      PGCB=PGCM
      PGMB=PGMM
!
!     * RESTORE TENDENCIES TO MEAN VALUES.
!
      DGDT=PGVM+SGPR
!
!     * SCALE AEROSOL UPTAKE TENDENCIES TO AVOID NEGATIVE
!     * CONCENTRATIONS, IF NECESSARY.
!
      WHERE ( DGDT(:,:) < -YSMALL )
        SCF(:,:)=MIN(SCF(:,:),MAX(0., &
                             -(GCNC(:,:)+SGPR(:,:)*DT)/(DT*PGVM(:,:))))
      ENDWHERE
!
      END SUBROUTINE AVGTNDG
