CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE TABLE_PM_EDB( UNIT, EDB_CNTR, EDB, COUNTER, WHO_CALLED,
     &			       LAST_EPOCH )
C+
C
C FUNCTIONAL DESCRIPTION:
C
C     Subroutine to accumulate counts from the PM-relevant contents of an EDB
C     and dump them at regular intervals to the file/device pointed to by UNIT.
C
C FORMAL ARGUMENTS:
C
C     UNIT:
C	I*4	  I	The Fortran unit number to which the averaged values
C			will be written.
C
C     EDB_CNTR:
C	I*4	  I	An integer that contains, upon entry, the EDB counter
C			value for the EDB contained in the argument EDB.  The
C			valid range of values is 0-19.
C
C     EDB:
C	/EDB_ALL/  I	A record of structure type /EDB_ALL/ containing the
C			EDB to be processed.
C
C     COUNTER:
C	I*4	  I/O	A count of the number of readouts that have been
C			accumulated.  This is incremented by one each time
C			we have a valid readout that is added to the running
C			sums, and reset to zero at the end of the averaging
C			interval (AVINT readouts).
C
C     WHO_CALLED:
C	I*4	  I	An integer informing this routine which application
C			is calling it.  Allowable values are 1 (PMRATES) and
C			2 (PMSW).
C
C     LAST_EPOCH
C	R*8	  O	The Epoch time of the end of the EDB.  This is to be
C			written to the output file along with the averaged
C			values. 
C
C INTERFACE:
!
!	INTERFACE TABLE_PM_EDB
!	  SUBROUTINE TABLE_PM_EDB(UNIT, EDB_CNTR, EDB, COUNTER, WHO_CALLED, LAST_EPOCH)
!	    INTEGER, INTENT(IN) :: UNIT, EDB_CNTR, WHO_CALLED
!	    INTEGER, INTENT(INOUT) :: COUNTER
!	    RECORD /EDB_ALL/ EDB
!	    INTENT(IN) EDB
!	    REAL(KIND=8), INTENT(OUT) :: LAST_EPOCH
!	  END SUBROUTINE TABLE_PM_EDB
!	END INTERFACE TABLE_PM_EDB
C
C IMPLICIT INPUTS:
C
C     The time that is stored in variables in common block SUM on one call is
C     used on a subsequent call.
C
C     The number of EDBs in the averaging interval is obtained from the common
C     block AVERAGE.
C
C IMPLICIT OUTPUTS:
C
C     The common block SUM is used to hold the intermediate sums for several
C     quantities.  The sums are used by another routine.
C
C SIDE EFFECTS:
C
C     None
C
C COMMON BLOCKS:
C
C     SUM	Contains the variables used to hold accumulated sums.
C     AVERAGE	Contains the variable AVINT, which is the number of readouts
C		in an averaging interval.
C
C INCLUDE FILES:
C
C     EDBDEF.INC	Contains definitions for the structure of an EDB.
C
C DESIGN:
C
C     This routine can be used by either the PMSW or PMRATES programs.  Much of
C     its operations are the same.  The argument WHO_CALLED is used to tell
C     the two programs apart and use program-specific code.
C
C     accumulate selected PM values into the variables of common block SUM
C     increment COUNTER each time this is done
C     if this is first readout of interval (COUNTER is 0) or no previous
C      readouts in this interval had a valid time (YEAR is still -1) then
C	if current time is nonzero then
C	  save current time (both Epoch and Gregorian), to be displayed when
C	   average is written out
C       endif
C     endif
C     if we've completed an averaging interval (COUNTER equals AVINT) then
C	call routine to calculate average of values and write them out
C	clear/reset COUNTER, other variables, set YEAR to -1
C     endif
C
C This version:   5.6   12-JAN-2000
C
C CREATED:
C
C     2-JAN-1996    John Paquette
C
C DEVELOPMENT HISTORY:
C
C  Author       Date            Description of Change 
C  --------     -----------     --------------------- 
C  J. PAQUETTE   2-JAN-1996     Created(from DUMP_MTOF_EDB)
C  J. PAQUETTE   3-JAN-1996     Fixed index error in PM E/Q
C  J. PAQUETTE   4-JAN-1996     Fixed another error in PM E/Q by using ZEXT;
C                               reversed order of E/Q steps
C  J. PAQUETTE  19-JAN-1996     Added logic to dump out partially-completed
C				average at the end of the data; explicitly
C				limited # of PM rates to 3/EDB
C  J. PAQUETTE  30-JAN-1996     Added a new counter (PM_COUNTER) to give
C                               correct averages in cases where data is
C                               missing; no longer test if we have run out of
C                               packets at this level. 
C  J. PAQUETTE   7-FEB-1996     Added SUM COMMON block to transfer information
C                               to the PARTIAL_AVERAGE_PM routine
C  J. PAQUETTE  29-FEB-1996     RETURN if quality flag is bad
C  J. PAQUETTE  17-MAY-1996     Added flag WHO_CALLED
C  J. PAQUETTE  28-MAY-1996     New format if called by PMSW
C  J. PAQUETTE   7-JUN-1996     Check PM EQ digital values before writing
C  J. PAQUETTE  10-JUN-1996     Write minimum and maximum rate value during
C                               averaging interval 
C  J. PAQUETTE  13-JUN-1996     Don't write minimum and maximum rate value
C                               during averaging 
C                               interval; adjust density for loss in gain
C  L. Bleau	12-JUL-1996	calculate minimum, maximum of PM_RATE values,
C                               write them out 
C  J. PAQUETTE  17-JUL-1996     Undo Larry's changes of 12 July; they were
C                               incorrect. Write minimum and maximum rate value
C                               during averaging interval as was done back in
C                               June 
C  J. PAQUETTE  30-JUL-1996     Don't write out average if a long data gap
C                               occurs during it 
C  J. PAQUETTE   5-AUG-1996     Always start a set of 6 rates on an even EDB;
C                               put fill flag of -1 when we fail to accumulate
C                               any values; do not attempt to fit such a case
C  J. PAQUETTE   6-AUG-1996     If time of 1st readout in averaging interval is
C                               not available, use time from a later readout
C  J. PAQUETTE  12-AUG-1996     Change method of finding maximum and minimum
C                               rates again; now find the 6 rates corresponding
C                               to one readout, find the max and min of those
C                               6, and average the maxima and minima  
C  J. PAQUETTE  26-AUG-1996     Save ending time of most recent averaging
C                               interval in LAST_EPOCH; pass via common block
C                               to PARTIAL_AVERAGE_PM 
C  J. PAQUETTE  26-AUG-1996     Make LAST_EPOCH an argument
C  J. PAQUETTE  29-AUG-1996     Initialize PRINT to .TRUE.
C  J. PAQUETTE  25-SEP-1996     Correct condition for accumulating max and min
C                               rates; was EDBMOD .EQ. 0, now is EDBMOD .NE. 0
C  J. PAQUETTE  20-NOV-1996     Incorporates new time correction and density
C                               normalizations
C  J. PAQUETTE  12-DEC-1996     Incorporates new time correction and density
C                               normalizations provided by Scott; corrects
C                               logic for computing MINRATE and MAXRATE
C  J. PAQUETTE  13-DEC-1996     Incorporates quantization and dead time
C                               corrections from Scott
C  J. PAQUETTE  17-DEC-1996     Correct for residual dependance on MAXRATE, use
C                               new constants
C  J. PAQUETTE   7-JAN-1997     Add 4 columns to output; change call to
C                               SWPARAMETERS
C  J. PAQUETTE   8-JAN-1997     Add call to HEFFALUMP
C  J. PAQUETTE  15-JAN-1997     Print out VSW_HEFTI also
C  J. PAQUETTE  17-JAN-1997     Yet another change in what is written out; and
C                               a change in the call to SWPARAMETERS
C  J. PAQUETTE  22-JAN-1997     Add decimal place to density
C  L. BLEAU     22-JAN-1997     placed runtime format stmt in char variable FMT,
C                               save in COMMON block FORM
C  J. PAQUETTE  24-JAN-1997     Pass uncorrected PM rates to HEFFALUMP;
C				rearrange DATA statement for FMT to avoid
C				compiler message
C  J. PAQUETTE  29-JAN-1997     Changeover to TABLE_PM_EDB_A; change meaning of
C                               "uncorrected Vsw; change speed correction
C  J. PAQUETTE  31-JAN-1997     Change BACK meaning of "uncorrected Vsw"
C  J. PAQUETTE   3-FEB-1997     Add two new columns of output
C  L. BLEAU	 3-FEB-1997     enable runtime format
C  L. BLEAU	 4-FEB-1997     remove format 170, use runtime format with FLAGS
C				to write out -1s
C  J. PAQUETTE   5-FEB-1997     Add two new columns of output (THETA and
C                               SIGMA_THETA)
C  J. PAQUETTE   5-FEB-1997     Small format changes
C  L. BLEAU	 6-FEB-1997 3.9	remove flag writes, add call to WRITE_FLAG_RECORD
C  J. PAQUETTE   6-FEB-1997     Increase the width of the format field for
C                               PM_MIN, other format changes; delete
C                               contribution from theta bin 0 
C  J. PAQUETTE   6-FEB-1997     Increase the width of the format field for N/S
C                               and Sig 
C  J. PAQUETTE  10-FEB-1997     Install check to see if SUMW is 0 before
C                               division
C  J. PAQUETTE  10-FEB-1997     Add Density correction to reflect change in speed
C  J. PAQUETTE  13-FEB-1997     Add call to CORRECT_ANGLE, print out value of ANGLE
C  J. PAQUETTE  14-FEB-1997     Add variable ANGLE_INDEX, to data statement
C  J. PAQUETTE  20-FEB-1997     Change PM_MAX lower limit from 1000 to 100
C  J. PAQUETTE  21-FEB-1997     Add parameters from moment calculations 
C  J. PAQUETTE  21-FEB-1997     More corrections to density and Vth
C  J. PAQUETTE  24-FEB-1997     Change limit in density correction based on
C                               Vth/Vsw to 1.2; call both HEFFALUMP and
C                               HEFFALUMP_H; call FISH; correct DENSITY_MOM
C                               based on VSW_MOM 
C  J. PAQUETTE  24-FEB-1997     Do last Vth corrections AFTER density
C                               corrections 
C  J. PAQUETTE  25-FEB-1997     Density_mom correction
C  J. PAQUETTE  27-FEB-1997     If a rate < 10 or rate > 70000, it does not
C                               contribute to the average
C  J. PAQUETTE  27-FEB-1997     Remove erroneous DENSITY_MOM corrections
C  J. PAQUETTE  28-FEB-1997     New corrections to DENSITY, VTH, VTH_MOM
C  J. PAQUETTE  11-MAR-1997     Output combined parameters (combination of fit
C                               and mom techniques)
C  J. PAQUETTE  12-MAR-1997     Change code that checks for data gaps to deal
C                               with averages that span a time step back
C  J. PAQUETTE  12-MAR-1997     Squeeze format
C  J. PAQUETTE  17-MAR-1997     Test moment quantities for 0 before calculating
C                               combined quantities
C  J. PAQUETTE   7-APR-1997     Restrict fit/mom correction factor by
C                               restricting ratio of fit/mom
C  J. PAQUETTE  11-APR-1997     Add code to avoid throwing out entire average
C                               when there's good data in it
C  J. PAQUETTE  14-APR-1997     Restore original order of incrementing COUNTER
C  J. PAQUETTE  14-MAY-1997     Correct error due to changes of 11-april
C  J. PAQUETTE  26-JUN-1997     New corrections to Vsw (both fit and mom); new
C                               formula for VSW_COM
C  J. PAQUETTE  21-JUL-1997     New correction to density based on Vsw_unc/Vsw;
C                               new Vsw_com; add a space to output format
C  J. PAQUETTE  21-JUL-1997     New correction to density to allow for apparent
C                               time decay in 1997 
C  J. PAQUETTE  24-JUL-1997     Change back to TABLE_PM_EDB
C  J. PAQUETTE  20-NOV-1997     PMSWC
C  J. PAQUETTE   4-DEC-1997     Renamed from TABLE_PM_EDB_C to TABLE_PM_EDB
C  J. PAQUETTE   4-DEC-1997     Changed call to BACKGROUND_C
C  J. PAQUETTE   9-JAN-1998     New Vsw_unc/Vsw correction
C  J. PAQUETTE  13-JAN-1998     New DENSITY_COM, as a consequence of the Jan 9
C                               change
C  J. PAQUETTE   5-MAY-1998     New time decay; also, allow for for bias change
C                               on 4/18/98
C  J. PAQUETTE   5-MAY-1998     Switch order of voltages vs rates in PMRATES
C                               (i.e. rates now appear to the left of voltages)
C  J. PAQUETTE   6-MAY-1998     PMRATES wants UNCORRECTED rates; when
C                               WHO_CALLED=1, use uncorrected rates
C  J. PAQUETTE   6-MAY-1998     Remove repeat group from FMT variable due to
C                               LRB's code in HOUR_AVERAGE; replace HEFTI Vsw
C                               and Vth with VTH_CHI_MIN in output, banish call
C                               to HEFFALUMP
C  J. PAQUETTE  29-OCT-1998     Possibly temporary fix for density after the
C                               "SOHO vacation"
C  fmi          16-NOV-1998     write all pmeq values for pmrates (i.e. even if
C                               not canonical) 
C  L. Bleau	23-APR-1999	added IMPLICIT NONE, declarations
C  J. PAQUETTE   4-MAY-1999     Ignore data from March 21 1996 before 20:50
C  SEL           4-MAY-1999     Ignore data from March 21 1996 before 20:50,
C                               not March 26, 1996 
C  J. PAQUETTE  17-JUN-1999     Correct longstanding error in READOUT_QUALITY
C  J. PAQUETTE  17-JUN-1999     Check for EDB.QUALITY = -2 (meaning Start Time
C                               has not yet been reached). RETURN in that case.
C                               Make some other RETURNs contingent on value of
C                               WHO_CALLED  
C  J. PAQUETTE	22-JUN-1999	Do not write any output when caller is PMRATES
C                               and all PM_EQ are zero or missing (-1)
C  J. PAQUETTE	24-JUN-1999	Implement new time correction for times after
C				the SOHO "vacation" 
C  L. Bleau	14-SEP-1999 5.0	separated into two routines: one to accumulate
C				(TABLE_PM_EDB) and one to average and print
C				(TABLE_PM_EDB_AVERAGE)
C  L. Bleau	15-SEP-1999	move reset of PM_QUALITY to TABLE_PM_EDB_AVERAGE
C  L. Bleau	15-SEP-1999 5.2	separate TABLE_PM_EDB_AVERAGE from TABLE_PM_EDB,
C				put into different files, add comments
C  L. Bleau	12-NOV-1999 5.3	removed unused common block PACKET_CONTROL;
C				added comments
C  L. Bleau	19-NOV-1999 5.4	ignore data on 99 Nov 19 (DOY 323) before
C				00:30:20
C  SEL      31-DEC-99  fixed bug in processing y2k data - changed
C                      IF(YEAR.GT.100)YEAR =YEAR - 100 to
C                      IF(YEAR.GE.100)YEAR =YEAR - 100 to
C  L. Bleau	 4-JAN-2000 5.5	fix y2k bug, replace .GT. with MOD
C L. Bleau	12-JAN-2000 5.6	YEAR = 0 was used as a flag value, but in year
C				2000 it is also a valid value, change to use
C				a -1; add test to make sure time is valid
C				(nonzero) before updating YEAR
C-
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

