program ch0808
    ! Initialising a Rank 2 Array
    implicit none

    integer, dimension(1:2,1:4) :: x
    integer, dimension(1:8) :: y = [ 1,2,3,4,5,6,7,8 ]
    integer, dimension(1:6) :: z = [ 1,2,3,4,5,6 ]
    integer :: r, c

    print *, ' Source array y'
    print *, y
    print *, ' Source array z'
    print *, z
    print *, ' Simple reshape sizes match'
    x = reshape(y, [2,4])
    do r = 1, 2
        print *, (x(r,c), c=1,4)
    end do

    print *, &
        ' Source 2 elements smaller pad with 0'
    x = reshape(z, [2,4], [0,0])
    do r = 1, 2
        print *, (x(r,c), c=1,4)
    end do

    print *, &
        ' As previous now specify order as 1*2'
    x = reshape(z, [2,4], [0,0], [1,2])
    do r = 1, 2
        print *, x(r, 1:4)
    end do

    print *, &
        ' As previous now specify order as 2*1'
    x = reshape(z, [2,4], [0,0], [2,1])
    do r = 1, 2
        print *, x(r, 1:4)
    end do
end program


      SUBROUTINE AB09IX( DICO, JOB, FACT, ORDSEL, N, M, P, NR,
     $                   SCALEC, SCALEO, A, LDA, B, LDB, C, LDC, D, LDD,
     $                   TI, LDTI, T, LDT, NMINR, HSV, TOL1, TOL2,
     $                   IWORK, DWORK, LDWORK, IWARN, INFO )
C
C     SLICOT RELEASE 5.7.
C
C     Copyright (c) 2002-2020 NICONET e.V.
C
C     PURPOSE
C
C     To compute a reduced order model (Ar,Br,Cr,Dr) for an original
C     state-space representation (A,B,C,D) by using the square-root or
C     balancing-free square-root Balance & Truncate (B&T) or
C     Singular Perturbation Approximation (SPA) model reduction methods.
C     The computation of truncation matrices TI and T is based on
C     the Cholesky factor S of a controllability Grammian P = S*S'
C     and the Cholesky factor R of an observability Grammian Q = R'*R,
C     where S and R are given upper triangular matrices.
C
C     For the B&T approach, the matrices of the reduced order system
C     are computed using the truncation formulas:
C
C          Ar = TI * A * T ,  Br = TI * B ,  Cr = C * T .     (1)
C
C     For the SPA approach, the matrices of a minimal realization
C     (Am,Bm,Cm) are computed using the truncation formulas:
C
C          Am = TI * A * T ,  Bm = TI * B ,  Cm = C * T .     (2)
C
C     Am, Bm, Cm and D serve further for computing the SPA of the given
C     system.
C
C     ARGUMENTS
C
C     Mode Parameters
C
C     DICO    CHARACTER*1
C             Specifies the type of the original system as follows:
C             = 'C':  continuous-time system;
C             = 'D':  discrete-time system.
C
C     JOB     CHARACTER*1
C             Specifies the model reduction approach to be used
C             as follows:
C             = 'B':  use the square-root B&T method;
C             = 'F':  use the balancing-free square-root B&T method;
C             = 'S':  use the square-root SPA method;
C             = 'P':  use the balancing-free square-root SPA method.
C
C     FACT    CHARACTER*1
C             Specifies whether or not, on entry, the matrix A is in a
C             real Schur form, as follows:
C             = 'S':  A is in a real Schur form;
C             = 'N':  A is a general dense square matrix.
C
C     ORDSEL  CHARACTER*1
C             Specifies the order selection method as follows:
C             = 'F':  the resulting order NR is fixed;
C             = 'A':  the resulting order NR is automatically determined
C                     on basis of the given tolerance TOL1.
C
C     Input/Output Parameters
C
C     N       (input) INTEGER
C             The order of the original state-space representation,
C             i.e., the order of the matrix A.  N >= 0.
C
C     M       (input) INTEGER
C             The number of system inputs.  M >= 0.
C
C     P       (input) INTEGER
C             The number of system outputs.  P >= 0.
C
C     NR      (input/output) INTEGER
C             On entry with ORDSEL = 'F', NR is the desired order of
C             the resulting reduced order system.  0 <= NR <= N.
C             On exit, if INFO = 0, NR is the order of the resulting
C             reduced order model. NR is set as follows:
C             if ORDSEL = 'F', NR is equal to MIN(NR,NMINR), where NR
C             is the desired order on entry and NMINR is the number of
C             the Hankel singular values greater than N*EPS*S1, where
C             EPS is the machine precision (see LAPACK Library Routine
C             DLAMCH) and S1 is the largest Hankel singular value
C             (computed in HSV(1));
C             NR can be further reduced to ensure HSV(NR) > HSV(NR+1);
C             if ORDSEL = 'A', NR is equal to the number of Hankel
C             singular values greater than MAX(TOL1,N*EPS*S1).
C
C     SCALEC  (input) DOUBLE PRECISION
C             Scaling factor for the Cholesky factor S of the
C             controllability Grammian, i.e., S/SCALEC is used to
C             compute the Hankel singular values.  SCALEC > 0.
C
C     SCALEO  (input) DOUBLE PRECISION
C             Scaling factor for the Cholesky factor R of the
C             observability Grammian, i.e., R/SCALEO is used to
C             compute the Hankel singular values.  SCALEO > 0.
C
C     A       (input/output) DOUBLE PRECISION array, dimension (LDA,N)
C             On entry, the leading N-by-N part of this array must
C             contain the state dynamics matrix A. If FACT = 'S',
C             A is in a real Schur form.
C             On exit, if INFO = 0, the leading NR-by-NR part of this
C             array contains the state dynamics matrix Ar of the
C             reduced order system.
C
C     LDA     INTEGER
C             The leading dimension of array A.  LDA >= MAX(1,N).
C
C     B       (input/output) DOUBLE PRECISION array, dimension (LDB,M)
C             On entry, the leading N-by-M part of this array must
C             contain the original input/state matrix B.
C             On exit, if INFO = 0, the leading NR-by-M part of this
C             array contains the input/state matrix Br of the reduced
C             order system.
C
C     LDB     INTEGER
C             The leading dimension of array B.  LDB >= MAX(1,N).
C
C     C       (input/output) DOUBLE PRECISION array, dimension (LDC,N)
C             On entry, the leading P-by-N part of this array must
C             contain the original state/output matrix C.
C             On exit, if INFO = 0, the leading P-by-NR part of this
C             array contains the state/output matrix Cr of the reduced
C             order system.
C
C     LDC     INTEGER
C             The leading dimension of array C.  LDC >= MAX(1,P).
C
C     D       (input/output) DOUBLE PRECISION array, dimension (LDD,M)
C             On entry, if JOB = 'S' or JOB = 'P', the leading P-by-M
C             part of this array must contain the original input/output
C             matrix D.
C             On exit, if INFO = 0 and JOB = 'S' or JOB = 'P', the
C             leading P-by-M part of this array contains the
C             input/output matrix Dr of the reduced order system.
C             If JOB = 'B' or JOB = 'F', this array is not referenced.
C
C     LDD     INTEGER
C             The leading dimension of array D.
C             LDD >= 1,        if JOB = 'B' or JOB = 'F';
C             LDD >= MAX(1,P), if JOB = 'S' or JOB = 'P'.
C
C     TI      (input/output) DOUBLE PRECISION array, dimension (LDTI,N)
C             On entry, the leading N-by-N upper triangular part of
C             this array must contain the Cholesky factor S of a
C             controllability Grammian P = S*S'.
C             On exit, if INFO = 0, and NR > 0, the leading NMINR-by-N
C             part of this array contains the left truncation matrix
C             TI in (1), for the B&T approach, or in (2), for the
C             SPA approach.
C
C     LDTI    INTEGER
C             The leading dimension of array TI.  LDTI >= MAX(1,N).
C
C     T       (input/output) DOUBLE PRECISION array, dimension (LDT,N)
C             On entry, the leading N-by-N upper triangular part of
C             this array must contain the Cholesky factor R of an
C             observability Grammian Q = R'*R.
C             On exit, if INFO = 0, and NR > 0, the leading N-by-NMINR
C             part of this array contains the right truncation matrix
C             T in (1), for the B&T approach, or in (2), for the
C             SPA approach.
C
C     LDT     INTEGER
C             The leading dimension of array T.  LDT >= MAX(1,N).
C
C     NMINR   (output) INTEGER
C             The number of Hankel singular values greater than
C             MAX(TOL2,N*EPS*S1).
C             Note: If S and R are the Cholesky factors of the
C             controllability and observability Grammians of the
C             original system (A,B,C,D), respectively, then NMINR is
C             the order of a minimal realization of the original system.
C
C     HSV     (output) DOUBLE PRECISION array, dimension (N)
C             If INFO = 0, it contains the Hankel singular values,
C             ordered decreasingly. The Hankel singular values are
C             singular values of the product R*S.
C
C     Tolerances
C
C     TOL1    DOUBLE PRECISION
C             If ORDSEL = 'A', TOL1 contains the tolerance for
C             determining the order of the reduced system.
C             For model reduction, the recommended value lies in the
C             interval [0.00001,0.001].
C             If TOL1 <= 0 on entry, the used default value is
C             TOL1 = N*EPS*S1, where EPS is the machine precision
C             (see LAPACK Library Routine DLAMCH) and S1 is the largest
C             Hankel singular value (computed in HSV(1)).
C             If ORDSEL = 'F', the value of TOL1 is ignored.
C
C     TOL2    DOUBLE PRECISION
C             The tolerance for determining the order of a minimal
C             realization of the system.
C             The recommended value is TOL2 = N*EPS*S1.
C             This value is used by default if TOL2 <= 0 on entry.
C             If TOL2 > 0, and ORDSEL = 'A', then TOL2 <= TOL1.
C
C     Workspace
C
C     IWORK   INTEGER array, dimension (LIWORK), where
C             LIWORK = 0,   if JOB = 'B';
C             LIWORK = N,   if JOB = 'F';
C             LIWORK = 2*N, if JOB = 'S' or 'P'.
C
C     DWORK   DOUBLE PRECISION array, dimension (LDWORK)
C             On exit, if INFO = 0, DWORK(1) returns the optimal value
C             of LDWORK.
C
C     LDWORK  INTEGER
C             The length of the array DWORK.
C             LDWORK >= MAX( 1, 2*N*N + 5*N, N*MAX(M,P) ).
C             For optimum performance LDWORK should be larger.
C
C     Warning Indicator
C
C     IWARN   INTEGER
C             = 0:  no warning;
C             = 1:  with ORDSEL = 'F', the selected order NR is greater
C                   than NMINR, the order of a minimal realization of
C                   the given system; in this case, the resulting NR is
C                   set automatically to NMINR;
C             = 2:  with ORDSEL = 'F', the selected order NR corresponds
C                   to repeated singular values, which are neither all
C                   included nor all excluded from the reduced model;
C                   in this case, the resulting NR is set automatically
C                   to the largest value such that HSV(NR) > HSV(NR+1).
C
C     Error Indicator
C
C     INFO    INTEGER
C             = 0:  successful exit;
C             < 0:  if INFO = -i, the i-th argument had an illegal
C                   value;
C             = 1:  the computation of Hankel singular values failed.
C
C     METHOD
C
C     Let be the stable linear system
C
C          d[x(t)] = Ax(t) + Bu(t)
C          y(t)    = Cx(t) + Du(t),                             (3)
C
C     where d[x(t)] is dx(t)/dt for a continuous-time system and x(t+1)
C     for a discrete-time system. The subroutine AB09IX determines for
C     the given system (3), the matrices of a reduced NR order system
C
C          d[z(t)] = Ar*z(t) + Br*u(t)
C          yr(t)   = Cr*z(t) + Dr*u(t),                         (4)
C
C     by using the square-root or balancing-free square-root
C     Balance & Truncate (B&T) or Singular Perturbation Approximation
C     (SPA) model reduction methods.
C
C     The projection matrices TI and T are determined using the
C     Cholesky factors S and R of a controllability Grammian P and an
C     observability Grammian Q.
C     The Hankel singular values HSV(1), ...., HSV(N) are computed as
C     singular values of the product R*S.
C
C     If JOB = 'B', the square-root Balance & Truncate technique
C     of [1] is used.
C
C     If JOB = 'F', the balancing-free square-root version of the
C     Balance & Truncate technique [2] is used.
C
C     If JOB = 'S', the square-root version of the Singular Perturbation
C     Approximation method [3,4] is used.
C
C     If JOB = 'P', the balancing-free square-root version of the
C     Singular Perturbation Approximation method [3,4] is used.
C
C     REFERENCES
C
C     [1] Tombs M.S. and Postlethwaite I.
C         Truncated balanced realization of stable, non-minimal
C         state-space systems.
C         Int. J. Control, Vol. 46, pp. 1319-1330, 1987.
C
C     [2] Varga A.
C         Efficient minimal realization procedure based on balancing.
C         Proc. of IMACS/IFAC Symp. MCTS, Lille, France, May 1991,
C         A. El Moudni, P. Borne, S. G. Tzafestas (Eds.),
C         Vol. 2, pp. 42-46.
C
C     [3] Liu Y. and Anderson B.D.O.
C         Singular Perturbation Approximation of balanced systems.
C         Int. J. Control, Vol. 50, pp. 1379-1405, 1989.
C
C     [4] Varga A.
C         Balancing-free square-root algorithm for computing singular
C         perturbation approximations.
C         Proc. 30-th CDC, Brighton, Dec. 11-13, 1991,
C         Vol. 2, pp. 1062-1065.
C
C     NUMERICAL ASPECTS
C
C     The implemented method relies on accuracy enhancing square-root
C     or balancing-free square-root methods.
C
C     CONTRIBUTORS
C
C     A. Varga, German Aerospace Center, Oberpfaffenhofen, August 2000.
C     D. Sima, University of Bucharest, August 2000.
C     V. Sima, Research Institute for Informatics, Bucharest, Aug. 2000.
C
C     REVISIONS
C
C     V. Sima, Research Institute for Informatics, Bucharest, Dec. 2000,
C              Sep. 2001.
C
C     KEYWORDS
C
C     Balance and truncate, minimal state-space representation,
C     model reduction, multivariable system,
C     singular perturbation approximation, state-space model.
C
C     ******************************************************************
C
C     .. Parameters ..
      DOUBLE PRECISION  ONE, ZERO
      PARAMETER         ( ONE = 1.0D0, ZERO = 0.0D0 )
