      SUBROUTINE BSL2 (T,N,K,TAU,GTAU,WGT,NTAU,BCOEF,WK,Q,IERR)
C
C   BSL2 PRODUCES THE B-SPLINE COEFFICIENTS BCOEF OF THE PIECEWISE
C   POLYNOMIAL P(X) OF ORDER K WITH KNOTS T(I) (I=1,...,N+K) WHICH
C   MINIMIZES  SUM(WGT(I)*(P(TAU(I))-GTAU(I))**2).
C
C ******  I N P U T  ******
C   T     KNOT SEQUENCE OF LENGTH N+K.
C   N     DIMENSION OF THE PIECEWISE POLYNOMIAL SPACE.
C   K     ORDER OF THE B-SPLINES.
C   TAU   ARRAY OF LENGTH NTAU CONTAINING DATA POINT ABSCISSAE.
C   GTAU  ARRAY OF LENGTH NTAU CONTAINING DATA POINT ORDINATES.
C   WGT   ARRAY OF LENGTH NTAU CONTAINING THE WEIGHTS.
C   NTAU  NUMBER OF DATA POINTS TO BE FITTED.
C
C ******  O U T P U T  ******
C   BCOEF ARRAY OF LENGTH N CONTAINING THE B-SPLINE COEFFICIENTS
C         OF THE L2 APPROXIMATION.
C   IERR  INTEGER SPECIFYING THE STATUS OF THE RESULTS. IERR = 0
C         IF NO INPUT ERRORS ARE DETECTED. OTHERWISE IERR = 1.
C
      REAL TAU(NTAU),GTAU(NTAU),WGT(NTAU)
      REAL T(1),BCOEF(N),WK(N),Q(K,N)
      IF (K.LT.1 .OR. N.LT.K) GO TO 100
      IF (T(N) .GE. T(N+1)) GO TO 100
      X = T(K)
C
      DO 11 J = 1,N
      BCOEF(J) = 0.0
         DO 10 I = 1,K
   10    Q(I,J) = 0.0
   11 CONTINUE
C
      NPK = N + K
      LEFT = K
      LEFTMK = 0
      DO 41 LL = 1,NTAU
      IF (TAU(LL) .LT. X) GO TO 100
      X = TAU(LL)
C     *** FIND THE INDEX LEFT SUCH THAT
C             T(LEFT) .LE. TAU(LL) .LT. T(LEFT+1)
   20 IF (LEFT .EQ. N) GO TO 21
      IF (TAU(LL) .LT. T(LEFT+1)) GO TO 30
      LEFT = LEFT + 1
      LEFTMK = LEFTMK + 1
      GO TO 20
   21 IF (TAU(LL) .GT. T(LEFT+1)) GO TO 100
C
   30 CALL BSPEV(T,NPK,TAU(LL),LEFT,0,K,WK,IERR)
C
      DO 41 MM = 1,K
      DW = WK(MM)*WGT(LL)
      J = LEFTMK + MM
      BCOEF(J) = DW*GTAU(LL) + BCOEF(J)
      I = 1
         DO 40 JJ = MM,K
         Q(I,J) = WK(JJ)*DW + Q(I,J)
   40    I = I + 1
   41 CONTINUE
C
C        SOLVE THE NORMAL EQUATIONS
C
      CALL BCHFAC(Q,K,N,WK)
      CALL BCHSLV(Q,K,N,BCOEF)
      RETURN
C
C             ERROR RETURN
C
  100 IERR = 1
      RETURN
      END
