      SUBROUTINE MATCH2(MIN,AERR,ERR,STD2T,P2T,M2T,DEL,N,NSTD,NM,XL,LIST
     1,TTY,D2)
C
C  SUBROUTINE TO MATCH INTERNAL STD WITH OBSERVED PEAKS
C    WRITTEN BY RAY GOEHNER  9/83
C
      COMMON /DPRC/ IDPRC,IBKGR,ISCH,INRM,ISTD,NDER,MF,MB,IK2,ISM,IPF,
     1NT,SENS,INSTD,EXSTD,E2T
C
      BYTE IBKGR,IK2,ISCH,INRM,IDPRC,ISTD,NDER,MF,MB,ISM,INSTD(30)
     1,EXSTD(30)
      INTEGER TTY
      DIMENSION STD2T(1),P2T(1)
      REAL*8 M2T(1),DEL(1)
      BYTE DUM(8),D2(13)
C
      M=0
      S=0
  500 DO 501 I=1,30
  501 IF(INSTD(I).EQ.'.') J=I
      INSTD(J+4)=0
      OPEN(UNIT=1,NAME=INSTD,TYPE='OLD',ERR=9001,READONLY)
  510 I=1
      READ(1,2005,END=9001) DUM  ! moved label 300 from here 
 2005 FORMAT(8A1)
  300 READ(1,2000,END=350,ERR=9001) STD2T(I) ! to here 5/85 -- mfg
 2000 FORMAT(F10.3)  ! FORMAT CHANGED 3/85 RPG
      I=I+1
      GO TO 300
  350 CLOSE(UNIT=1)
      NSTD=I-1
C
  402 DO 100 I=1,N
      DO 100 J=1,NSTD
      DIF=ABS(STD2T(J)-P2T(I))
      IF(DIF.GT.E2T) GO TO 100
C MATCHED
      S=S+DIF
      M=M+1
  100 CONTINUE
      IF(M.LT.MIN) GO TO 900
      AERR=S/FLOAT(M)
      IF(LIST.EQ.1) WRITE(TTY,1120)
 1120 FORMAT(3X,'OBS 2THETA',2X,'STD 2THETA',5X,'STD-OBS')
  110 S=0
      NM=0
      ERR=0.0
      DO 200 J=1,M
      DO 200 I=1,N
      DIF=ABS(STD2T(J)-P2T(I))
      IF(DIF.GT.E2T) GO TO 200 ! NOT MATCHED
C MAKE SURE NEXT LINE ISN'T BETTER MATCH
      IF(I.EQ.N)GO TO 190  !  LAST LINE -- NO NEXT TO COMPARE
      DIF2=ABS(STD2T(J)-P2T(I+1))
      IF(DIF2.LT.DIF)GO TO 200 ! LET NEXT LINE BE MATCHED
C  FINAL MATCH
190   S=S+DIF  ! CALCULATE APPROPRIATE VALUES FOR MATCHED LINE
      NM=NM+1
      M2T(NM)=P2T(I)
      DEL(NM)=STD2T(J)-P2T(I)
      ERR=ERR+DEL(NM)
      IF(LIST.EQ.1) WRITE(TTY,1000) P2T(I),STD2T(J),DEL(NM)
 1000 FORMAT(1X,3F12.4)
  200 CONTINUE
      IF(NM.GE.MIN) GO TO 301
      AERR=2.0*AERR
      GO TO 110
  301 AERR=S/FLOAT(NM)
      ERR=ERR/FLOAT(NM)
      IF(LIST.EQ.0) RETURN
      WRITE(TTY,1010) AERR,NM
 1010 FORMAT(/1X,'AVERAGE ERROR=',F8.4,'  NUMBER OF STD LINES MATCHED='
     1,I4)
      WRITE(TTY,1020) ERR
 1020 FORMAT(1X,'AVERAGE DIFFERENCE IN OBS  & STD =',F9.4)
      RETURN
  900 WRITE(TTY,2001) E2T,AERR
 2001 FORMAT(1X,'PROBLEM IN MATCHING INTERNAL STANDARD LINES'
     1,' TO PEAKS FOUND'/' E2T=',F8.4,'  AERR=',F8.4)
      STOP 'MATCH FAILED'
 9001 WRITE(TTY,2003) F
 2003 FORMAT(1X,'FILE ',30A1,' WAS NOT OPENED')
  999 STOP 'WHAT CAN I DO ?'
      END