C     .. Scalar Arguments ..
      CHARACTER         DICO, FACT, JOB, ORDSEL
      INTEGER           INFO, IWARN, LDA, LDB, LDC, LDD, LDT, LDTI,
     $                  LDWORK, M, N, NMINR, NR, P
      DOUBLE PRECISION  SCALEC, SCALEO, TOL1, TOL2
C     .. Array Arguments ..
      INTEGER           IWORK(*)
      DOUBLE PRECISION  A(LDA,*), B(LDB,*), C(LDC,*), D(LDD,*),
     $                  DWORK(*), HSV(*), T(LDT,*), TI(LDTI,*)
C     .. Local Scalars ..
      LOGICAL           BAL, BTA, DISCR, FIXORD, RSF, SPA
      INTEGER           IERR, IJ, J, K, KTAU, KU, KV, KW, LDW, LW,
     $                  NRED, NR1, NS, WRKOPT
      DOUBLE PRECISION  ATOL, RCOND, SKP, TEMP, TOLDEF
C     .. External Functions ..
      LOGICAL           LSAME
      DOUBLE PRECISION  DLAMCH
      EXTERNAL          DLAMCH, LSAME
C     .. External Subroutines ..
      EXTERNAL          AB09DD, DGEMM,  DGEMV, DGEQRF, DGETRF, DGETRS,
     $                  DLACPY, DORGQR, DSCAL, DTRMM,  DTRMV,  MA02AD,
     $                  MB03UD, XERBLA
C     .. Intrinsic Functions ..
      INTRINSIC         DBLE, INT, MAX, MIN, SQRT
C     .. Executable Statements ..
C
      INFO   = 0
      IWARN  = 0
      DISCR  = LSAME( DICO,   'D' )
      BTA    = LSAME( JOB,    'B' ) .OR. LSAME( JOB, 'F' )
      SPA    = LSAME( JOB,    'S' ) .OR. LSAME( JOB, 'P' )
      BAL    = LSAME( JOB,    'B' ) .OR. LSAME( JOB, 'S' )
      RSF    = LSAME( FACT,   'S' )
      FIXORD = LSAME( ORDSEL, 'F' )
C
      LW = MAX( 1, 2*N*N + 5*N, N*MAX( M, P ) )
C
C     Test the input scalar arguments.
C
      IF( .NOT. ( LSAME( DICO, 'C' ) .OR. DISCR ) ) THEN
         INFO = -1
      ELSE IF( .NOT. ( BTA .OR. SPA ) ) THEN
         INFO = -2
      ELSE IF( .NOT. ( RSF .OR. LSAME( FACT, 'N' ) ) ) THEN
         INFO = -3
      ELSE IF( .NOT. ( FIXORD .OR. LSAME( ORDSEL, 'A' ) ) ) THEN
         INFO = -4
      ELSE IF( N.LT.0 ) THEN
         INFO = -5
      ELSE IF( M.LT.0 ) THEN
         INFO = -6
      ELSE IF( P.LT.0 ) THEN
         INFO = -7
      ELSE IF( FIXORD .AND. ( NR.LT.0 .OR. NR.GT.N ) ) THEN
         INFO = -8
      ELSE IF( SCALEC.LE.ZERO ) THEN
         INFO = -9
      ELSE IF( SCALEO.LE.ZERO ) THEN
         INFO = -10
      ELSE IF( LDA.LT.MAX( 1, N ) ) THEN
         INFO = -12
      ELSE IF( LDB.LT.MAX( 1, N ) ) THEN
         INFO = -14
      ELSE IF( LDC.LT.MAX( 1, P ) ) THEN
         INFO = -16
      ELSE IF( LDD.LT.1 .OR. ( SPA .AND. LDD.LT.P ) ) THEN
         INFO = -18
      ELSE IF( LDTI.LT.MAX( 1, N ) ) THEN
         INFO = -20
      ELSE IF( LDT.LT.MAX( 1, N ) ) THEN
         INFO = -22
      ELSE IF( TOL2.GT.ZERO .AND. .NOT.FIXORD .AND. TOL2.GT.TOL1 ) THEN
         INFO = -26
      ELSE IF( LDWORK.LT.LW ) THEN
         INFO = -29
      END IF
C
      IF( INFO.NE.0 ) THEN
C
C        Error return.
C
         CALL XERBLA( 'AB09IX', -INFO )
         RETURN
      END IF
C
C     Quick return if possible.
C
      IF( MIN( N, M, P ).EQ.0 ) THEN
         NR = 0
         NMINR = 0
         DWORK(1) = ONE
         RETURN
      END IF
C
C     Save S in DWORK(KV).
C
      KV = 1
      KU = KV + N*N
      KW = KU + N*N
      CALL DLACPY( 'Upper', N, N, TI, LDTI, DWORK(KV), N )
C                             | x x |
C     Compute R*S in the form | 0 x | in TI.
C
      DO 10 J = 1, N
         CALL DTRMV( 'Upper', 'NoTranspose', 'NonUnit', J, T, LDT,
     $               TI(1,J), 1 )
   10 CONTINUE
