c
c*******************************************************************************
c
      subroutine SCALE ( K, DELK, ldK, nr, nc, y, stdevy, S2, correl,
c
     1                   A, DELA, b, ipr, iprint, mou )
c
c+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
c
c  A subroutine to scale the matrix  K  and the r.h.s. vector  y  with
c          the standard deviations of the errors in the latter.
c
      logical  ipr, correl
c
      real  K(ldK,nc), DELK(ldK,nc), y(nr), stdevy(nr), 
     1      A(ldK,nc), DELA(ldK,nc), b(nr), S2(ldK,ldK)
c
c+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
c
      if ( .not. correl ) then
c                             -- For diagonal variance-covariance matrix
             do j=1,nc
c
                do i=1,nr
                      A(i,j) = K(i,j) / stdevy(i)
                   DELA(i,j) = DELK(i,j) / stdevy(i)
                end do
c
             end do
c
             do i = 1, nr
                b(i) = y(i) / stdevy(i)
             end do
c
      end if
c
c+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
c
      if ( correl ) then
c                       -- Factor variance-covariance matrix:  S**2 = L L**T
c           ----------------------------------------
             call SPOTRF ( 'L', nr, S2, ldK, info )
c           ----------------------------------------
              if ( info .ne. 0 ) then
                                     print 20, info
                        if (ipr) write(mou,20) info
              end if
c                       -- Invert the lower triangular matrix L
c            ---------------------------------------------
              call STRTRI ( 'L', 'N', nr, S2, ldK, info )
c            ---------------------------------------------
              if ( info .ne. 0 ) then
                                     print 30, info
                        if (ipr) write(mou,30) info
              end if
c
              do i = 1, nr
c
                    b(i) = 0.0
                    do j = 1, i
                       b(i) = b(i) + S2(i,j) * y(j)
                    end do
c
                    do j = 1, nc
c
                          A(i,j) = 0.0
                       DELA(i,j) = 0.0
                       do kk = 1, i
                              A(i,j) =    A(i,j) + S2(i,kk)*   K(kk,j)
                           DELA(i,j) = DELA(i,j) + S2(i,kk)*DELK(kk,j)
                       end do
c
                    end do
c
              end do
c
      end if
c
   20 format (' '/' '/' ****** Error in SPOTRF ****** info =', i4 )
c
   30 format (' '/' '/' ****** Error in STRTRI ****** info =', i4 )
c
c+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
c
      return
c
      end

