      SUBROUTINE Y12MBF(N, Z, A, SNR, NN, RNR, NN1, HA, IHA, AFLAG,
     1 IFLAG,IFAIL)
C
C
C  THE NON-ZERO ELEMENTS OF A SPARSE MATRIX A ARE PREPARED  IN ORDER TO
C  SOLVE THE SYSTEM AX=B BY USE OF SPARSE MATRIX TECHNIQUE/
C
C
      IMPLICIT DOUBLE PRECISION(A-B,G,P,T-Y),INTEGER(C,F,H-N,R-S,Z)
      DOUBLE PRECISION A(NN), AFLAG(8)
      INTEGER SNR(NN), RNR(NN1), HA(IHA,11), IFLAG(10)
      MODE=IFLAG(4)
      IFAIL=0
      IF(N.LT.2)IFAIL=12
      IF(Z.LE.0)IFAIL=13
      IF(NN.LT.2*Z)IFAIL=5
      IF(NN1.LT.Z)IFAIL=6
      IF(IFAIL.EQ.0.AND.N.GT.Z)IFAIL=14
      IF(IHA.LT.N)IFAIL=15
      IF(MODE.LT.0)IFAIL=16
      IF(MODE.GT.2)IFAIL=16
      IF(IFAIL.NE.0) GO TO 22
      GT1=0.0D0
      DO 10 I=1,N
      HA(I,2)=0
      HA(I,3)=0
   10 HA(I,6)=0
C
C  FIND THE NUMBER OF THE NON-ZERO ELEMENTS IN EACH ROW AND COLUMN;MOVE
C  THE NON-ZERO ELEMENTS IN THE END OF THE ARRAYS A AND SNR;FIND THE
C  LARGEST NON-ZERO ELEMENT IN A(IN ABSOLUTE VALUE).
C
      DO 20 I=1,Z
      T=DABS(A(I))
      L3=RNR(I)
      L4=SNR(I)
      IF(L4.GT.N.OR.L4.LT.1)IFAIL=24
      IF(L3.GT.N.OR.L3.LT.1)IFAIL=25
      HA(L3,3)=HA(L3,3)+1
      HA(L4,6)=HA(L4,6)+1
      IF(T.GT.GT1)GT1=T
      A(Z+I)=A(I)
   20 SNR(Z+I)=SNR(I)
      IF(IFAIL.GT.0)GO TO 22
C
C  STORE THE INFORMATION OF THE ROW STARTS(IN HA(I,1))AND OF THE COLUMN
C  STARTS(IN HA(I,4)).
C
      L1=1
      L2=1
      DO 40 I=1,N
      L3=HA(I,3)
      L4=HA(I,6)
      IF(L3.GT.0)GO TO 21
      IFAIL=17
      GO TO 22
   21 IF(L4.GT.0)GO TO 23
      IFAIL=18
      GO TO 22
   23 IF(MODE.EQ.2)GO TO 30
      HA(I,9)=L3
      HA(I,10)=L4
      HA(I,11)=0
      HA(L3,2)=HA(L3,2)+1
      HA(I,5)=L3
   30 HA(I,1)=L1
      HA(I,4)=L2
      L1=L1+L3
      L2=L2+L4
      HA(I,3)=0
   40 HA(I,6)=0
C
C  STORE THE NON-ZERO ELEMENTS OF MATRIX A(ORDERED IN ROWS) IN THE
C  FIRST Z LOCATIONS OF THE ARRAY A.DO THE SAME FOR THEIR COLUMN NUMBERS
C
      DO 50 I=1,Z
      L1=Z+I
      L3=RNR(I)
      L2=HA(L3,1)+HA(L3,3)
      A(L2)=A(L1)
      SNR(L2)=SNR(L1)
   50 HA(L3,3)=HA(L3,3)+1
C
C  STORE THE ROW NUMBERS OF THE NON-ZERO ELEMENTS ORDERED BY COLUMNS IN
C  THE FIRST Z LOCATIONS OF THE ARRAY RNR. STORE INFORMATION ABOUT ROW
C  ENDS(IN HA(I,3)).
C
      L4=1
      DO 70 I=1,N
      IF(MODE.EQ.2)GO TO 60
      IF(HA(I,2).EQ.0)GO TO 60
      HA(I,11)=L4
      L4=L4+HA(I,2)
      HA(I,2)=HA(I,11)
   60 HA(I,3)=HA(I,1)+HA(I,3)-1
      L1=HA(I,1)
      L2=HA(I,3)
      DO 70 J=L1,L2
      L3=SNR(J)
      R=HA(L3,6)
      INDEX=HA(L3,4)+R
      RNR(INDEX)=I
      IF(R.EQ.0)GO TO 70
      IF(J.EQ.L1)GO TO 70
      IF(RNR(INDEX-1).NE.I)GO TO 70
      IFAIL=11
      GO TO 22
   70 HA(L3,6)=R+1
      DO 90 I=1,N
      IF(MODE.EQ.2)GO TO 80
      L3=HA(I,5)
      L5=HA(L3,2)
      HA(L5,8)=I
      HA(I,7)=L5
      HA(L3,2)=HA(L3,2)+1
   80 CONTINUE
   90 HA(I,6)=HA(I,4)+HA(I,6)-1
      AFLAG(6)=GT1
      IFLAG(6)=0
      IFLAG(7)=0
      IFLAG(8)=Z
      IFLAG(1)=-1
22    RETURN
      END