C
C     Compute the singular value decomposition R*S = V*Sigma*UT of the
C     upper triangular matrix R*S, with UT in TI and V in DWORK(KU).
C
C     Workspace:  need   2*N*N + 5*N;
C                 prefer larger.
C
      CALL MB03UD( 'Vectors', 'Vectors', N, TI, LDTI, DWORK(KU), N, HSV,
     $             DWORK(KW), LDWORK-KW+1, IERR )
      IF( IERR.NE.0 ) THEN
         INFO = 1
         RETURN
      ENDIF
      WRKOPT = INT( DWORK(KW) ) + KW - 1
C
C     Scale the singular values.
C
      CALL DSCAL( N, ONE / SCALEC / SCALEO, HSV, 1 )
C
C     Partition Sigma, U and V conformally as:
C
C     Sigma = diag(Sigma1,Sigma2,Sigma3),  U = [U1,U2,U3] (U' in TI) and
C     V = [V1,V2,V3] (in DWORK(KU)).
C
C     Compute NMINR, the order of a minimal realization, as the order
C     of [Sigma1 Sigma2].
C
      TOLDEF = DBLE( N )*DLAMCH( 'Epsilon' )
      ATOL   = MAX( TOL2, TOLDEF*HSV(1) )
      NMINR  = N
   20 IF( NMINR.GT.0 ) THEN
         IF( HSV(NMINR).LE.ATOL ) THEN
            NMINR = NMINR - 1
            GO TO 20
         END IF
      END IF
C
C     Compute the order NR of reduced system, as the order of Sigma1.
C
      IF( FIXORD ) THEN
C
C        Check if the desired order is less than the order of a minimal
C        realization.
C
         IF( NR.GT.NMINR ) THEN
C
C           Reduce the order to NMINR.
C
            NR = NMINR
            IWARN = 1
         END IF
C
C        Check for singular value multiplicity at cut-off point.
C
         IF( NR.GT.0 .AND. NR.LT.NMINR ) THEN
            SKP = HSV(NR)
            IF( SKP-HSV(NR+1).LE.TOLDEF*SKP ) THEN
               IWARN = 2
C
C              Reduce the order such that HSV(NR) > HSV(NR+1).
C
   30          NR = NR - 1
               IF( NR.GT.0 ) THEN
                  IF( HSV(NR)-SKP.LE.TOLDEF*SKP ) GO TO 30
               END IF
            END IF
         END IF
      ELSE
C
C        The order is given as the number of singular values
C        exceeding MAX( TOL1, N*EPS*HSV(1) ).
C
         ATOL = MAX( TOL1, ATOL )
         NR   = 0
         DO 40 J = 1, NMINR
            IF( HSV(J).LE.ATOL ) GO TO 50
            NR = NR + 1
   40    CONTINUE
   50    CONTINUE
      ENDIF
C
C     Finish if the order is zero.
C
      IF( NR.EQ.0 ) THEN
         IF( SPA )
     $      CALL AB09DD( DICO, N, M, P, NR, A, LDA, B, LDB, C, LDC,
     $                   D, LDD, RCOND, IWORK, DWORK, IERR )
         DWORK(1) = WRKOPT
         RETURN
      END IF
C
C     Compute NS, the order of Sigma2. For BTA, NS = 0.
C
      IF( SPA ) THEN
         NRED = NMINR
      ELSE
         NRED = NR
      END IF
      NS = NRED - NR
C
C     Compute the truncation matrices.
C
C     Compute TI' = | TI1' TI2' | = R'*| V1 V2 | in DWORK(KU).
C
      CALL DTRMM( 'Left', 'Upper', 'Transpose', 'NonUnit', N, NRED,
     $            ONE, T, LDT, DWORK(KU), N )
C
C     Compute  T = | T1 T2 | = S*| U1 U2 | .
C
      CALL MA02AD( 'Full', NRED, N, TI, LDTI, T, LDT )
      CALL DTRMM( 'Left', 'Upper', 'NoTranspose', 'NonUnit', N,
     $            NRED, ONE, DWORK(KV), N, T, LDT )
C
      KTAU = KW
      IF( BAL ) THEN
         IJ = KU
C
C        Square-Root B&T/SPA method.
C
C        Compute the truncation matrices for balancing
C                        -1/2                -1/2
C               T1*Sigma1     and TI1'*Sigma1    .
C
         DO 60 J = 1, NR
            TEMP = ONE/SQRT( HSV(J) )
            CALL DSCAL( N, TEMP, T(1,J), 1 )
            CALL DSCAL( N, TEMP, DWORK(IJ), 1 )
            IJ = IJ + N
   60    CONTINUE
C
      ELSE
C
C        Balancing-Free B&T/SPA method.
C
C        Compute orthogonal bases for the images of matrices T1 and
C        TI1'.
C
C        Workspace:  need   2*N*N + 2*N;
C                    prefer larger.
C
         KW   = KTAU + NR
         LDW  = LDWORK - KW + 1
         CALL DGEQRF( N, NR, T, LDT, DWORK(KTAU), DWORK(KW), LDW, IERR )
         CALL DORGQR( N, NR, NR, T, LDT, DWORK(KTAU), DWORK(KW), LDW,
     $                IERR )
         CALL DGEQRF( N, NR, DWORK(KU), N, DWORK(KTAU), DWORK(KW), LDW,
     $                IERR )
         WRKOPT = MAX( WRKOPT, INT( DWORK(KW) ) + KW - 1 )
         CALL DORGQR( N, NR, NR, DWORK(KU), N, DWORK(KTAU), DWORK(KW),
     $                LDW, IERR )
         WRKOPT = MAX( WRKOPT, INT( DWORK(KW) ) + KW - 1 )
      ENDIF
C
      IF( NS.GT.0 ) THEN
C
C        Compute orthogonal bases for the images of matrices T2 and
C        TI2'.
C
C        Workspace:  need   2*N*N + 2*N;
C                    prefer larger.
C
         NR1 = NR + 1
         KW  = KTAU + NS
         LDW = LDWORK - KW + 1
         CALL DGEQRF( N, NS, T(1,NR1), LDT, DWORK(KTAU), DWORK(KW), LDW,
     $                IERR )
         CALL DORGQR( N, NS, NS, T(1,NR1), LDT, DWORK(KTAU), DWORK(KW),
     $                LDW, IERR )
         CALL DGEQRF( N, NS, DWORK(KU+N*NR), N, DWORK(KTAU), DWORK(KW),
     $                LDW, IERR )
         WRKOPT = MAX( WRKOPT, INT( DWORK(KW) ) + KW - 1 )
         CALL DORGQR( N, NS, NS, DWORK(KU+N*NR), N, DWORK(KTAU),
     $                DWORK(KW), LDW, IERR )
         WRKOPT = MAX( WRKOPT, INT( DWORK(KW) ) + KW - 1 )
      ENDIF
C
C     Transpose TI' in TI.
C
      CALL MA02AD( 'Full', N, NRED, DWORK(KU), N, TI, LDTI )
C
      IF( .NOT.BAL ) THEN
C                        -1
C        Compute (TI1*T1)  *TI1 in TI.
C
         CALL DGEMM( 'NoTranspose', 'NoTranspose', NR, NR, N, ONE, TI,
     $               LDTI, T, LDT, ZERO, DWORK(KU), N )
         CALL DGETRF( NR, NR, DWORK(KU), N, IWORK, IERR )
         CALL DGETRS( 'NoTranspose', NR, N, DWORK(KU), N, IWORK, TI,
     $                LDTI, IERR )
C
         IF( NS.GT.0 ) THEN
C                           -1
C           Compute (TI2*T2)  *TI2 in TI2.
C
            CALL DGEMM( 'NoTranspose', 'NoTranspose', NS, NS, N, ONE,
     $                  TI(NR1,1), LDTI, T(1,NR1), LDT, ZERO, DWORK(KU),
     $                  N )
            CALL DGETRF( NS, NS, DWORK(KU), N, IWORK, IERR )
            CALL DGETRS( 'NoTranspose', NS, N, DWORK(KU), N, IWORK,
     $                   TI(NR1,1), LDTI, IERR )
         END IF
      END IF
C
C     Compute TI*A*T. Exploit RSF of A if possible.
C     Workspace:  need   N*N.
C
      IF( RSF ) THEN
         IJ = 1
         DO 80 J = 1, N
            K = MIN( J+1, N )
            CALL DGEMV( 'NoTranspose', NRED, K, ONE, TI, LDTI,
     $                  A(1,J), 1, ZERO, DWORK(IJ), 1 )
            IJ = IJ + N
   80    CONTINUE
      ELSE
         CALL DGEMM( 'NoTranspose', 'NoTranspose', NRED, N, N, ONE,
     $               TI, LDTI, A, LDA, ZERO, DWORK, N )
      END IF
      CALL DGEMM( 'NoTranspose', 'NoTranspose', NRED, NRED, N, ONE,
     $            DWORK, N, T, LDT, ZERO, A, LDA )
C
C     Compute TI*B and C*T.
C     Workspace:  need   N*MAX(M,P).
C
      CALL DLACPY( 'Full', N, M, B, LDB, DWORK, N )
      CALL DGEMM( 'NoTranspose', 'NoTranspose', NRED, M, N, ONE, TI,
     $            LDTI, DWORK, N, ZERO, B, LDB )
C
      CALL DLACPY( 'Full', P, N, C, LDC, DWORK, P )
      CALL DGEMM( 'NoTranspose', 'NoTranspose', P, NRED, N, ONE,
     $            DWORK, P, T, LDT, ZERO, C, LDC )
C
C     Compute the singular perturbation approximation if possible.
C     Note that IERR = 1 on exit from AB09DD cannot appear here.
C
C     Workspace:  need real    4*(NMINR-NR);
C                 need integer 2*(NMINR-NR).
C
      IF( SPA) THEN
         CALL AB09DD( DICO, NRED, M, P, NR, A, LDA, B, LDB,
     $                C, LDC, D, LDD, RCOND, IWORK, DWORK, IERR )
      ELSE
         NMINR = NR
      END IF
      DWORK(1) = WRKOPT
C
      RETURN
C *** Last line of AB09IX ***
      END


        module fft_module
          use m_kind
          implicit none
          private
          public :: fft_window
          integer , parameter :: np2 = 9, nn = 2**np2, nn_2 = nn / 2   ! 2^9 = 512
          real(kd), parameter :: pi = 4 * atan(1.0_kd), pi2 = 2 * pi
          real(kd), parameter :: pi2_n = pi2 / nn
          integer, save :: indx(nn)
          integer, private :: i_
          complex(kd), parameter :: omega(0:*) = [(exp(cmplx(0.0_kd, pi2_n * i_, kind = kd)), i_ = 0, nn - 1)]
          real(kd)   , parameter :: hann_window(*) = [(0.5_kd * (1.0_kd - cos(pi2_n * i_))  , i_ = 0, nn - 1)]
        contains
          subroutine fft_initialize()
            integer :: i, j2, k, n
            do i = 1, nn
              n = 0
              k = i - 1
              do j2 = np2 - 1, 0, -1
                n = n + mod(k, 2) * 2**j2
                k = k / 2
              end do
              indx(i) = n + 1 ! indx = 1..n
            end do
          end subroutine fft_initialize

          subroutine fft_window(x, y)
            real    (kd), intent(in ) :: x(:)
            complex (kd), intent(out) :: y(:)
            logical :: qfirst = .true.
            if (qfirst) then
              qfirst = .false.
              call fft_initialize()
            end if
            y = hann_window * x / nn
            call fft2(y)
          end subroutine fft_window

          subroutine fft2(fft) ! fft_2^np2
            complex (kd), intent(in out) :: fft(:)
            complex (kd) :: tmp1, tmp2, c1
            integer :: i, j, k2, m1, m2, iphase, kn2
            fft = fft(indx)
            do k2 = 1, np2
              kn2 = 2**(k2 - 1)
              do i = 1, nn, 2* kn2
                do j = 1, kn2
                  iphase = 2**(np2 - k2)*(j - 1)
                  c1 = omega( mod(iphase, nn) )
                  m1 = i + j - 1
                  m2 = m1 + kn2
                  tmp1 =      fft(m1)
                  tmp2 = c1 * fft(m2)
                  fft(m1) = tmp1 + tmp2 ! 1 = x^2 ; x = 1 or -1
                  fft(m2) = tmp1 - tmp2
                end do
              end do
            end do
          end subroutine fft2
        end module fft_module

        module m_psycho
          use m_kind
          implicit none
          private
          public :: psychoacoustics
          real(kd), save :: freq_fft(0:256), pseud_bark(0:256), ath_fft(0:256)
          real(kd), save :: crbw_fft(0:256), cbwl_fft(0:256)
          real(kd), save :: sp(256, 256) ! spreading function for masking
          real(kd), save :: scale
          real(kd), parameter :: alpha = 0.27d0 ! non-linear factor
        contains
          subroutine psychoacoustics(pcm, isample_rate, smr)
            use fft_module
            real (kd), intent(in ) :: pcm(:, :)
            integer       , intent(in ) :: isample_rate
            real (kd), intent(out) :: smr(:, :)
            complex(kd) :: cfft(512)
            integer :: ichannel, i0, i1
            logical, save :: qfirst = .true.
            if (qfirst) then
              qfirst = .false.
              call init_absolute_threshold(isample_rate)
            end if
            i0 = 161
            i1 = i0 + 512 - 1
            do ichannel = 1, size(pcm, 2)
              call fft_window(pcm(i0:i1, ichannel), cfft)
              call calc_smr(cfft, smr(:, ichannel))
            end do
          end subroutine

          subroutine init_absolute_threshold(isample_rate)
            integer, intent(in) :: isample_rate
            real (kd) :: freq, tmp
            integer :: i, m, i0, i1
            do i = 0, size(freq_fft) - 1
              freq = real(isample_rate, kind = kd) / 2.0_kd / 1000.0_kd &
                   * real(i, kind = kd) / real(size(freq_fft), kind = kd)
              ath_fft(i) = 3.64_kd * freq**(-0.8_kd)  & !
                         - 6.5_kd * exp(-0.6_kd * (freq - 3.3_kd)**2) + 0.001_kd * freq**4.0_kd
              freq = freq * 1000.0_kd ! khz -> hz
              freq_fft(i) = freq
            end do
            scale =  real(isample_rate, kind = kd) / 2 / 256 ! freq to fft-line scale
            crbw_fft = critical_band_width( freq_fft )       ! critical band width in hz
            cbwl_fft = decibel( crbw_fft )                   ! critical band width in log
            tmp = 0.0_kd ! pseud bark: integrate critical band
            do m = 1, 256
              tmp = tmp + 1.0_kd / crbw_fft(m) ! integration
              pseud_bark(m) = tmp * scale
            end do
            ! spreading function
            forall(i = 1:256, m = 1:256) sp(i, m) = spreading( pseud_bark( i ) - pseud_bark( m ) ) ! top normalized to 1.0
          end subroutine init_absolute_threshold

          pure elemental real(kd) function spreading(z)
            real(kd), intent(in) :: z ! pseud-bark
            if ( z > 0.0d0 ) then
              spreading = -25.0_kd * z
            else
              spreading =  75.0_kd * z
            end if
            spreading = max(-160.0_kd, spreading)
          end function spreading

          pure elemental real(kd) function critical_band_width(f)
            real(kd), intent(in) :: f ! hz
            real(kd), parameter :: gamma = 0.69_kd
            critical_band_width = 25.0_kd + 75.0_kd * ( 1.0_kd + 1.4_kd * (f / 1000.0_kd)**2 )**gamma
          !  critical_band_width = 100.0d0 * ( 1.0d0 + 1.0d0 * (f / 1000.0d0)**2 )**gamma
          end function critical_band_width

          pure elemental real(kd) function decibel(x)
            real (kd), intent(in) :: x
            real (kd) :: tmp
            tmp = max(1.0e-100_kd, x)
            decibel = 10.0e0_kd * log10(tmp)
          end function decibel

          subroutine calc_smr(cfft, smr)
            complex(kd), intent(in) :: cfft(0:)
            real   (kd), intent(out) :: smr(:)
            real   (kd), parameter :: pi = 4 * atan(1.0_kd), pi2 = 2 * pi ! fortran2003
            real   (kd) :: snr(32), rmnr(32)
            real   (kd) :: xa(0:256), ya(0:256), za(0:256)
            integer :: iband, i, m, i0, i1
            xa = 2 * decibel( abs(cfft(0:256)) )
            ya = 0.0_kd
            do i = 1, 256 ! convolution of spreading function
              do m = 1, 256                                                                                ! i maskee, m masker
                ya(i) = ya(i) + 10.0_kd**( ((sp(i, m) + xa(m) - ath_fft(m)) * alpha - cbwl_fft(m)) / 10.0_kd ) ! non-linear sum
              end do
            end do
            ya = max(decibel(ya * scale) / alpha - 11.5_kd, ath_fft - 90.3_kd) ! 11.5 mask factor, 90.3dB = 2^15  ATH shift empirical
        ! effective spl
            do i = 1, 256
              m = nint( crbw_fft(i) / scale )
              i0 = max(i  - m / 2,   1)       !f0 - bw(f0) / 2
              i1 = min(i0 + m - 1, 256)       !f0 + bw(f0) / 2
              za(i) = sum( 10.0_kd**( (xa(i0:i1) * alpha  - cbwl_fft(i)) / 10.0_kd ) )
            end do
            za = decibel(za * scale) / alpha
            ! smr = snr' - mnr'
            do iband = 1, 32
              m = (iband - 1) * 8 + 1
              i0 = m - nint( crbw_fft(m) / 2 / scale ) ! fl - bw(fl) / 2  ; subband [fl..fh]
              i0 = max(i0,   1)
              m = m + 7
              i1 = m + nint( crbw_fft(m) / 2 / scale ) ! fh + bw(fh) / 2
              i1 = min(i1, 256)
              snr(iband)  = maxval( za(i0:i1) )
              rmnr(iband) = minval( ya(i0:i1) )
            end do
            smr = snr - rmnr
           end subroutine calc_smr
        end module m_psycho


MODULE RungeKutta

	use subs_raytracing
	implicit none

	contains

	subroutine RK4(x,y,dt,dxdt,dydt,param1,param2,x_1,y_1)
		!-----------------------------------------------------------------
		! Runge–Kutta fourth-order method
		! CALLING SEQUENCE : RK4(x,y,dt,dxdt,dydt,param1,x_1,y_1)
		! INPUTS:     x: 3*Nray dimension vector
		!             y: 3*Nray dimension vector
		!            dt: integration time step
		!          dxdt: the derivative of x
		!          dydt: the derivative of y
		!        param1: parameter --> f
		!	 param2: parameter --> mode ('X' ou 'O' ou 'V')
		! OUTPUTS:  x_1: 3*Nray dimension vector at n+1 step
		!           y_1: 3*Nray dimension vector at n+1 step
		!-----------------------------------------------------------------
	implicit none
	real(kind=8), dimension(:,:), intent(in)  :: x,y
	real(kind=8), dimension(:), intent(in)    :: dt
	real(kind=8), intent(in)                  :: param1
	character(len=1), intent(in), dimension(:):: param2
	real(kind=8), dimension(:,:), intent(out) :: x_1,y_1

	external                                  :: dxdt, dydt

	real(kind=8), dimension(3,size(dt))       :: dx1,dy1,dx2,dy2,dx3,dy3,dx4,dy4
	real(kind=8), dimension(3,size(dt))       :: dx1dt,dy1dt,dx2dt,dy2dt,dx3dt
	real(kind=8), dimension(3,size(dt))       :: dy3dt,dx4dt,dy4dt, Yp
	real(kind=8), dimension(size(dt))		  :: Xp
	integer									  :: i
	real(kind=8), dimension(size(dt))		  :: nmode

	call dxdt(x,y,param1,param2,dx1dt,size(dt)) !drdt
	call varplasma(x,param1,Xp,Yp)
	forall (i=1:3) dx1(i,:)=dt(:)*dx1dt(i,:)!*sqrt((1.d0-Xp)/(dx1dt(1,:)**2+dx1dt(2,:)**2+dx1dt(3,:)**2))

	call dydt(x,y,param1,param2,dy1dt,size(dt)) !dkdt
	forall (i=1:3) dy1(i,:)=dt(:)*dy1dt(i,:)!*sqrt((1.d0-Xp)/(dx1dt(1,:)**2+dx1dt(2,:)**2+dx1dt(3,:)**2))

	call dxdt(x+dx1/2.d0,y+1.d0/2.d0*dy1,param1,param2,dx2dt,size(dt)) !drdt
	call varplasma(x+dx1/2.d0,param1,Xp,Yp)
	forall (i=1:3) dx2(i,:)=dt(:)*dx2dt(i,:)!*sqrt((1.d0-Xp)/(dx2dt(1,:)**2+dx2dt(2,:)**2+dx2dt(3,:)**2))

	call dydt(x+dx1/2.d0,y+1.d0/2.d0*dy1,param1,param2,dy2dt,size(dt)) !dkdt
	forall (i=1:3) dy2(i,:)=dt(:)*dy2dt(i,:)!*sqrt((1.d0-Xp)/(dx2dt(1,:)**2+dx2dt(2,:)**2+dx2dt(3,:)**2))

	call dxdt(x+dx2/2.d0,y+1.d0/2.d0*dy2,param1,param2,dx3dt,size(dt)) !drdt
	call varplasma(x+dx2/2.d0,param1,Xp,Yp)
	forall (i=1:3) dx3(i,:)=dt(:)*dx3dt(i,:)!*sqrt((1.d0-Xp)/(dx3dt(1,:)**2+dx3dt(2,:)**2+dx3dt(3,:)**2))

	call dydt(x+dx2/2.d0,y+1.d0/2.d0*dy2,param1,param2,dy3dt,size(dt)) !drdt
	forall (i=1:3) dy3(i,:)=dt(:)*dy3dt(i,:)!*sqrt((1.d0-Xp)/(dx3dt(1,:)**2+dx3dt(2,:)**2+dx3dt(3,:)**2))

	call dxdt(x+dx3,y+dy3,param1,param2,dx4dt,size(dt)) !drdt
	call varplasma(x+dx3,param1,Xp,Yp)
	forall (i=1:3) dx4(i,:)=dt(:)*dx4dt(i,:)!*sqrt((1.d0-Xp)/(dx4dt(1,:)**2+dx4dt(2,:)**2+dx4dt(3,:)**2))

	call dydt(x+dx3,y+dy3,param1,param2,dy4dt,size(dt)) !drdt
	forall (i=1:3) dy4(i,:)=dt(:)*dy4dt(i,:)!*sqrt((1.d0-Xp)/(dx4dt(1,:)**2+dx4dt(2,:)**2+dx4dt(3,:)**2))

	!change of sign of derivatives in Haselgrove_63 needed to get the right equations without B
	where (param2 .eq. 'X')
		nmode =-1.d0
	else where
		nmode = 1.d0
	end where

	forall(i=1:3) x_1(i,:) = x(i,:) + nmode(:)*1.d0/6.d0*(dx1(i,:)+2.d0*dx2(i,:)+2.d0*dx3(i,:)+dx4(i,:))
	forall(i=1:3) y_1(i,:) = y(i,:) + nmode(:)*1.d0/6.d0*(dy1(i,:)+2.d0*dy2(i,:)+2.d0*dy3(i,:)+dy4(i,:))

	end subroutine RK4
END MODULE RungeKutta


    subroutine newton(x,fx,dfx,ermaxa,temper)
!   ----------------------------------
    implicit none
    integer num
    double precision x,fx,dfx,ermaxa,temper,eror,fx0
    double precision fxfx0,residu,err

!   methode de newton-raphson amelioree

    eror=1.d-10

    call phfunc(x,fx0,dfx,temper)
    fx=fx0

    num=1

!   commencer par des pas doubles jusqu'a ce que fx*fx0<0

 1    continue
    x=x-2.*fx/dfx
    call phfunc(x,fx,dfx,temper)
    num=num+1
    fxfx0=fx*fx0
    if(num.ge.51)then
        write(74,*)'num=',num,' x=',x
        write(74,*)'fx=',fx,' dfx=',dfx
        write(74,*)'program stop'
        stop
    endif
    if(fxfx0.gt.0.)go to 1

!   continuer par newton-raphson classique

 2    continue
    residu=-fx/dfx
    x=x+residu
    call phfunc(x,fx,dfx,temper)
    num=num+1
    err=dabs(residu/x)
    if(num.ge.101)then
        write(74,*)'num=',num,' x=',x
        write(74,*)'fx=',fx,' dfx=',dfx
        write(74,*)'program stop'
        stop
    endif
    if(err.gt.eror)go to 2

    return
    end


C
C       $Id$
C
      SUBROUTINE SHSTORE3 (N,X,Y,Z,NR, LCELL,LNEXT,XYZMIN,
     +                    XYZDEL,IER)
      INTEGER N, NR, LCELL(NR,NR,NR), LNEXT(N), IER
      REAL    X(N), Y(N), Z(N), XYZMIN(3), XYZDEL(3)
C
C***********************************************************
C
C                                               ROBERT RENKA
C                                       UNIV. OF NORTH TEXAS
C                                             (817) 565-2767
C
C  Given a set of N arbitrarily distributed nodes in three-
C  space, this subroutine creates a data structure for a
C  cell-based method of solving closest-point problems.  The
C  smallest box containing the nodes is partitioned into an
C  NR by NR by NR uniform grid of cells, and nodes are as-
C  sociated with cells.  In particular, the data structure
C  stores the indices of the nodes contained in each cell.
C  For a uniform random distribution of nodes, the nearest
C  node to an arbitrary point can be determined in constant
C  expected time.
C
C  ON INPUT --
C
C    N = number of nodes.  N .GE. 2.
C
C    X,Y,Z = arrays of length N containing the Cartesian
C            coordinates of the nodes.
C
C    NR = number of rows, columns, and planes in the
C         grid.  The cell density (average number of
C         nodes per cell) is D = N/(NR**3).  A recommended
C         value, based on empirical evidence, is D = 3
C         -- NR = (N/3)**(1/3).  NR .GE. 1.
C
C  The above parameters are not altered by this routine.
C
C    LCELL = array of length .GE. NR**3.
C
C    LNEXT = array of length .GE. N.
C
C    XYZMIN,XYZDEL = arrays of length .GE. 3.
C
C  ON OUTPUT --
C
C    LCELL = NR by NR by NR cell array such that
C            LCELL(I,J,K) contains the index (for X, Y,
C            and Z) of the first node (node with smallest
C            index) in cell (I,J,K), or LCELL(I,J,K) = 0
C            If no nodes are contained in the cell.  The
C            corner of cell (I,J,K) which is farthest
C            from the box corner defined by XYZMIN has
C            coordinates (XMIN+I*DX,YMIN+J*DY,ZMIN+K*DZ),
C            where (XMIN,YMIN,ZMIN) are the elements of
C            XYZMIN.  LCELL is not defined if IER .NE. 0.
C
C    LNEXT = Array of next-node indices such that
C            LNEXT(L) contains the index of the next node
C            in the cell which contains node L, or
C            LNEXT(L) = L if L is the last node in the
C            cell for L = 1,...,N.  (The nodes contained
C            in a cell are ordered by their indices.)
C            If, for example, cell (I,J,K) contains nodes
C            2, 3, and 5 (and no others), then
C            LCELL(I,J,K) = 2, LNEXT(2) = 3, LNEXT(3) =
C            5, and LNEXT(5) = 5.  LNEXT is not defined
C            if IER .NE. 0.
C
C    XYZMIN = Array of length 3 containing the minimum
C             nodal coordinates XMIN, YMIN, and ZMIN (in
C             that order) unless IER = 1.  The opposite
C             corner of the box defined by the nodes is
C             (XMIN+NR*DX,YMIN+NR*DY,ZMIN+NR*DZ).
C
C    XYZDEL = Array of length 3 containing the dimensions
C             of the cells unless IER = 1.  XYZDEL(1) =
C             (XMAX-XMIN)/NR, XYZDEL(2) = (YMAX-YMIN)/NR,
C             AND XYZDEL(3) = (ZMAX-ZMIN)/NR, where XMIN,
C             XMAX, YMIN, YMAX, ZMIN, and ZMAX are the
C             extrema of X, Y, and Z.
C
C    IER = Error indicator --
C          IER = 0 if no errors were encountered.
C          IER = 1 if N .LT. 2 or NR .LT. 1.
C          IER = 2 if a component of XYZDEL is not positive.
C
C  MODULES REQUIRED BY SHSTORE3 -- NONE
C
C  INTRINSIC FUNCTIONS CALLED BY SHSTORE3 -- FLOAT, IFIX
C
C***********************************************************
C
      NN = N
      NNR = NR
      IF (NN .LT. 2  .OR.  NNR .LT. 1) GO TO 4
C
C  Compute the dimensions of the rectangle containing the nodes.
C
      XMN = X(1)
      XMX = XMN
      YMN = Y(1)
      YMX = YMN
      ZMN = Z(1)
      ZMX = ZMN
      DO 1 L = 2,NN
        IF (X(L) .LT. XMN) XMN = X(L)
        IF (X(L) .GT. XMX) XMX = X(L)
        IF (Y(L) .LT. YMN) YMN = Y(L)
        IF (Y(L) .GT. YMX) YMX = Y(L)
        IF (Z(L) .LT. ZMN) ZMN = Z(L)
        IF (Z(L) .GT. ZMX) ZMX = Z(L)
    1 CONTINUE
      XYZMIN(1) = XMN
      XYZMIN(2) = YMN
      XYZMIN(3) = ZMN
C
C  Compute cell dimensions and test for zero area.
C
      DELX = (XMX-XMN)/FLOAT(NNR)
      DELY = (YMX-YMN)/FLOAT(NNR)
      DELZ = (ZMX-ZMN)/FLOAT(NNR)
      XYZDEL(1) = DELX
      XYZDEL(2) = DELY
      XYZDEL(3) = DELZ
      IF (DELX .EQ. 0.  .OR.  DELY .EQ. 0.  .OR.
     +    DELZ .EQ. 0.) GO TO 5
C
C INITIALIZE LCELL.
C
      DO 7 K = 1,NNR
        DO 6 J = 1,NNR
          DO 2 I = 1,NNR
            LCELL(I,J,K) = 0
    2     CONTINUE
    6   CONTINUE
    7 CONTINUE
C
C  Loop on nodes, storing indices in LCELL and LNEXT.
C
      NP1 = NN + 1
      DO 3 LL = 1,NN
        LB = NP1 - LL
        I = IFIX((X(LB)-XMN)/DELX) + 1
        IF (I .GT. NNR) I = NNR
        J = IFIX((Y(LB)-YMN)/DELY) + 1
        IF (J .GT. NNR) J = NNR
        K = IFIX((Z(LB)-ZMN)/DELZ) + 1
        IF (K .GT. NNR) K = NNR
        L = LCELL(I,J,K)
        LNEXT(LB) = L
        IF (L .EQ. 0) LNEXT(LB) = LB
        LCELL(I,J,K) = LB
    3 CONTINUE
C
C  No errors encountered.
C
      IER = 0
      RETURN
C
C  Invalid input parameter.
C
    4 CONTINUE
      CALL SHERR (1,'SHSTORE3 - number of input data must be > 9',41)
      IER = 1
      RETURN
C
C  Nonpositive XYZDEL component.
C
    5 CONTINUE
      CALL SHERR (7,
     +            'SHSTORE3 - cell grid dimensions must be positive',
     +             48)
      IER = 7
      RETURN
      END


program select_kind
  implicit none
  integer, parameter   :: i4=SELECTED_INT_KIND(4)
  integer, parameter   :: i8=SELECTED_INT_KIND(8)
  integer, parameter   :: i15=SELECTED_INT_KIND(15)
  integer, parameter   :: r4=SELECTED_REAL_KIND(6,37)
  integer, parameter   :: r8=SELECTED_REAL_KIND(15,307)
  integer(KIND=i4) :: ia
  integer(KIND=i8) :: ib
  integer(KIND=i15) :: ic
  real(KIND=r4) :: ra
  real(KIND=r8) :: rb

  print *,' Integer kind=', i4, ' biggest value=', huge(ia)
  print *,' Integer kind=', i8, ' biggest value=', huge(ib)
  print *,' Integer kind=', i15, ' biggest value=', huge(ic)
  print *,' Real kind=', r4, ' smallest value= ', tiny(ra) , &
          ' biggest value=', huge(ra)
  print *,' Real kind=', r8, ' smallest value= ', tiny(rb) , &
          ' biggest value=', huge(rb)

end program select_kind


!   Matrix Module

    module Matrix
        use Util
        implicit none
        integer :: D_MAX_ITER = 1000
        double precision :: D_TOL = 1.0D-5
    contains
        subroutine ill_cond()
!           Prompts the user with an ill-conditioning warning.
            implicit none
            call error('Matriz mal-condicionada: este método não irá convergir.')
        end subroutine

        subroutine show_matrix(var, A, m, n)
            implicit none
            integer :: m, n
            character(len=*) :: var
            double precision, dimension(m, n), intent(in) :: A
            write (*, *) ''//achar(27)//'[36m'//var//' = '
            call print_matrix(A, m, n)
            write (*, *) ''//achar(27)//'[0m'
        end subroutine

        subroutine print_matrix(A, m, n)
            implicit none
            integer :: m, n
            double precision :: A(m, n)
            integer :: i, j
20          format(' |', F32.12, ' ')
21          format(F30.12, '|')
22          format(F30.12, ' ')
            do i = 1, m
                do j = 1, n
                    if (j == 1) then
                        write(*, 20, advance='no') A(i, j)
                    elseif (j == n) then
                        write(*, 21, advance='yes') A(i, j)
                    else
                        write(*, 22, advance='no') A(i, j)
                    end if
                end do
            end do
        end subroutine

        subroutine read_matrix(fname, A, m, n)
            implicit none
            character(len=*) :: fname
            integer :: m, n
            double precision, dimension(:, :), allocatable :: A
            integer :: i
            open(unit=33, file=fname, status='old', action='read')
            read(33, *) m
            read(33, *) n
            allocate(A(m, n))
            do i = 1, m
                read(33,*) A(i,:)
            end do
            close(33)
        end subroutine

        subroutine print_vector(x, n)
            implicit none
            integer :: n
            double precision :: x(n)
            integer :: i
30          format(' |', F30.12, '|')
            do i = 1, n
                write(*, 30) x(i)
            end do
        end subroutine

        subroutine read_vector(fname, b, n)
            implicit none
            character(len=*) :: fname
            integer :: n
            double precision, allocatable :: b(:)

            open(unit=33, file=fname, status='old', action='read')
            read(33, *) n
            allocate(b(n))
            read(33, *) b(:)
            close(33)
        end subroutine

        subroutine show_vector(var, x, n)
            implicit none
            integer :: n
            character(len=*) :: var
            double precision :: x(n)
            write (*, *) ''//achar(27)//'[36m'//var//' = '
            call print_vector(x, n)
            write (*, *) ''//achar(27)//'[0m'
        end subroutine

!       =========== Matrix Methods ============

        function clip(x, n, a, b) result (y)
            integer, intent(in) :: n
            integer :: k
            double precision, intent(in) :: a, b
            double precision, dimension(n), intent(in) :: x
            double precision, dimension(n) :: y

            do k=1, n
                if ((a <= x(k)) .AND. (x(k) <= b)) then
                    y(k) = x(k)
                else
                    y(k) = DNAN
                end if
            end do
            return
        end function

        function rand_vector(n, a, b) result (r)
            implicit none
            integer :: n, i
            double precision, dimension(n) :: r
            double precision, optional :: a, b
            double precision :: t_a, t_b

            if (.NOT. PRESENT(a)) then
                t_a = -1.0D0
            else
                t_a = a
            end if

            if (.NOT. PRESENT(b)) then
                t_b = 1.0D0
            else
                t_b = b
            end if

            do i = 1, n
                r(i) = DRAND(t_a, t_b)
            end do
            return
        end function

        function rand_matrix(m, n, a, b) result (R)
            implicit none
            integer :: m, n, i
            double precision, dimension(m, n) :: R
            double precision, optional :: a, b

            do i = 1, m
                R(i, :) = rand_vector(n, a=a, b=b)
            end do
            return
        end function

        function id_matrix(n) result (A)
            implicit none
            integer :: n
            double precision :: A(n, n)
            integer :: j
            A(:, :) = 0.0D0
            do j = 1, n
                A(j, j) = 1.0D0
            end do
            return
        end function

        function given_matrix(A, n, i, j) result (G)
            implicit none

            integer :: n, i, j
            double precision :: A(n, n), G(n, n)
            double precision :: t, c, s

            G(:, :) = id_matrix(n)

            t = 0.5D0 * DATAN2(2.0D0 * A(i,j), A(i, i) - A(j, j))
            s = DSIN(t)
            c = DCOS(t)

            G(i, i) = c
            G(j, j) = c
            G(i, j) = -s
            G(j, i) = s

            return
        end function

        function vandermond_matrix(x, n) result (V)
            implicit none
            integer :: n, i
            double precision, dimension(n), intent(in) :: x
            double precision, dimension(n, n) :: V
            V(1, :) = 1.0D0
            do i=2, n
                V(i, :) = V(i-1, :) * x(:)
            end do
            return
        end function

        function diagonally_dominant(A, n) result (ok)
            implicit none

            integer :: n
            double precision :: A(n, n)

            logical :: ok
            integer :: i

            do i = 1, n
                if (DABS(A(i, i)) < SUM(DABS(A(i, :i-1))) + SUM(DABS(A(i, i+1:)))) then
                    ok = .FALSE.
                    return
                end if
            end do
            ok = .TRUE.
            return
        end function

        recursive function positive_definite(A, n) result (ok)
!       Checks wether a matrix is positive definite
!       according to Sylvester's criterion.
            implicit none

            integer :: n
            double precision A(n, n)

            logical :: ok

            if (n == 1) then
                ok = (A(1, 1) > 0)
                return
            else
                ok = positive_definite(A(:n-1, :n-1), n-1) .AND. (det(A, n) > 0)
                return
            end if
        end function

        function symmetrical(A, n) result (ok)
!           Check if the Matrix is symmetrical
            integer :: n

            double precision :: A(n, n)

            integer :: i, j
            logical :: ok

            do i = 1, n
                do j = 1, i-1
                    if (A(i, j) /= A(j, i)) then
                        ok = .FALSE.
                        return
                    end if
                end do
            end do
            ok = .TRUE.
            return
        end function

        subroutine swap_rows(A, i, j, n)
            implicit none

            integer :: n
            integer :: i, j
            double precision A(n, n)
            double precision temp(n)

            temp(:) = A(i, :)
            A(i, :) = A(j, :)
            A(j, :) = temp(:)
        end subroutine

        function outer_product(x, y, n) result (A)
            implicit none
            integer :: n
            double precision, dimension(n), intent(in) :: x, y
            double precision, dimension(n, n) :: A
            integer :: i, j
            do i=1,n
                do j=1,n
                    A(i, j) = x(i) * y(j)
                end do
            end do
            return
        end function

!       ================= Matrix Method ====================
        function inv(A, n, ok) result (Ainv)
            integer :: n
            double precision :: A(n, n), Ainv(n, n)
            double precision :: work(n)
            integer :: ipiv(n)   ! pivot indices
            integer :: info

            logical :: ok

            ! External procedures defined in LAPACK
            external DGETRF
            external DGETRI

            ! Store A in Ainv to prevent it from being overwritten by LAPACK
            Ainv(:, :) = A(:, :)

            ! DGETRF computes an LU factorization of a general M-by-N matrix A
            ! using partial pivoting with row interchanges.
            call DGETRF(n, n, Ainv, n, ipiv, info)

            if (info /= 0) then
                ok = .FALSE.
                return
            end if

            ! DGETRI computes the inverse of a matrix using the LU factorization
            ! computed by DGETRF.
            call DGETRI(n, Ainv, n, ipiv, work, n, info)

            if (info /= 0) then
                ok = .FALSE.
                return
            end if

            return
        end function

        function row_max(A, j, n) result(k)
            implicit none

            integer :: n
            double precision A(n, n)

            integer :: i, j, k
            double precision :: s

            s = 0.0D0
            do i = j, n
                if (A(i, j) > s) then
                    s = A(i, j)
                    k = i
                end if
            end do
            return
        end function

        function pivot_matrix(A, n) result (P)
            implicit none

            integer :: n
            double precision :: A(n, n)

            double precision :: P(n, n)

            integer :: j, k

            P = id_matrix(n)

            do j = 1, n
                k = row_max(A, j, n)
                if (j /= k) then
                    call swap_rows(P, j, k, n)
                end if
            end do
            return
        end function

        function vector_norm(x, n) result (s)
            implicit none
            integer :: n
            double precision :: x(n)
            double precision :: s
            s = sqrt(dot_product(x, x))
            return
        end function

        function NORM(x, n) result (s)
            implicit none
            integer :: n
            double precision :: x(n)
            double precision :: s
            s = SQRT(DOT_PRODUCT(x, x))
            return
        end function

        function matrix_norm(A, n) result (s)
!           Frobenius norm
            implicit none
            integer :: n
            double precision :: A(n, n)
            double precision :: s

            s = DSQRT(SUM(A * A))
            return
        end function

        function spectral_radius(A, n) result (r)
            implicit none

            integer :: n
            double precision :: A(n, n), x(n)
            double precision :: r, l
            logical :: ok
            ok = power_method(A, n, x, l)
            r = DABS(l)
            return
        end function

        recursive function det(A, n) result (d)
            implicit none
            integer :: n
            double precision, dimension(n, n) :: A
            double precision, dimension(n-1, n-1) :: X
            integer :: i
            double precision :: d, s

            if (n == 1) then
                d = A(1, 1)
                return
            elseif (n == 2) then
                d = A(1, 1) * A(2, 2) - A(1, 2) * A(2, 1)
                return
            else
                d = 0.0D0
                s = 1.0D0
                do i = 1, n
!                   Compute submatrix X
                    X(:,  :i-1) = A(2:,    :i-1)
                    X(:, i:   ) = A(2:, i+1:   )
                    d = s * det(X, n-1) * A(1, i) + d
                    s = -s
                end do
            end if
            return
        end function

        function LU_det(A, n) result (d)
            implicit none

            integer :: n
            integer :: i
            double precision :: A(n, n), L(n, n), U(n, n)
            double precision :: d

            d = 0.0D0

            if (.NOT. LU_decomp(A, L, U, n)) then
                call ill_cond()
                return
            end if

            do i = 1, n
                d = d * L(i, i) * U(i, i)
            end do

            return
        end function

        subroutine LU_matrix(A, L, U, n)
!           Splits Matrix in Lower and Upper-Triangular
            implicit none

            integer :: n
            double precision :: A(n, n), L(n, n), U(n, n)

            integer :: i

            L(:, :) = 0.0D0
            U(:, :) = 0.0D0

            do i = 1, n
                L(i, i) = 1.0D0
                L(i,  :i-1) = A(i,  :i-1)
                U(i, i:   ) = A(i, i:   )
            end do
        end subroutine

!       === Matrix Factorization Conditions ===
        function Cholesky_cond(A, n) result (ok)
            implicit none
            integer :: n
            double precision :: A(n, n)
            logical :: ok
            ok = symmetrical(A, n) .AND. positive_definite(A, n)
            return
        end function

        function PLU_cond(A, n) result (ok)
            implicit none
            integer :: n
            double precision A(n, n)
            integer :: i, j
            double precision :: s
            logical :: ok
            do j = 1, n
                s = 0.0D0
                do i = 1, j
                    if (A(i, j) > s) then
                        s = A(i, j)
                    end if
                end do
            end do
            ok = (s < 0.01D0)
            return
        end function

        function LU_cond(A, n) result (ok)
            implicit none
            integer :: n
            double precision A(n, n)
            logical :: ok
            ok = positive_definite(A, n)
            return
        end function
!        _      _____  _____ _______         __
!       | |    |_   _|/ ____|__   __|/\     /_ |
!       | |      | | | (___    | |  /  \     | |
!       | |      | |  \___ \   | | / /\ \    | |
!       | |____ _| |_ ____) |  | |/ ____ \   | |
!       |______|_____|_____/   |_/_/    \_\  |_|
!       ========================================

!       ======= Matrix Factorization Methods ========
        function PLU_decomp(A, P, L, U, n) result (ok)
            implicit none
            integer :: n
            double precision :: A(n,n), P(n,n), L(n,n), U(n,n)
            logical :: ok
!           Permutation Matrix
            P = pivot_matrix(A, n)
!           Decomposition over Row-Swapped Matrix
            ok = LU_decomp(matmul(P, A), L, U, n)
            return
        end function

        function LU_decomp(A, L, U, n) result (ok)
            implicit none
            integer :: n
            double precision :: A(n, n), L(n, n), U(n,n), M(n, n)
            logical :: ok
            integer :: i, j, k
!           Results Matrix
            M(:, :) = A(:, :)
            if (.NOT. LU_cond(A, n)) then
                call ill_cond()
                ok = .FALSE.
                return
            end if
            do k = 1, n-1
                do i = k+1, n
                    M(i, k) = M(i, k) / M(k, k)
                end do
                do j = k+1, n
                    do i = k+1, n
                        M(i, j) = M(i, j) - M(i, k) * M(k, j)
                    end do
                end do
            end do

!           Splits M into L & U
            call LU_matrix(M, L, U, n)

            ok = .TRUE.
            return

        end function

        function Cholesky_decomp(A, L, n) result (ok)
            implicit none

            integer :: n
            double precision :: A(n, n), L(n, n)

            logical :: ok

            integer :: i, j

            if (.NOT. Cholesky_cond(A, n)) then
                call ill_cond()
                ok = .FALSE.
                return
            end if

            do i = 1, n
                L(i, i) = sqrt(A(i, i) - sum(L(i, :i-1) * L(i, :i-1)))
                do j = 1 + 1, n
                    L(j, i) = (A(i, j) - sum(L(i, :i-1) * L(j, :i-1))) / L(i, i)
                end do
            end do

            ok = .TRUE.
            return
        end function

        function Jacobi_cond(A, n) result (ok)
            implicit none

            integer :: n

            double precision :: A(n, n)

            logical :: ok

            if (.NOT. spectral_radius(A, n) < 1.0D0) then
                ok = .FALSE.
                call ill_cond()
                return
            else
                ok = .TRUE.
                return
            end if
        end function

        function Jacobi(A, x, b, e, n, tol, max_iter) result (ok)
            implicit none

            logical :: ok

            integer :: n, i, k, t_max_iter
            integer, optional :: max_iter

            double precision :: A(n, n)
            double precision :: b(n), x(n), x0(n)
            double precision :: e, t_tol
            double precision, optional :: tol

            if (.NOT. PRESENT(tol)) then
                t_tol = D_TOL
            else
                t_tol = tol
            end if

            if (.NOT. PRESENT(max_iter)) then
                t_max_iter = D_MAX_ITER
            else
                t_max_iter = max_iter
            end if

            x0 = rand_vector(n)

            ok = Jacobi_cond(A, n)

            if (.NOT. ok) then
                return
            end if

            do k = 1, t_max_iter
                do i = 1, n
                    x(i) = (b(i) - dot_product(A(i, :), x0)) / A(i, i)
                end do
                x0(:) = x(:)
                e = vector_norm(matmul(A, x) - b, n)
                if (e < t_tol) then
                    return
                end if
            end do
            call error('Erro: Esse método não convergiu.')
            ok = .FALSE.
            return
        end function

        function Gauss_Seidel_cond(A, n) result (ok)
            implicit none

            integer :: n

            double precision :: A(n, n)

            logical :: ok

            integer :: i

            do i = 1, n
                if (A(i, i) == 0.0D0) then
                    ok = .FALSE.
                    call ill_cond()
                    return
                end if
            end do

            if (symmetrical(A, n) .AND. positive_definite(A, n)) then
                ok = .TRUE.
                return
            else
                call warn('Aviso: Esse método pode não convergir.')
                return
            end if
        end function

        function Gauss_Seidel(A, x, b, e, n, tol, max_iter) result (ok)
            implicit none
            logical :: ok
            integer :: n, i, j, k, t_max_iter
            integer, optional :: max_iter
            double precision :: A(n, n)
            double precision :: b(n), x(n)
            double precision :: e, s, t_tol
            double precision, optional :: tol

            if (.NOT. PRESENT(tol)) then
                t_tol = D_TOL
            else
                t_tol = tol
            end if

            if (.NOT. PRESENT(max_iter)) then
                t_max_iter = D_MAX_ITER
            else
                t_max_iter = max_iter
            end if

            ok = Gauss_Seidel_cond(A, n)

            if (.NOT. ok) then
                return
            end if

            do k = 1, t_max_iter
                do i = 1, n
                    s = 0.0D0
                    do j = 1, n
                        if (i /= j) then
                            s = s + A(i, j) * x(j)
                        end if
                    end do
                    x(i) = (b(i) - s) / A(i, i)
                end do
                e = vector_norm(matmul(A, x) - b, n)
                if (e < t_tol) then
                    return
                end if
            end do
            call error('Erro: Esse método não convergiu.')
            ok = .FALSE.
            return
        end function

!       Decomposição LU e afins
        subroutine LU_backsub(L, U, x, y, b, n)
            implicit none
            integer :: n
            double precision :: L(n, n), U(n, n)
            double precision :: b(n), x(n), y(n)
            integer :: i
!           Ly = b (Forward Substitution)
            do i = 1, n
                y(i) = (b(i) - SUM(L(i, 1:i-1) * y(1:i-1))) / L(i, i)
            end do
!           Ux = y (Backsubstitution)
            do i = n, 1, -1
                x(i) = (y(i) - SUM(U(i,i+1:n) * x(i+1:n))) / U(i, i)
            end do
        end subroutine

        function LU_solve(A, x, y, b, n) result (ok)
            implicit none

            integer :: n

            double precision :: A(n, n), L(n, n), U(n, n)
            double precision :: b(n), x(n), y(n)

            logical :: ok

            ok = LU_decomp(A, L, U, n)

            if (.NOT. ok) then
                return
            end if

            call LU_backsub(L, U, x, y, b, n)

            return
        end function

        function PLU_solve(A, x, y, b, n) result (ok)
            implicit none

            integer :: n

            double precision :: A(n, n), P(n,n), L(n, n), U(n, n)
            double precision :: b(n), x(n), y(n)

            logical :: ok

            ok = PLU_decomp(A, P, L, U, n)

            if (.NOT. ok) then
                return
            end if

            call LU_backsub(L, U, x, y, matmul(P, b), n)

            x(:) = matmul(P, x)

            return
        end function

        function Cholesky_solve(A, x, y, b, n) result (ok)
            implicit none

            integer :: n

            double precision :: A(n, n), L(n, n), U(n, n)
            double precision :: b(n), x(n), y(n)

            logical :: ok

            ok = Cholesky_decomp(A, L, n)

            if (.NOT. ok) then
                return
            end if

            U = transpose(L)

            call LU_backsub(L, U, x, y, b, n)

            return
        end function

!        _      _____  _____ _______         ___
!       | |    |_   _|/ ____|__   __|/\     |__ \
!       | |      | | | (___    | |  /  \       ) |
!       | |      | |  \___ \   | | / /\ \     / /
!       | |____ _| |_ ____) |  | |/ ____ \   / /_
!       |______|_____|_____/   |_/_/    \_\ |____|
!       ==========================================