CDEC$ IDENT	'5.6'
      IMPLICIT NONE
      INCLUDE 'INC_DIR:EDBDEF.INC'
      INTEGER*4 UNIT, EDB_CNTR, COUNTER, WHO_CALLED
      REAL*8 LAST_EPOCH
      RECORD /EDB_ALL/ EDB
C
C Local variables and COMMON blocks
C
      INTEGER SOHO_DECOMPRESS, EDBMOD, READOUT_QUALITY
      INTEGER MAXOF6, MINOF6
      INTEGER CANONICAL_PM(6)/198,123,76,47,29,18/, NEWRATE, NEWRATE2
      INTEGER TEDBMOD, BAD/0/, I
      REAL Y
      REAL*8 AVERAGE_EPOCH
      LOGICAL CODE_C, BAD_RATES/.FALSE./, MCP_BIAS_PROB, OUTPUT
C
      INTEGER AVINT
      COMMON /AVERAGE/ AVINT
C
      INTEGER*4 PM_RATE(6), YEAR, DOY, HR, MIN, SEC, MINRATE, MAXRATE
      INTEGER*4 MMCOUNTER, UNC_PM_RATE(6)
      REAL*4 PM_EQ(6), PM_COUNTER(6), PM_T1(120), TCOUNT(120)
      LOGICAL PRINT
      COMMON /SUM/ PM_EQ, PM_RATE, YEAR, DOY, HR, MIN, SEC, PM_COUNTER, PRINT,
     &             MINRATE, MAXRATE, MMCOUNTER, PM_T1, TCOUNT, UNC_PM_RATE
      DATA YEAR/-1/, MINRATE/0/, MAXRATE/0/, PRINT/.TRUE./
