      SUBROUTINE POLYBG(LUB,LUR,LUTI,NA,XW,YW,YN)
C
C    WRITTEN BY RAY GOEHNER FOR SPECPLOT 4/84
      COMMON /XY/X,Y,X1,Y1,X2,Y2
      COMMON /CRD/AUSX,BUSX,AUSY,BUSY,ASUX,BSUX,ASUY,BSUY,AMSX,BMSX
     1,ASMX,BSMX,AUMX,BUMX,AMUX,BMUX,DSP,ITERM,N,NS,NF
      COMMON /SCN/ XS,XF,YS,YF,XXS,XXF,YYS,YYF,CSTR,CFIN,CYMIN,CYMAX,STR
     1,FIN,YMIN,YMAX,ZZ,CW,CH,ISP,JSP,IFL
      COMMON /COLOR/ CL,CLB,CLA,CLG
C
      BYTE ISP,IFL,ITERM,DSP,JSP
      REAL*8 A,BB(10),XX(100),YY(100),SD
C
C  LU-LUB WRITE OUT BKGR WHICH WAS REMOVED
C  LU-LUR WRITE RESULTS IE POLYNOMIALS
C  LU-LUTI TERMINAL
C
C
      XX(1)=ASUX*X+BSUX
	J=ASMX*X+BSMX
	JS=J
	IF(J.LT.1.OR.J.GT.N) GO TO 100
	READ(LUB'J) B
	YX=B
	IF(DSP.EQ.2) YX=ALOG10(B+ZZ)
	IF(DSP.EQ.3) YX=SQRT(B+ZZ)
	IF(DSP.EQ.4) YX=B*YN
	Y=AUSY*YX+BUSY
      CALL TPLOT(0,X,YYS)
      CALL TPLOT(1,X,Y)
      CALL TPLOT(2,X,Y)
      I=2
  100 CALL CURSOR(ID,X,Y,ITERM)
      XX(I)=ASUX*X+BSUX
      IF(ID.EQ.' ') GO TO 200
C  CHANGE COLOR OF DOTS HERE OR DRAW LINES TO PTS
	J=ASMX*X+BSMX
	IF(J.LT.1.OR.J.GT.N) GO TO 200
	JF=J
	READ(LUB'J) B
	YX=B
	IF(DSP.EQ.2) YX=ALOG10(B+ZZ)
	IF(DSP.EQ.3) YX=SQRT(B+ZZ)
	IF(DSP.EQ.4) YX=B*YN
	Y=AUSY*YX+BUSY
      CALL TPLOT(0,X,YYS)
      CALL TPLOT(1,X,Y)
      CALL TPLOT(2,X,YYS)    ! CLEAR BUFFER
      I=I+1
      GO TO 100
  200 NB=I-1
      NORD=-(NB-3)
      N2=NA/2
      DO 300 I=1,NB
      IX=AUMX*XX(I)+BUMX
      M=0
      S=0
      DO 250 J=1,NA
      L=IX+N2-J+1
      M=M+1
      READ(LUB'L) B
      S=S+B
  250 CONTINUE
      YY(I)=S/FLOAT(M)
  300 CONTINUE
      IF(NORD.LT.-6) NORD=-6
      IF(NORD.GT.-1) GO TO 999
      CALL PFIT(XX,YY,NB,NORD,A,BB,IORD,SD)
      M=IORD
      W=50*CW
      CALL XWYW(XW,YW,XS,XF,W,CW,CH)
      WRITE(LUTI,1000) A,(BB(I),I=1,M)
 1000 FORMAT('+',$,7E10.3)
C
	NC=0
	ZN=0
      DO 500 I=NS,NF
	IF(I.LT.JS.OR.I.GT.JF) GO TO 500
      S=A
      X=AMUX*I+BMUX
      DO 400 J=1,IORD
  400 S=S+BB(J)*X**J
      X=AMSX*I+BMSX
	IF(X.LT.XXS.OR.X.GT.XXF) GO TO 500
	YX=S
	ZE=S+ZZ
	IF(DSP.EQ.2) THEN
	IF(ZE.LT.0.0) GO TO 500
	YX=ALOG10(ZE)
	ENDIF
	IF(DSP.EQ.3) THEN
	IF(ZE.LT.0.0) GO TO 500
	YX=SQRT(ZE)
	ENDIF
	IF(DSP.EQ.4) YX=S*YN
	Y=AUSY*YX+BUSY
	IF(Y.LT.YYS.OR.Y.GT.YYF) GO TO 500
	IF(NC.EQ.0) CALL TPLOT(0,X,Y)
	NC=1
      CALL TPLOT(1,X,Y)
  500 CONTINUE
	CALL TPLOT(2,0,0)
C
	CALL CURSOR(ID,X,T,ITERM)  ! IF N TRY AGAIN
	IF(ID.NE.'Y') RETURN
	DO 501 I=NS,NF
	S=A
	X=AMUX*I+BMUX
	DO 401 J=1,IORD
401	S=S+BB(J)*X**J
	L=I
	READ(LUB'L) B
	B=B-S
C
	IF(B.LT.0.0) THEN
	IF(ABS(B).GT.ZZ) ZZ=ABS(B)+1.0
	ENDIF
C
501	WRITE(LUB'L) B
C
  999 CONTINUE
      CALL TPLOT(2,0,0)
      RETURN
      END