!       ============ Power Method ============
        function power_method(A, n, x, l, tol, max_iter) result (ok)
            implicit none
            logical :: ok
            integer :: n, k, t_max_iter
            integer, optional :: max_iter
            double precision :: A(n, n)
            double precision :: x(n)
            double precision :: l, ll, t_tol
            double precision, optional :: tol

            if (.NOT. PRESENT(tol)) then
                t_tol = D_TOL
            else
                t_tol = tol
            end if

            if (.NOT. PRESENT(max_iter)) then
                t_max_iter = D_MAX_ITER
            else
                t_max_iter = max_iter
            end if

!           Begin with random normal vector and set 1st component to zero
            x(:) = rand_vector(n)
            x(1) = 1.0D0

!           Initialize Eigenvalues
            l = 0.0D0

!           Checks if error tolerance was reached
            do k=1, t_max_iter
                ll = l

                x(:) = matmul(A, x)

!               Retrieve Eigenvalue
                l = x(1)

!               Retrieve Eigenvector
                x(:) = x(:) / l

                if (dabs((l - ll) / l) < t_tol) then
                    ok = .TRUE.
                    return
                end if
            end do
            ok = .FALSE.
            return
        end function

        function Jacobi_eigen(A, n, L, X, tol, max_iter) result (ok)
            implicit none
            logical :: ok
            integer :: n, i, j, k, u, v, t_max_iter
            integer, optional :: max_iter
            double precision :: A(n, n), L(n, n), X(n, n), P(n, n)
            double precision :: y, z, t_tol
            double precision, optional :: tol

            if (.NOT. PRESENT(tol)) then
                t_tol = D_TOL
            else
                t_tol = tol
            end if

            if (.NOT. PRESENT(max_iter)) then
                t_max_iter = D_MAX_ITER
            else
                t_max_iter = max_iter
            end if

            X(:, :) = id_matrix(n)
            L(:, :) = A(:, :)

            do k=1, t_max_iter
                z = 0.0D0
                do i = 1, n
                    do j = 1, i - 1
                        y = DABS(L(i, j))

