C-------------------------------------------------------------------
C  TDB_PRFLAX
C  D. MC CUNE 10JUN-1982
C  ADD ON TO ELECTRON DATA PROFILE SYMMETRIZATION SYSTEM--
C  REPLACE FLATSPOTS IN THE UNSYMMETRIZED PROFILE WITH VERY
C  GENTLE SLOPES, PRIOR TO CARRYING OUT SYMMETRIZATION OPERATION
C
      SUBROUTINE TDB_PRFLAX(DATA,N)
C
!============
! idecl:  explicitize implicit INTEGER declarations:
      IMPLICIT NONE
      INTEGER, PARAMETER :: R8=SELECTED_REAL_KIND(12,100)
      INTEGER n,i,il,ilp1,ist,istm1,ifin,imid,inum,iabs,isign
!============
! idecl:  explicitize implicit REAL declarations:
      REAL*8 ztol,dtol,dstm1,dsum,dfnp1,davg,dinc,dnew,dav2,dcen0
!============
      real*8 DATA(N)
C
      DATA ZTOL/1.E-5_R8/
C  DEFINE TOLERANCE FOR DETERMINING FLATNESS
      DTOL=0.0_R8
      DO 10 I=1,N
      DTOL=max(DTOL,ABS(DATA(I)))
 10   CONTINUE
C  ZTOL* MAX MODULUS
      DTOL=ZTOL*DTOL
C-----
C  LOCATE ALL FLAT SPOTS
      IL=0
 20   CONTINUE
      IL=IL+1
      IF(IL.GE.N) GO TO 500
C  TEST FOR FLATSPOT
      ILP1=IL+1
      IF(ABS(DATA(ILP1)-DATA(IL)).GT.DTOL) GO TO 20
C  START OF FLATSPOT DETECTED
      IST=IL
      ISTM1=IL-1
      DSTM1=0.0_R8
      IF(ISTM1.GT.0) DSTM1=DATA(ISTM1)
      DSUM=DATA(IL)
C  FIND END OF FLATSPOT
 30   CONTINUE
      IL=IL+1
      DSUM=DSUM+DATA(IL)
      IF(IL.GE.N) GO TO 100
      ILP1=IL+1
      IF(ABS(DATA(ILP1)-DATA(IL)).LE.DTOL) GO TO 30
C  END OF FLATSPOT FOUND
 100  CONTINUE
      DFNP1=0.0_R8
      IF(IL.LT.N) DFNP1=DATA(ILP1)
      IFIN=IL
      IMID=(IST+IFIN)/2
C
      INUM=IFIN-IST+1
      DAVG=DSUM/INUM
C
C  DECIDE ON SKEWED STRAIGHT LINE OR TRIANGLE PATTERN TO REPLACE
C  DATA FLATSPOT
      IF(ABS(DSTM1-DFNP1).LE.DTOL) GO TO 200
C  SKEWED STRAIGHT LINE REPLACEMENT
      DINC=DTOL/INUM
      ISIGN=1
      IF(DFNP1.LT.DSTM1) ISIGN=-1
C
      DO 150 I=IST,IFIN
      DNEW=ISIGN*(I-IMID)*DINC + DAVG
      DATA(I)=DNEW
 150  CONTINUE
C  RE-ENTER LOOP TO CHECK FOR MORE FLATSPOTS
      GO TO 20
C  TRIANGULAR PATTERN REPLACEMENT
 200  CONTINUE
      DAV2=.5_R8*(DSTM1+DFNP1)
      ISIGN=1
      IF(DAV2.LT.DAVG) ISIGN=-1
      DINC=DTOL/INUM
      DCEN0=DAVG-0.25_R8*ISIGN*INUM*DINC
C
      DO 250 I=IST,IFIN
      DNEW=DCEN0+ISIGN*IABS(IMID-I)*DINC
      DATA(I)=DNEW
 250  CONTINUE
C  REENTER LOOP TO FIND FLATSPOTS
      GO TO 20
C-----
C  EXIT
 500  CONTINUE
      RETURN
      END