C
C Since we get the first three PM rates in even-numbered EDB's, and the second
C three in odd-numbered EDB's, we have to buffer things.
C
      EDBMOD = 3-3*MOD(EDB_CNTR,2)
C
C Reset READOUT_QUALITY to 0 at the beginning of a readout.  Since a readout of
C PM data requires a pair of EDB's, reset counter on the first EDB of the pair.
C The first EDB is ODD, so EDBMOD will be 0.
C
      IF(EDBMOD .EQ. 0) READOUT_QUALITY = 0
      READOUT_QUALITY = READOUT_QUALITY +  EDB.QUALITY
C
C If EDB.QUALITY = -2, then we haven't reached the start time yet; RETURN
C
      IF(EDB.QUALITY .EQ. -2)RETURN
C
C Test if anything nonzero.  RETURN unless called by PMRATES
C
      IF((EDB.HEADER.MTOF_STATUS_LEN .EQ. 0) .AND. (EDB.HEADER.PM_RATES_LEN .EQ. 0).AND.(WHO_CALLED .NE. 1)) RETURN
C
C Demand that first readout in averaging interval is good.  Return if it's not
C (unless called by PMRATES).
C
      IF((COUNTER .EQ. 0).AND.(EDB.QUALITY .EQ. -1).AND.(WHO_CALLED .NE. 1))RETURN
