      SUBROUTINE Y12MDF(N,A,NN,B,PIVOT,SNR,HA,IHA,IFLAG,IFAIL)
      IMPLICIT DOUBLE PRECISION(A-B,G,P,T-Y),INTEGER (C,F,H-N,R-S,Z)
      DOUBLE PRECISION A(NN), PIVOT(N), B(N)
      INTEGER SNR(NN), HA(IHA,11), IFLAG(10)
      IFAIL=0
      IF(IFLAG(1).EQ.-2)GO TO 1000
      IFAIL=1
      GO TO 1110
1000  MODE=IFLAG(4)
      IPIV=IFLAG(3)
      N8=N+1
      N7=N-1
      STATE=IFLAG(5)
C
C  SOLVE THE SYSTEM WITH LOWER TRIANGULAR MATRIX  L  (IF THE
C  LU-FACTORIZATION IS AVAILABLE).
C
      IF(STATE.NE.3)GO TO 1051
      IF(IPIV.EQ.0)GO TO 1020
      DO 1010 I=1,N7
      L1=HA(I,7)
      T=B(L1)
      B(L1)=B(I)
      B(I)=T
1010  CONTINUE
1020  CONTINUE
      DO 1050 I=1,N
      RR1=HA(I,1)
      RR2=HA(I,2)-1
      IF(RR1.GT.RR2)GO TO 1040
      DO 1030 J=RR1,RR2
      L1=SNR(J)
 1030 B(I)=B(I)-A(J)*B(L1)
 1040 CONTINUE
 1050 CONTINUE
C
C  SOLVE THE SYSTEM WITH UPPER TRIAGULAR MATRIX.
C
 1051 CONTINUE
      DO 1090 I=1,N
      R1=N8-I
      RR1=HA(R1,2)
      RR2=HA(R1,3)
      IF(RR2.LT.RR1)   GO TO 1080
      DO 1070 J=RR1,RR2
      R2=SNR(J)
 1070 B(R1)=B(R1)-A(J)*B(R2)
 1080 CONTINUE
 1090 B(R1)=B(R1)/PIVOT(R1)
C
C IF INTERCHANGES WERE USED DURING THE  ELIMINATION THEN A REORDERING IN
C LUTION VECTOR IS MADE.
C
      IF(IPIV.EQ.0)GO TO 1110
      DO 1100 I=1,N7
      R1=N-I
      R2=HA(R1,8)
      T=B(R2)
      B(R2)=B(R1)
 1100 B(R1)=T
 1110 RETURN
      END
