' ******************************************************************
' Back transformation of eigenvectors
' ******************************************************************

SUB BalBak(Z()     AS DOUBLE,  _ 
           Lo      AS INTEGER, _ 
           Hi      AS INTEGER, _ 
           Scale() AS DOUBLE,  _ 
           M       AS INTEGER)
' ------------------------------------------------------------------
' This subroutine is a translation of the EISPACK subroutine Balbak
'
' This subroutine forms the eigenvectors of a real general matrix
' by back transforming those of the corresponding balanced matrix
' determined by Balance.
'
' On input:
'
'   Z contains the real and imaginary parts of the eigenvectors
'   to be back transformed.
'
'   Lo and Hi are integers determined by Balance.
'
'   Scale contains information determining the permutations
'   and scaling factors used by Balance.
'
'   M is the index of the latest column of Z to be back transformed.
'
' On output:
'
'   Z contains the real and imaginary parts of the transformed
'   eigenvectors in its columns Lbound(Z)..M
' ------------------------------------------------------------------

  DIM AS INTEGER Lb, Ub, I, J, K
  DIM AS DOUBLE  S

  Lb = LBOUND(Z, 1)
  Ub = UBOUND(Z, 1)

  IF M < Lb THEN EXIT SUB

  IF Hi <> Lo THEN
    FOR I = Lo TO Hi
      S = Scale(I)
      ' Left hand eigenvectors are back transformed if the
      '  foregoing statement is replaced by S = 1.0 / Scale(I)
      FOR J = Lb TO M
        Z(I, J) = Z(I, J) * S
      NEXT J
    NEXT I
  END IF

  FOR I = (Lo - 1) TO Lb STEP -1
    K = INT(Scale(I))
    IF K <> I THEN
      FOR J = Lb TO M
        SWAP Z(I, J), Z(K, J)
      NEXT J
    END IF
  NEXT I

  FOR I = (Hi + 1) TO Ub
    K = INT(Scale(I))
    IF K <> I THEN
      FOR J = Lb TO M
        SWAP Z(I, J), Z(K, J)
      NEXT J
    END IF
  NEXT I
END SUB