C
      IF(EDBMOD .NE. 0)THEN
        COUNTER = COUNTER + 1
      ENDIF
C
C Test the quality flag.  RETURN if its bad
C
      IF(EDB.QUALITY .NE. -1)THEN
C
C Get the PM E/Q values
C
        DO 24 I = 3, 1, -1

          PM_EQ(4 - I + EDBMOD) = PM_EQ(4 - I + EDBMOD) + 0.0159 * ZEXT(EDB.DATA.MTOF_STATUS(I+1))

          IF((ABS(ZEXT(EDB.DATA.MTOF_STATUS(I+1)) - CANONICAL_PM(4 - I + EDBMOD))) .GT. 1)THEN
C
C Set flag indicating bad rates UNLESS the caller was PMRATES.  If PMRATES was
C the calling routine, don't invalidate the rates just because the PMEQ values
C are out of range.
C
            IF(WHO_CALLED .NE. 1)BAD_RATES = .TRUE.
          ENDIF
  24    CONTINUE
C
C On March 21 1996, the PM MCP bias was ramped up.  Ignore data from before
C 20:50 on that day.
C
C On November 19 (DOY 323) 1999, the PM E/q went operational before the PM MCPs
C were completely turned up, causing PMSW to report incorrect density values
C until the PM MCP level was correct.  Ignore data from before 0:30:20 on that
C day.
C
        IF((EDB.EPOCH .GT. 1206057600.0D0).AND.(EDB.EPOCH .LT. 1206132600.0D0))MCP_BIAS_PROB=.TRUE.
	IF((EDB.EPOCH .GT. 1321660800.0D0) .AND. (EDB.EPOCH .LT. 1321662620.0D0)) MCP_BIAS_PROB = .TRUE.