!                       Found new maximum absolute value
                        if (y > z) then
                            u = i
                            v = j
                            z = y
                        end if
                    end do
                end do

                if (z >= t_tol) then
                    P(:, :) = given_matrix(L, n, u, v)
                    L(:, :) = matmul(matmul(transpose(P), L), P)
                    X(:, :) = matmul(X, P)
                else
                    ok = .TRUE.
                    return
                end if
            end do
            ok = .FALSE.
            return
        end function

!        _      _____  _____ _______         _____
!       | |    |_   _|/ ____|__   __|/\     |__   |
!       | |      | | | (___    | |  /  \       )  /
!       | |      | |  \___ \   | | / /\ \     |_  \
!       | |____ _| |_ ____) |  | |/ ____ \   ___)  |
!       |______|_____|_____/   |_/_/    \_\ |_____/
!       ==========================================

        function least_squares(x, y, s, n) result (ok)
            implicit none
            integer :: n

            logical :: ok

            double precision :: A(2,2), b(2), s(2), r(2), x(n), y(n)

            A(1, 1) = n
            A(1, 2) = SUM(x)
            A(2, 1) = SUM(x)
            A(2, 2) = dot_product(x, x)

            b(1) = SUM(y)
            b(2) = dot_product(x, y)

            ok = Cholesky_solve(A, s, r, b, n)
            return
        end function