C
        IF(MCP_BIAS_PROB)THEN
          BAD_RATES = .TRUE.
          PRINT = .FALSE.
          MCP_BIAS_PROB = .FALSE.
        ENDIF
C
        IF((EDBMOD .NE. 0).AND.(BAD_RATES))BAD = BAD + 1
C
C Decode three PM rates and store into PM_RATE array.
C
        IF(.NOT. BAD_RATES)THEN
          CODE_C =.TRUE.
          DO 40 I=3, 1, -1
            NEWRATE = SOHO_DECOMPRESS(EDB.DATA.PM_RATES(I), CODE_C)
            NEWRATE2 = SOHO_DECOMPRESS(EDB.DATA.PM_RATES(I)+1, CODE_C)
C
C Test to avoid bad data.  If we have a point outside the set limits, then 
C get out of the 40 loop and the IF(EDB.QUALITY...) section
C
            IF((WHO_CALLED .NE.1).AND.((NEWRATE .LT. 10).OR.(NEWRATE .GT. 700000)))THEN
              EDB.QUALITY = -1
              READOUT_QUALITY = -1
C              I=1
C Effect of previous line was supposed to be to terminate loop by setting I to
C its final value.  This method is unsupported.
C Easier way: Use GOTO out of loop.
	      GOTO 45
            ELSE
C
C Before any corrections are applied, save the raw rate for use by PMRATES
C
              UNC_PM_RATE(3 - I + 1 + EDBMOD) = UNC_PM_RATE(3 - I + 1 + EDBMOD) + NEWRATE
C
C Since the compression routine truncates(?), take the average of the
C uncompressed value and the next higher uncompressed value, giving a result
C halfway between the two.  Do not do this if the rate is 32 or less, because
C no truncation occurs in that case.
C
              IF(NEWRATE .GT. 32)NEWRATE = (NEWRATE + NEWRATE2)/2
C
C Find the maximum and minimum rates of this set of 6
C
              IF(NEWRATE .GT. MAXOF6)MAXOF6 = NEWRATE
              IF(NEWRATE .LT. MINOF6)MINOF6 = NEWRATE
C
C Correct for deadtime.  400000 is the assumed max rate
C
              IF(NEWRATE .GT. 0)THEN
                Y = FLOAT(NEWRATE) / 400000.0
      	        IF (Y .GE. 0.95) Y = 0.95                ! This restriction is equivalent to demanding correction factor < 3
                NEWRATE = IFIX(FLOAT(NEWRATE) /(-Y / LOG(1-Y)))
              ENDIF
C
              PM_RATE(3 - I + 1 + EDBMOD) = PM_RATE(3 - I + 1 + EDBMOD) + NEWRATE
              PM_COUNTER(3 - I + 1 + EDBMOD) = PM_COUNTER(3 - I + 1 +EDBMOD) + 1.0
C
C Note the time; its the most recent time to contribute to the average.  Add
C 15 seconds so that the time denotes the end of the current EDB, not the
C beginning of it.
C
              LAST_EPOCH = EDB.EPOCH + 15.D0
            ENDIF
  40      CONTINUE
  45      CONTINUE
C
          TEDBMOD = 60-60*MOD(EDB_CNTR,2)
C
C Get the PM Theta values
C
          DO 50 I=EDB.HEADER.PM_THETA_SPECT_LEN, 1, -1
            IF((I .GT. 40).AND.(EDB_CNTR .EQ. 1))THEN