!       ========== Extra Stuff ========

        function Gauss_solve(A0, x, b0, n) result (ok)
            implicit none
            integer n
            double precision, dimension(n, n), intent(in) :: A0
            double precision, dimension(n, n) :: A
            double precision, dimension(n), intent(in) :: b0
            double precision, dimension(n) :: b, x, s
            double precision :: c, pivot, store
            integer i, j, k, l

            logical :: ok

            ok = .TRUE.

            A(:, :) = A0(:, :)
            b(:) = b0(:)

            do k=1, n-1
                do i=k,n
                    s(i) = 0.0
                    do j=k,n
                        s(i) = MAX(s(i), DABS(A(i,j)))
                    end do
                end do

                pivot = DABS(A(k,k) / s(k))
                l = k
                do j=k+1,n
                    if(DABS(A(j,k) / s(j)) > pivot) then
                        pivot = DABS(A(j,k) / s(j))
                        l = j
                    end if
                end do

                if(pivot == 0.0) then
                    ok = .FALSE.
                    return
                end if

                if (l /= k) then
                    do j=k,n
                        store = A(k,j)
                        A(k,j) = A(l,j)
                        A(l,j) = store
                    end do
                    store = b(k)
                    b(k) = b(l)
                    b(l) = store
                end if

                do i=k+1,n
                    c = A(i,k) / A(k,k)
                    A(i,k) = 0.0D0
                    b(i) = b(i)- c*b(k)
                    do j=k+1,n
                        A(i,j) = A(i,j) - c * A(k,j)
                    end do
                end do
            end do

            x(n) = b(n) / A(n,n)
            do i=n-1,1,-1
                c = 0.0D0
                do j=i+1,n
                    c = c + A(i,j) * x(j)
                end do
                x(i) = (b(i)- c) / A(i,i)
            end do

            return
        end function

        function solve(A, b, n, kind) result (x)
            implicit none
            integer :: n
            double precision, dimension(n), intent(in) :: b
            double precision, dimension(n) :: x, y
            double precision, dimension(n, n), intent(in) :: A
            character(len=*), optional :: kind
            character(len=:), allocatable :: t_kind

            logical :: ok = .TRUE.

            if (.NOT. PRESENT(kind)) then
                call debug("Indeed, not present.")
                t_kind = "gauss"
            else
                t_kind = kind
            end if

            call debug("Now it is: "//t_kind)
            if (t_kind == "LU") then
                ok = LU_solve(A, x, y, b, n)
            else if (t_kind == "PLU") then
                ok = PLU_solve(A, x, y, b, n)
            else if (t_kind =="cholesky") then
                ok = Cholesky_solve(A, x, y, b, n)
            else if (t_kind =="gauss") then
                ok = Gauss_solve(A, x, b, n)
            else
                ok = .FALSE.
            end if

            call debug(":: Solved via `"//t_kind//"` ::")

            if (.NOT. ok) then
                call error("Failed to solve system Ax = b.")
            end if

            return
        end function

    end module Matrix