C
C The data is dead for this EDB and step; don't count it for purposes of
C accumulation 
C
            ELSE
              PM_T1(EDB.HEADER.PM_THETA_SPECT_LEN - I + 1 + TEDBMOD) = PM_T1(EDB.HEADER.PM_THETA_SPECT_LEN - I + 1 + TEDBMOD) +
     &                                                                SOHO_DECOMPRESS(EDB.DATA.PM_THETA_SPECT(I), CODE_C)
              TCOUNT(EDB.HEADER.PM_THETA_SPECT_LEN - I + 1 + TEDBMOD) = TCOUNT(EDB.HEADER.PM_THETA_SPECT_LEN - I + 1 + TEDBMOD) + 1 
            ENDIF
  50      CONTINUE
        ENDIF
C
C Increment counter for maxima and minima when you have a complete set of 6
C
        IF(EDBMOD .NE. 0)THEN
C
C Add the max and min of this set of 6 to accumulators for the computation of
C average maximum and minimum 
C
          IF((READOUT_QUALITY .EQ. 0).AND.(.NOT.BAD_RATES))THEN
            MMCOUNTER = MMCOUNTER + 1
            MAXRATE = MAXRATE + MAXOF6
            MINRATE = MINRATE + MINOF6
           ENDIF
          READOUT_QUALITY = 0
          MAXOF6 = 0
          MINOF6 = 7864320
        ENDIF
C
        BAD_RATES =.FALSE.
      ENDIF
C
C Save the time to display when this averaging interval is written out.
C Use the time from the first *good* readout in the averaging interval (COUNTER
C will be 0).  We won't ven get here if the first readout of an interval is
C marked as bad.
C If, however, for some strange reason the edb is marked as good but the time
C it contains is bad (ie, zero), we'd save a zero for YEAR, so test EDB_TIME
C before we overwrite YEAR.
C
      IF((COUNTER .EQ. 0).OR.(YEAR .EQ. -1))THEN
        IF (EDB.EDB_TIME.YEAR .NE. 0) THEN
          YEAR = EDB.EDB_TIME.YEAR
          IF (YEAR .GT. 1900) YEAR = MOD(YEAR,100)
          DOY = EDB.EDB_TIME.DOY
          HR  = EDB.EDB_TIME.HR
          MIN = EDB.EDB_TIME.MIN
          SEC = EDB.EDB_TIME.SEC
          AVERAGE_EPOCH = EDB.EPOCH
        ENDIF
      ENDIF
C
C If we have accumulated enough readouts divide the sums by the number of
C readouts to get an average, and write the data out; then clear the sums and
C reset the counter.
C This is now done by another subroutine.
C
      IF(COUNTER .EQ. AVINT)THEN
        IF(BAD .GE. AVINT)PRINT =.FALSE.
C
C Only output if the start time of the current EDB is within 3 times the
C averaging interval (=3*AVINT*30 seconds) of the start time of the averaging
C interval.  This is to guard against data gaps.
C
C Instead of conditionally calling TABLE_PM_EDB_AVERAGE then zeroing the
C accumulated values, which would require knowing most of TABLE_PM_EDB_AVERAGE's
C local variables, compute the condition here and pass it as a logical variable
C to TABLE_PM_EDB_AVERAGE.  If true it averages and writes; if false it does
C not.  Either way it clears the accumulated values for us.
C
	OUTPUT = (ABS(EDB.EPOCH - AVERAGE_EPOCH)/90.D0 .LE. AVINT) .OR.
     &		 (EDB.QUALITY .EQ. -1)
C
	CALL TABLE_PM_EDB_AVERAGE( OUTPUT, UNIT, WHO_CALLED, AVERAGE_EPOCH )
C
C Reset COUNTER to restart the averaging interval
C Also set YEAR to flag value of -1 to ensure new time gets loaded
C
        COUNTER = 0
        YEAR = -1
        BAD = 0
        PRINT = .TRUE.
C
      ENDIF
C
      RETURN
      END
