*> \brief \b ZLA_GERFSX_EXTENDED
*
*  =========== DOCUMENTATION ===========
*
* Online html documentation available at
*            http://www.netlib.org/lapack/explore-html/
*
*> \htmlonly
*> Download ZLA_GERFSX_EXTENDED + dependencies
*>
*> [TGZ]
*>
*> [ZIP]
*>
*> [TXT]
*> \endhtmlonly
*
*  Definition:
*  ===========
*
*       SUBROUTINE ZLA_GERFSX_EXTENDED( PREC_TYPE, TRANS_TYPE, N, NRHS, A,
*                                       LDA, AF, LDAF, IPIV, COLEQU, C, B,
*                                       LDB, Y, LDY, BERR_OUT, N_NORMS,
*                                       ERRS_N, ERRS_C, RES, AYB, DY,
*                                       Y_TAIL, RCOND, ITHRESH, RTHRESH,
*                                       DZ_UB, IGNORE_CWISE, INFO )
*
*       .. Scalar Arguments ..
*       INTEGER            INFO, LDA, LDAF, LDB, LDY, N, NRHS, PREC_TYPE,
*      $                   TRANS_TYPE, N_NORMS
*       LOGICAL            COLEQU, IGNORE_CWISE
*       INTEGER            ITHRESH
*       DOUBLE PRECISION   RTHRESH, DZ_UB
*       ..
*       .. Array Arguments
*       INTEGER            IPIV( * )
*       COMPLEX*16         A( LDA, * ), AF( LDAF, * ), B( LDB, * ),
*      $                   Y( LDY, * ), RES( * ), DY( * ), Y_TAIL( * )
*       DOUBLE PRECISION   C( * ), AYB( * ), RCOND, BERR_OUT( * ),
*      $                   ERRS_N( NRHS, * ), ERRS_C( NRHS, * )
*       ..
*
*
*> \par Purpose:
*  =============
*>
*> \verbatim
*>
*> ZLA_GERFSX_EXTENDED improves the computed solution to a system of
*> linear equations by performing extra-precise iterative refinement
*> and provides error bounds and backward error estimates for the solution.
*> This subroutine is called by ZGERFSX to perform iterative refinement.
*> In addition to normwise error bound, the code provides maximum
*> componentwise error bound if possible. See comments for ERRS_N
*> and ERRS_C for details of the error bounds. Note that this
*> subroutine is only resonsible for setting the second fields of
*> ERRS_N and ERRS_C.
*> \endverbatim
*
*  Arguments:
*  ==========
*
*> \param[in] PREC_TYPE
*> \verbatim
*>          PREC_TYPE is INTEGER
*>     Specifies the intermediate precision to be used in refinement.
*>     The value is defined by ILAPREC(P) where P is a CHARACTER and
*>     P    = 'S':  Single
*>          = 'D':  Double
*>          = 'I':  Indigenous
*>          = 'X', 'E':  Extra
*> \endverbatim
*>
*> \param[in] TRANS_TYPE
*> \verbatim
*>          TRANS_TYPE is INTEGER
*>     Specifies the transposition operation on A.
*>     The value is defined by ILATRANS(T) where T is a CHARACTER and
*>     T    = 'N':  No transpose
*>          = 'T':  Transpose
*>          = 'C':  Conjugate transpose
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*>          N is INTEGER
*>     The number of linear equations, i.e., the order of the
*>     matrix A.  N >= 0.
*> \endverbatim
*>
*> \param[in] NRHS
*> \verbatim
*>          NRHS is INTEGER
*>     The number of right-hand-sides, i.e., the number of columns of the
*>     matrix B.
*> \endverbatim
*>
*> \param[in] A
*> \verbatim
*>          A is COMPLEX*16 array, dimension (LDA,N)
*>     On entry, the N-by-N matrix A.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*>          LDA is INTEGER
*>     The leading dimension of the array A.  LDA >= max(1,N).
*> \endverbatim
*>
*> \param[in] AF
*> \verbatim
*>          AF is COMPLEX*16 array, dimension (LDAF,N)
*>     The factors L and U from the factorization
*>     A = P*L*U as computed by ZGETRF.
*> \endverbatim
*>
*> \param[in] LDAF
*> \verbatim
*>          LDAF is INTEGER
*>     The leading dimension of the array AF.  LDAF >= max(1,N).
*> \endverbatim
*>
*> \param[in] IPIV
*> \verbatim
*>          IPIV is INTEGER array, dimension (N)
*>     The pivot indices from the factorization A = P*L*U
*>     as computed by ZGETRF; row i of the matrix was interchanged
*>     with row IPIV(i).
*> \endverbatim
*>
*> \param[in] COLEQU
*> \verbatim
*>          COLEQU is LOGICAL
*>     If .TRUE. then column equilibration was done to A before calling
*>     this routine. This is needed to compute the solution and error
*>     bounds correctly.
*> \endverbatim
*>
*> \param[in] C
*> \verbatim
*>          C is DOUBLE PRECISION array, dimension (N)
*>     The column scale factors for A. If COLEQU = .FALSE., C
*>     is not accessed. If C is input, each element of C should be a power
*>     of the radix to ensure a reliable solution and error estimates.
*>     Scaling by powers of the radix does not cause rounding errors unless
*>     the result underflows or overflows. Rounding errors during scaling
*>     lead to refining with a matrix that is not equivalent to the
*>     input matrix, producing error estimates that may not be
*>     reliable.
*> \endverbatim
*>
*> \param[in] B
*> \verbatim
*>          B is COMPLEX*16 array, dimension (LDB,NRHS)
*>     The right-hand-side matrix B.
*> \endverbatim
*>
*> \param[in] LDB
*> \verbatim
*>          LDB is INTEGER
*>     The leading dimension of the array B.  LDB >= max(1,N).
*> \endverbatim
*>
*> \param[in,out] Y
*> \verbatim
*>          Y is COMPLEX*16 array, dimension (LDY,NRHS)
*>     On entry, the solution matrix X, as computed by ZGETRS.
*>     On exit, the improved solution matrix Y.
*> \endverbatim
*>
*> \param[in] LDY
*> \verbatim
*>          LDY is INTEGER
*>     The leading dimension of the array Y.  LDY >= max(1,N).
*> \endverbatim
*>
*> \param[out] BERR_OUT
*> \verbatim
*>          BERR_OUT is DOUBLE PRECISION array, dimension (NRHS)
*>     On exit, BERR_OUT(j) contains the componentwise relative backward
*>     error for right-hand-side j from the formula
*>         max(i) ( abs(RES(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) )
*>     where abs(Z) is the componentwise absolute value of the matrix
*>     or vector Z. This is computed by ZLA_LIN_BERR.
*> \endverbatim
*>
*> \param[in] N_NORMS
*> \verbatim
*>          N_NORMS is INTEGER
*>     Determines which error bounds to return (see ERRS_N
*>     and ERRS_C).
*>     If N_NORMS >= 1 return normwise error bounds.
*>     If N_NORMS >= 2 return componentwise error bounds.
*> \endverbatim
*>
*> \param[in,out] ERRS_N
*> \verbatim
*>          ERRS_N is DOUBLE PRECISION array, dimension
*>                    (NRHS, N_ERR_BNDS)
*>     For each right-hand side, this array contains information about
*>     various error bounds and condition numbers corresponding to the
*>     normwise relative error, which is defined as follows:
*>
*>     Normwise relative error in the ith solution vector:
*>             max_j (abs(XTRUE(j,i) - X(j,i)))
*>            ------------------------------
*>                  max_j abs(X(j,i))
*>
*>     The array is indexed by the type of error information as described
*>     below. There currently are up to three pieces of information
*>     returned.
*>
*>     The first index in ERRS_N(i,:) corresponds to the ith
*>     right-hand side.
*>
*>     The second index in ERRS_N(:,err) contains the following
*>     three fields:
*>     err = 1 "Trust/don't trust" boolean. Trust the answer if the
*>              reciprocal condition number is less than the threshold
*>              sqrt(n) * slamch('Epsilon').
*>
*>     err = 2 "Guaranteed" error bound: The estimated forward error,
*>              almost certainly within a factor of 10 of the true error
*>              so long as the next entry is greater than the threshold
*>              sqrt(n) * slamch('Epsilon'). This error bound should only
*>              be trusted if the previous boolean is true.
*>
*>     err = 3  Reciprocal condition number: Estimated normwise
*>              reciprocal condition number.  Compared with the threshold
*>              sqrt(n) * slamch('Epsilon') to determine if the error
*>              estimate is "guaranteed". These reciprocal condition
*>              numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some
*>              appropriately scaled matrix Z.
*>              Let Z = S*A, where S scales each row by a power of the
*>              radix so all absolute row sums of Z are approximately 1.
*>
*>     This subroutine is only responsible for setting the second field
*>     above.
*>     See Lapack Working Note 165 for further details and extra
*>     cautions.
*> \endverbatim
*>
*> \param[in,out] ERRS_C
*> \verbatim
*>          ERRS_C is DOUBLE PRECISION array, dimension
*>                    (NRHS, N_ERR_BNDS)
*>     For each right-hand side, this array contains information about
*>     various error bounds and condition numbers corresponding to the
*>     componentwise relative error, which is defined as follows:
*>
*>     Componentwise relative error in the ith solution vector:
*>                    abs(XTRUE(j,i) - X(j,i))
*>             max_j ----------------------
*>                         abs(X(j,i))
*>
*>     The array is indexed by the right-hand side i (on which the
*>     componentwise relative error depends), and the type of error
*>     information as described below. There currently are up to three
*>     pieces of information returned for each right-hand side. If
*>     componentwise accuracy is not requested (PARAMS(3) = 0.0), then
*>     ERRS_C is not accessed.  If N_ERR_BNDS .LT. 3, then at most
*>     the first (:,N_ERR_BNDS) entries are returned.
*>
*>     The first index in ERRS_C(i,:) corresponds to the ith
*>     right-hand side.
*>
*>     The second index in ERRS_C(:,err) contains the following
*>     three fields:
*>     err = 1 "Trust/don't trust" boolean. Trust the answer if the
*>              reciprocal condition number is less than the threshold
*>              sqrt(n) * slamch('Epsilon').
*>
*>     err = 2 "Guaranteed" error bound: The estimated forward error,
*>              almost certainly within a factor of 10 of the true error
*>              so long as the next entry is greater than the threshold
*>              sqrt(n) * slamch('Epsilon'). This error bound should only
*>              be trusted if the previous boolean is true.
*>
*>     err = 3  Reciprocal condition number: Estimated componentwise
*>              reciprocal condition number.  Compared with the threshold
*>              sqrt(n) * slamch('Epsilon') to determine if the error
*>              estimate is "guaranteed". These reciprocal condition
*>              numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some
*>              appropriately scaled matrix Z.
*>              Let Z = S*(A*diag(x)), where x is the solution for the
*>              current right-hand side and S scales each row of
*>              A*diag(x) by a power of the radix so all absolute row
*>              sums of Z are approximately 1.
*>
*>     This subroutine is only responsible for setting the second field
*>     above.
*>     See Lapack Working Note 165 for further details and extra
*>     cautions.
*> \endverbatim
*>
*> \param[in] RES
*> \verbatim
*>          RES is COMPLEX*16 array, dimension (N)
*>     Workspace to hold the intermediate residual.
*> \endverbatim
*>
*> \param[in] AYB
*> \verbatim
*>          AYB is DOUBLE PRECISION array, dimension (N)
*>     Workspace.
*> \endverbatim
*>
*> \param[in] DY
*> \verbatim
*>          DY is COMPLEX*16 array, dimension (N)
*>     Workspace to hold the intermediate solution.
*> \endverbatim
*>
*> \param[in] Y_TAIL
*> \verbatim
*>          Y_TAIL is COMPLEX*16 array, dimension (N)
*>     Workspace to hold the trailing bits of the intermediate solution.
*> \endverbatim
*>
*> \param[in] RCOND
*> \verbatim
*>          RCOND is DOUBLE PRECISION
*>     Reciprocal scaled condition number.  This is an estimate of the
*>     reciprocal Skeel condition number of the matrix A after
*>     equilibration (if done).  If this is less than the machine
*>     precision (in particular, if it is zero), the matrix is singular
*>     to working precision.  Note that the error may still be small even
*>     if this number is very small and the matrix appears ill-
*>     conditioned.
*> \endverbatim
*>
*> \param[in] ITHRESH
*> \verbatim
*>          ITHRESH is INTEGER
*>     The maximum number of residual computations allowed for
*>     refinement. The default is 10. For 'aggressive' set to 100 to
*>     permit convergence using approximate factorizations or
*>     factorizations other than LU. If the factorization uses a
*>     technique other than Gaussian elimination, the guarantees in
*>     ERRS_N and ERRS_C may no longer be trustworthy.
*> \endverbatim
*>
*> \param[in] RTHRESH
*> \verbatim
*>          RTHRESH is DOUBLE PRECISION
*>     Determines when to stop refinement if the error estimate stops
*>     decreasing. Refinement will stop when the next solution no longer
*>     satisfies norm(dx_{i+1}) < RTHRESH * norm(dx_i) where norm(Z) is
*>     the infinity norm of Z. RTHRESH satisfies 0 < RTHRESH <= 1. The
*>     default value is 0.5. For 'aggressive' set to 0.9 to permit
*>     convergence on extremely ill-conditioned matrices. See LAWN 165
*>     for more details.
*> \endverbatim
*>
*> \param[in] DZ_UB
*> \verbatim
*>          DZ_UB is DOUBLE PRECISION
*>     Determines when to start considering componentwise convergence.
*>     Componentwise convergence is only considered after each component
*>     of the solution Y is stable, which we definte as the relative
*>     change in each component being less than DZ_UB. The default value
*>     is 0.25, requiring the first bit to be stable. See LAWN 165 for
*>     more details.
*> \endverbatim
*>
*> \param[in] IGNORE_CWISE
*> \verbatim
*>          IGNORE_CWISE is LOGICAL
*>     If .TRUE. then ignore componentwise convergence. Default value
*>     is .FALSE..
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*>          INFO is INTEGER
*>       = 0:  Successful exit.
*>       < 0:  if INFO = -i, the ith argument to ZGETRS had an illegal
*>             value
*> \endverbatim
*
*  Authors:
*  ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date December 2016
*
*> \ingroup complex16GEcomputational
*
*  =====================================================================
      SUBROUTINE ZLA_GERFSX_EXTENDED( PREC_TYPE, TRANS_TYPE, N, NRHS, A,
     $                                LDA, AF, LDAF, IPIV, COLEQU, C, B,
     $                                LDB, Y, LDY, BERR_OUT, N_NORMS,
     $                                ERRS_N, ERRS_C, RES, AYB, DY,
     $                                Y_TAIL, RCOND, ITHRESH, RTHRESH,
     $                                DZ_UB, IGNORE_CWISE, INFO )
*
*  -- LAPACK computational routine (version 3.7.0) --
*  -- LAPACK is a software package provided by Univ. of Tennessee,    --
*  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*     December 2016
*
*     .. Scalar Arguments ..
      INTEGER            INFO, LDA, LDAF, LDB, LDY, N, NRHS, PREC_TYPE,
     $                   TRANS_TYPE, N_NORMS
      LOGICAL            COLEQU, IGNORE_CWISE
      INTEGER            ITHRESH
      DOUBLE PRECISION   RTHRESH, DZ_UB
*     ..
*     .. Array Arguments
      INTEGER            IPIV( * )
      COMPLEX*16         A( LDA, * ), AF( LDAF, * ), B( LDB, * ),
     $                   Y( LDY, * ), RES( * ), DY( * ), Y_TAIL( * )
      DOUBLE PRECISION   C( * ), AYB( * ), RCOND, BERR_OUT( * ),
     $                   ERRS_N( NRHS, * ), ERRS_C( NRHS, * )
*     ..
*
*  =====================================================================
*
*     .. Local Scalars ..
      CHARACTER          TRANS
      INTEGER            CNT, I, J,  X_STATE, Z_STATE, Y_PREC_STATE
      DOUBLE PRECISION   YK, DYK, YMIN, NORMY, NORMX, NORMDX, DXRAT,
     $                   DZRAT, PREVNORMDX, PREV_DZ_Z, DXRATMAX,
     $                   DZRATMAX, DX_X, DZ_Z, FINAL_DX_X, FINAL_DZ_Z,
     $                   EPS, HUGEVAL, INCR_THRESH
      LOGICAL            INCR_PREC
      COMPLEX*16         ZDUM
*     ..
*     .. Parameters ..
      INTEGER            UNSTABLE_STATE, WORKING_STATE, CONV_STATE,
     $                   NOPROG_STATE, BASE_RESIDUAL, EXTRA_RESIDUAL,
     $                   EXTRA_Y
      PARAMETER          ( UNSTABLE_STATE = 0, WORKING_STATE = 1,
     $                   CONV_STATE = 2,
     $                   NOPROG_STATE = 3 )
      PARAMETER          ( BASE_RESIDUAL = 0, EXTRA_RESIDUAL = 1,
     $                   EXTRA_Y = 2 )
      INTEGER            FINAL_NRM_ERR_I, FINAL_CMP_ERR_I, BERR_I
      INTEGER            RCOND_I, NRM_RCOND_I, NRM_ERR_I, CMP_RCOND_I
      INTEGER            CMP_ERR_I, PIV_GROWTH_I
      PARAMETER          ( FINAL_NRM_ERR_I = 1, FINAL_CMP_ERR_I = 2,
     $                   BERR_I = 3 )
      PARAMETER          ( RCOND_I = 4, NRM_RCOND_I = 5, NRM_ERR_I = 6 )
      PARAMETER          ( CMP_RCOND_I = 7, CMP_ERR_I = 8,
     $                   PIV_GROWTH_I = 9 )
      INTEGER            LA_LINRX_ITREF_I, LA_LINRX_ITHRESH_I,
     $                   LA_LINRX_CWISE_I
      PARAMETER          ( LA_LINRX_ITREF_I = 1,
     $                   LA_LINRX_ITHRESH_I = 2 )
      PARAMETER          ( LA_LINRX_CWISE_I = 3 )
      INTEGER            LA_LINRX_TRUST_I, LA_LINRX_ERR_I,
     $                   LA_LINRX_RCOND_I
      PARAMETER          ( LA_LINRX_TRUST_I = 1, LA_LINRX_ERR_I = 2 )
      PARAMETER          ( LA_LINRX_RCOND_I = 3 )
*     ..
*     .. External Subroutines ..
      EXTERNAL           ZAXPY, ZCOPY, ZGETRS, ZGEMV, BLAS_ZGEMV_X,
     $                   BLAS_ZGEMV2_X, ZLA_GEAMV, ZLA_WWADDW, DLAMCH,
     $                   CHLA_TRANSTYPE, ZLA_LIN_BERR
      DOUBLE PRECISION   DLAMCH
      CHARACTER          CHLA_TRANSTYPE
*     ..
*     .. Intrinsic Functions ..
      INTRINSIC          ABS, MAX, MIN
*     ..
*     .. Statement Functions ..
      DOUBLE PRECISION   CABS1
*     ..
*     .. Statement Function Definitions ..
      CABS1( ZDUM ) = ABS( DBLE( ZDUM ) ) + ABS( DIMAG( ZDUM ) )
*     ..
*     .. Executable Statements ..
*
      IF ( INFO.NE.0 ) RETURN
      TRANS = CHLA_TRANSTYPE(TRANS_TYPE)
      EPS = DLAMCH( 'Epsilon' )
      HUGEVAL = DLAMCH( 'Overflow' )
*     Force HUGEVAL to Inf
      HUGEVAL = HUGEVAL * HUGEVAL
*     Using HUGEVAL may lead to spurious underflows.
      INCR_THRESH = DBLE( N ) * EPS
*
      DO J = 1, NRHS
         Y_PREC_STATE = EXTRA_RESIDUAL
         IF ( Y_PREC_STATE .EQ. EXTRA_Y ) THEN
            DO I = 1, N
               Y_TAIL( I ) = 0.0D+0
            END DO
         END IF

         DXRAT = 0.0D+0
         DXRATMAX = 0.0D+0
         DZRAT = 0.0D+0
         DZRATMAX = 0.0D+0
         FINAL_DX_X = HUGEVAL
         FINAL_DZ_Z = HUGEVAL
         PREVNORMDX = HUGEVAL
         PREV_DZ_Z = HUGEVAL
         DZ_Z = HUGEVAL
         DX_X = HUGEVAL

         X_STATE = WORKING_STATE
         Z_STATE = UNSTABLE_STATE
         INCR_PREC = .FALSE.

         DO CNT = 1, ITHRESH
*
*         Compute residual RES = B_s - op(A_s) * Y,
*             op(A) = A, A**T, or A**H depending on TRANS (and type).
*
            CALL ZCOPY( N, B( 1, J ), 1, RES, 1 )
            IF ( Y_PREC_STATE .EQ. BASE_RESIDUAL ) THEN
               CALL ZGEMV( TRANS, N, N, (-1.0D+0,0.0D+0), A, LDA,
     $              Y( 1, J ), 1, (1.0D+0,0.0D+0), RES, 1)
            ELSE IF (Y_PREC_STATE .EQ. EXTRA_RESIDUAL) THEN
               CALL BLAS_ZGEMV_X( TRANS_TYPE, N, N, (-1.0D+0,0.0D+0), A,
     $              LDA, Y( 1, J ), 1, (1.0D+0,0.0D+0),
     $              RES, 1, PREC_TYPE )
            ELSE
               CALL BLAS_ZGEMV2_X( TRANS_TYPE, N, N, (-1.0D+0,0.0D+0),
     $              A, LDA, Y(1, J), Y_TAIL, 1, (1.0D+0,0.0D+0), RES, 1,
     $              PREC_TYPE)
            END IF

!         XXX: RES is no longer needed.
            CALL ZCOPY( N, RES, 1, DY, 1 )
            CALL ZGETRS( TRANS, N, 1, AF, LDAF, IPIV, DY, N, INFO )
*
*         Calculate relative changes DX_X, DZ_Z and ratios DXRAT, DZRAT.
*
            NORMX = 0.0D+0
            NORMY = 0.0D+0
            NORMDX = 0.0D+0
            DZ_Z = 0.0D+0
            YMIN = HUGEVAL
*
            DO I = 1, N
               YK = CABS1( Y( I, J ) )
               DYK = CABS1( DY( I ) )

               IF ( YK .NE. 0.0D+0 ) THEN
                  DZ_Z = MAX( DZ_Z, DYK / YK )
               ELSE IF ( DYK .NE. 0.0D+0 ) THEN
                  DZ_Z = HUGEVAL
               END IF

               YMIN = MIN( YMIN, YK )

               NORMY = MAX( NORMY, YK )

               IF ( COLEQU ) THEN
                  NORMX = MAX( NORMX, YK * C( I ) )
                  NORMDX = MAX( NORMDX, DYK * C( I ) )
               ELSE
                  NORMX = NORMY
                  NORMDX = MAX(NORMDX, DYK)
               END IF
            END DO

            IF ( NORMX .NE. 0.0D+0 ) THEN
               DX_X = NORMDX / NORMX
            ELSE IF ( NORMDX .EQ. 0.0D+0 ) THEN
               DX_X = 0.0D+0
            ELSE
               DX_X = HUGEVAL
            END IF

            DXRAT = NORMDX / PREVNORMDX
            DZRAT = DZ_Z / PREV_DZ_Z
*
*         Check termination criteria
*
            IF (.NOT.IGNORE_CWISE
     $           .AND. YMIN*RCOND .LT. INCR_THRESH*NORMY
     $           .AND. Y_PREC_STATE .LT. EXTRA_Y )
     $           INCR_PREC = .TRUE.

            IF ( X_STATE .EQ. NOPROG_STATE .AND. DXRAT .LE. RTHRESH )
     $           X_STATE = WORKING_STATE
            IF ( X_STATE .EQ. WORKING_STATE ) THEN
               IF (DX_X .LE. EPS) THEN
                  X_STATE = CONV_STATE
               ELSE IF ( DXRAT .GT. RTHRESH ) THEN
                  IF ( Y_PREC_STATE .NE. EXTRA_Y ) THEN
                     INCR_PREC = .TRUE.
                  ELSE
                     X_STATE = NOPROG_STATE
                  END IF
               ELSE
                  IF ( DXRAT .GT. DXRATMAX ) DXRATMAX = DXRAT
               END IF
               IF ( X_STATE .GT. WORKING_STATE ) FINAL_DX_X = DX_X
            END IF

            IF ( Z_STATE .EQ. UNSTABLE_STATE .AND. DZ_Z .LE. DZ_UB )
     $           Z_STATE = WORKING_STATE
            IF ( Z_STATE .EQ. NOPROG_STATE .AND. DZRAT .LE. RTHRESH )
     $           Z_STATE = WORKING_STATE
            IF ( Z_STATE .EQ. WORKING_STATE ) THEN
               IF ( DZ_Z .LE. EPS ) THEN
                  Z_STATE = CONV_STATE
               ELSE IF ( DZ_Z .GT. DZ_UB ) THEN
                  Z_STATE = UNSTABLE_STATE
                  DZRATMAX = 0.0D+0
                  FINAL_DZ_Z = HUGEVAL
               ELSE IF ( DZRAT .GT. RTHRESH ) THEN
                  IF ( Y_PREC_STATE .NE. EXTRA_Y ) THEN
                     INCR_PREC = .TRUE.
                  ELSE
                     Z_STATE = NOPROG_STATE
                  END IF
               ELSE
                  IF ( DZRAT .GT. DZRATMAX ) DZRATMAX = DZRAT
               END IF
               IF ( Z_STATE .GT. WORKING_STATE ) FINAL_DZ_Z = DZ_Z
            END IF
*
*           Exit if both normwise and componentwise stopped working,
*           but if componentwise is unstable, let it go at least two
*           iterations.
*
            IF ( X_STATE.NE.WORKING_STATE ) THEN
               IF ( IGNORE_CWISE ) GOTO 666
               IF ( Z_STATE.EQ.NOPROG_STATE .OR. Z_STATE.EQ.CONV_STATE )
     $              GOTO 666
               IF ( Z_STATE.EQ.UNSTABLE_STATE .AND. CNT.GT.1 ) GOTO 666
            END IF

            IF ( INCR_PREC ) THEN
               INCR_PREC = .FALSE.
               Y_PREC_STATE = Y_PREC_STATE + 1
               DO I = 1, N
                  Y_TAIL( I ) = 0.0D+0
               END DO
            END IF

            PREVNORMDX = NORMDX
            PREV_DZ_Z = DZ_Z
*
*           Update soluton.
*
            IF ( Y_PREC_STATE .LT. EXTRA_Y ) THEN
               CALL ZAXPY( N, (1.0D+0,0.0D+0), DY, 1, Y(1,J), 1 )
            ELSE
               CALL ZLA_WWADDW( N, Y( 1, J ), Y_TAIL, DY )
            END IF

         END DO
*        Target of "IF (Z_STOP .AND. X_STOP)".  Sun's f77 won't EXIT.
 666     CONTINUE
*
*     Set final_* when cnt hits ithresh
*
         IF ( X_STATE .EQ. WORKING_STATE ) FINAL_DX_X = DX_X
         IF ( Z_STATE .EQ. WORKING_STATE ) FINAL_DZ_Z = DZ_Z
*
*     Compute error bounds
*
         IF (N_NORMS .GE. 1) THEN
            ERRS_N( J, LA_LINRX_ERR_I ) = FINAL_DX_X / (1 - DXRATMAX)

         END IF
         IF ( N_NORMS .GE. 2 ) THEN
            ERRS_C( J, LA_LINRX_ERR_I ) = FINAL_DZ_Z / (1 - DZRATMAX)
         END IF
*
*     Compute componentwise relative backward error from formula
*         max(i) ( abs(R(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) )
*     where abs(Z) is the componentwise absolute value of the matrix
*     or vector Z.
*
*        Compute residual RES = B_s - op(A_s) * Y,
*            op(A) = A, A**T, or A**H depending on TRANS (and type).
*
         CALL ZCOPY( N, B( 1, J ), 1, RES, 1 )
         CALL ZGEMV( TRANS, N, N, (-1.0D+0,0.0D+0), A, LDA, Y(1,J), 1,
     $        (1.0D+0,0.0D+0), RES, 1 )

         DO I = 1, N
            AYB( I ) = CABS1( B( I, J ) )
         END DO
*
*     Compute abs(op(A_s))*abs(Y) + abs(B_s).
*
         CALL ZLA_GEAMV ( TRANS_TYPE, N, N, 1.0D+0,
     $        A, LDA, Y(1, J), 1, 1.0D+0, AYB, 1 )

         CALL ZLA_LIN_BERR ( N, N, 1, RES, AYB, BERR_OUT( J ) )
*
*     End of loop for each RHS.
*
      END DO
*
      RETURN
      END


  function qintxs (photonEG, x, sig, l, m, n)

! ======================================================================
!
!    Interpolation of gamma+N differential cross sections.
!
!    Written by K. K. Gudima, Fall 2003?
!    Modified by AJS, May, 2004.
!    Edited by AJS, LANL T-2, December, 2011.
!
! ======================================================================

    use, intrinsic:: iso_fortran_env, only: int32, real64

    implicit none
    class(PhotonEventGenerator), intent(inout) :: photonEG
    integer(int32),              intent(in   ) :: m
    integer(int32),              intent(in   ) :: n
    real(real64),                intent(in   ) :: x
    real(real64),                intent(in   ) :: sig(m, n)
    integer(int32),              intent(in   ) :: l
    real(real64)                               :: qintxs

    integer(int32) :: k, k1, k2, k3, numElements
    real(real64)   :: a, b, c, d1, da, db, dc, y1, y2, y3

! ======================================================================

    ! Provide default value
    qintxs = 0

    ! Ensure course angle mesh data was created:
    if ( photonEG%data%numElements <= 0 ) then
       ! Wasn't constructed OR no course angle mesh exists
       ! Warn and return to client
       write(photonEG%io%message, 2000)
       call photonEG%io%print(2, 2, photonEG%io%message)
       write(photonEG%io%message, 2010)
       call photonEG%io%print(2, 2, photonEG%io%message)
       return
    end if

    ! Look for points very close to the desired value
    numElements = min(n, photonEG%data%numElements)
    do k = 1, numElements
       if (abs(x - photonEG%data%theta(k)) <= 1.0d-3) then
          qintxs = sig(l,k)
          qintxs = max(qintxs, zro)
          return
       endif
    enddo

    ! Perform interpolation
    do k = 2, (numElements-1)
       ! Look for a point nearby
       if (x < photonEG%data%theta(k)) then
          k1 = k - 1
          k2 = k
          k3 = k + 1
          go to 10
       endif
    enddo
    ! No points found - use maximum
    k1 = numElements - 2
    k2 = numElements - 1
    k3 = numElements

10  continue
    y1 = sig(l,k1)
    y2 = sig(l,k2)
    y3 = sig(l,k3)
    da = photonEG%data%x23(k2)*y1 + photonEG%data%x31(k2)*y2 + &
         & photonEG%data%x12(k2)*y3
    db =   (y2 - y3)*photonEG%data%x11(k2) + &
         & (y3 - y1)*photonEG%data%x22(k2) + &
         & (y1 - y2)*photonEG%data%x33(k2)
    dc =   (photonEG%data%theta(k2)*y3 - photonEG%data%theta(k3)*y2)*photonEG%data%x11(k2) + &
         & (photonEG%data%theta(k3)*y1 - photonEG%data%theta(k1)*y3)*photonEG%data%x22(k2) + &
         & (photonEG%data%theta(k1)*y2 - photonEG%data%theta(k2)*y1)*photonEG%data%x33(k2)
    d1 = zro
    if ( abs(photonEG%data%d(k2)-zro)>=divZerLim ) d1 = one/photonEG%data%d(k2)
    a = da*d1
    b = db*d1
    c = dc*d1

    qintxs = a*x*x + b*x + c
    qintxs = max(qintxs,zro)

    return

! ======================================================================
2000 format("No photon cross section interpolation data was created.")
2010 format("   Cannot interpolate cross section values in 'qintxs.f90'.")
! ======================================================================
  end function qintxs


CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      PROGRAM EXMPL5
C     Example 5: Determining Nuclear Charge Density
C  COMPUTATIONAL PHYSICS (FORTRAN VERSION)
C  by Steven E. Koonin and Dawn C. Meredith
C  Copyright 1989, Addison-Wesley Publishing Company, Inc.
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      CALL INIT           !display header screen, setup parameters
5     CONTINUE            !main loop/ execute once for each set of param
        CALL PARAM        !get input from screen
        CALL ARCHON       !calculate nuclear charge density
      GOTO 5
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE ARCHON
C calculates nuclear charge density from best fit to electron scattering
C data; the density is expanded in a finite Fourier series
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E5'
      INCLUDE 'IO.ALL'
C Local variables:
      INTEGER ITER                      !number of iterations
      INTEGER INCRS,CONT                !increase nsine? continue iter?
      INTEGER NSINE                     !number of coefficients
      REAL CZERO(CMAX)                  !Fourier coefficients
      REAL SIGT(DATMAX)                 !total cross section
      COMPLEX FTOTAL(DATMAX)            !total scattering amplitude
      REAL QBASIS                       !max num momentum transfer
      DOUBLE PRECISION A(CMAX+1,CMAX+1) !matrix for inverting
      REAL CHI(NLEG)                    !profile functions
      REAL RHO(NGRF)                    !density for graphing
      REAL DRHO(NGRF)                   !error in density
      INTEGER SCREEN                    !send to terminal
      INTEGER PAPER                     !make a hardcopy
      INTEGER FILE                      !send to a file
C Function:
      INTEGER GETINT,YESNO              !get input from screen
      DATA SCREEN,PAPER,FILE/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     read in nuclear data and calculate derivative parameters
      CALL NDATA
C     set up arrays that do not depend on Cn's
      CALL TABLES(A)
C     prompt for value of N to begin with
      NSINE=GETINT(NBASIS,1,NBASIS,
     +         'Enter number of sine functions to begin with')
      CALL CLEAR
C
C     output summary of parameters
      IF (TTERM) CALL PRMOUT(OUNIT)
      IF (TFILE) CALL PRMOUT(TUNIT)
      IF (GFILE) CALL PRMOUT(GUNIT)
C
C     obtain initial Cn's from Fermi distribution
      ITER=0
      QBASIS=NSINE*PI/RMAX                 !largest Q described by basis
      CALL FERMI(NSINE,CZERO)
C     calculate initial fit and display
      CALL FIT(NSINE,CZERO,ITER,SIGT,FTOTAL,QBASIS,CHI,A,RHO,DRHO)
C
100   CONTINUE                             !loop over iterations
          ITER=ITER+1
C         find changes in CZERO's to minimize the error
          CALL MINIMZ(CZERO,NSINE,SIGT,FTOTAL,QBASIS,CHI,A)
C         calculate quality of fit, errors; display results
          CALL FIT(NSINE,CZERO,ITER,SIGT,FTOTAL,QBASIS,CHI,A,RHO,DRHO)
C
C         various options for continuing
          IF (NSINE .LT. NBASIS) THEN
            INCRS=
     +      YESNO(0,'Do you want to increment number of sines by one?')
            IF (INCRS .EQ. 1) THEN
               NSINE=NSINE+1
               CZERO(NSINE)=0.
               CONT=1
               QBASIS=NSINE*PI/RMAX       !largest Q described by basis
            ELSE
               CONT=YESNO(1,'Do you want to continue iterating?')
            END IF
          ELSE
            CONT=YESNO(1,'Do you want to continue iterating?')
          END IF
C
       IF (CONT .EQ. 1) GOTO 100
C
C      write out only the final version to a file
       IF (GHRDCP) CALL GRFOUT(PAPER,RHO,SIGT,NSINE,DRHO)
       IF (GFILE) CALL GRFOUT(FILE,RHO,SIGT,NSINE,DRHO)
C
       RETURN
       END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE NDATA
C read in nuclear data
C define variables that are nucleus-dependent
C take recoil out of data; calculate effective momentum transfer
C prompt for NBASIS and RMAX
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E5'
      INCLUDE 'IO.ALL'
C Local variables:
      INTEGER I,IR                      !index of input data, radius
      REAL QLAB,RECOIL                  !variables to adjust input data
      REAL MTARGT                       !mass of the target in MeV
      INTEGER NZERO                     !suggestion for NBASIS
C Function:
      INTEGER GETINT                    !get integer input from terminal
      REAL GETFLT                       !get real input from terminal
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     open data files
      IF (NUCL .EQ. CA) THEN
          OPEN(UNIT=DUNIT,FILE='CA.DAT',STATUS='OLD')
      ELSE IF (NUCL .EQ. NI) THEN
          OPEN(UNIT=DUNIT,FILE='NI.DAT',STATUS='OLD')
      ELSE IF (NUCL .EQ. PB) THEN
          OPEN(UNIT=DUNIT,FILE='PB.DAT',STATUS='OLD')
      END IF
C
C     read in data description
      READ (DUNIT,5) TARGET
      READ (DUNIT,*) ZTARGT,ATARGT,EBEAM,NPTS
5     FORMAT (2X,A10)
C
C     calculate target parameters
      RZERO=1.07*ATARGT**(1./3.)
      MTARGT=940*ATARGT
      ZA=ZTARGT*ALPHA
      KBEAM=EBEAM/HBARC
      VC1=1.+4./3.*ZA*HBARC/(EBEAM*RZERO)
C
C     read in cross sections; close file
      READ (DUNIT,20) (THETA(I),SIGE(I),DSIGE(I),
     +              THETA(I+1),SIGE(I+1),DSIGE(I+1),I=1,NPTS,2)
20    FORMAT (2(1X,F7.3,1X,E10.3,1X,E10.3))
      CLOSE (UNIT=DUNIT)
C
C     do some preliminary adjustments to the data
      QMAX=0.
      DO 30 I=1,NPTS
C        keep the error small
         IF (DSIGE(I) .GT. SIGE(I)) DSIGE(I)=.8*SIGE(I)
C        angle in radians
         THETA(I)=THETA(I)*PI/180.
C        correction to momentum transfer
         QLAB=2*KBEAM*SIN(THETA(I)/2.)
         QEFF(I)=QLAB*VC1
         IF (QEFF(I) .GT. QMAX) QMAX=QEFF(I)
C        take out recoil
         RECOIL=1.+2.*EBEAM*SIN(THETA(I)/2)**2/MTARGT
         SIGE(I)=SIGE(I)*RECOIL
         DSIGE(I)=DSIGE(I)*RECOIL
30    CONTINUE
C
C     prompt for input of RMAX and NBASIS
      WRITE (OUNIT,40) TARGET
      WRITE (OUNIT,50) EBEAM
      WRITE (OUNIT,60) QMAX
      WRITE (OUNIT,70) RZERO
      WRITE (OUNIT,*) '  '
C
      RMAX=GETFLT(RZERO+4.,1.,25.,
     +       ' Enter the boundary radius to use (in fermis)')
      NZERO=INT(QMAX*RMAX/PI)
      WRITE (OUNIT,80) NZERO
      NBASIS=GETINT(NZERO,1,15,' Enter NBASIS')
C
C     fill array RGRF that is used for charge density with radial values
      DRGRF=RMAX/NGRF
      DO 90 IR=1,NGRF
         RGRF(IR)=IR*DRGRF
90    CONTINUE
C
40    FORMAT (' For the target ',A10)
50    FORMAT (' the data are at a beam energy of ',F7.3,' MeV')
60    FORMAT (' the maximum momentum transfer covered is ',
     +        F7.3,' fm**-1')
70    FORMAT (' the nuclear radius is about',F7.3,' fm')
80    FORMAT (' to keep QMAX less than Qexperimental, NBASIS'
     +  ' must be less than ',I2)
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE TABLES(A)
C calculates CHI(N), sets up table of B*J_0(QR), calculates FOUTER
C and zeroes the matrix A
C (none of these variables depend on Cn's, and therefore need
C to be done only once per calculation)
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E5'
      INCLUDE 'IO.ALL'
C Output variables:
      DOUBLE PRECISION A(CMAX+1,CMAX+1)!matrix for inverting
C Local variables:
      REAL B                           !impact parameter/RMAX
      INTEGER N,ILEG,JLEG,I,J          !indices
      REAL Z,X,Y                       !integration variables
      REAL SUM                         !sum for integration
      REAL PHI,BESSJ0,BESSJ1           !real functions
      REAL J0,J1                       !temp values for Fouter
      COMPLEX MU                       !arguments of the Lommel function
      REAL NU
      COMPLEX FACTOR                   !common factor in FOUTER
      COMPLEX LOMMEL                   !Lommel function * X**(1-MU)
      COMPLEX TEMP1,TEMP2              !temp storage for Lommel function
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     function for CHIN
      PHI(Y)=ALOG((1.+SQRT(1.-Y**2))/Y)-SQRT(1.-Y**2)
C     Lommel function * X**(1-MU)
      LOMMEL(X,MU,NU)=1.- ((MU-1.)**2-NU**2)/X**2 +
     +                ((MU-1)**2-NU**2)*((MU-3.)**2-NU**2)/X**4
C
C     zero the matrix A
      DO 2 I=1,CMAX+1
         DO 1 J=1,CMAX+1
            A(I,J)=0.
1        CONTINUE
2     CONTINUE
C
C     CHIN = part of profile function independent of Cn's
      WRITE (OUNIT,*) ' Calculating chi(n)...'
      DO 20 N=1,NBASIS
         DO 10 ILEG=1,NLEG
            B=(1+XLEG(ILEG))/2.           !all B's are scaled by RMAX
            SUM=0.
            DO 5 JLEG=1,NLEG
               Z=B+(1.-B)/2.*(1.+XLEG(JLEG))              !Eq. 5.66b
               SUM=SUM+WLEG(JLEG)*Z*SIN(N*PI*Z)*PHI(B/Z)  !Gaussian quad
5           CONTINUE
            CHIN(ILEG,N)=-4*PI*ALPHA*RMAX**2*SUM*(1.-B)/2.
10       CONTINUE
20    CONTINUE
C
C     part of F_inner integrand independent of Cn's
      WRITE (OUNIT,*) ' Calculating Bessel functions * b ...'
      DO 60 ILEG=1,NLEG
         B=(1+XLEG(ILEG))/2.               !all B's are scaled by RMAX
         DO 50 I=1,NPTS                    !Eq. 5.62
            X=QEFF(I)*RMAX*B
            JTABLE(ILEG,I)=BESSJ0(X)*B*WLEG(ILEG)
50       CONTINUE
60    CONTINUE
C
C     calculate F_outer (which only sees a point charge)
      WRITE (OUNIT,*) ' Calculating outer scattering amplitude...'
      WRITE (OUNIT,*) '  '
      FACTOR=-2*SQRTM1*ZA
      DO 80 I=1,NPTS
         X=QEFF(I)*RMAX
         J0=BESSJ0(X)
         J1=BESSJ1(X)                      !Eq. 5.63
         TEMP1=LOMMEL(X,FACTOR,-1.)
         TEMP2=LOMMEL(X,1.+FACTOR,0.)
         FOUTER(I)=FACTOR*J0*TEMP1+X*J1*TEMP2-X*J1
         FOUTER(I)=SQRTM1*KBEAM*FOUTER(I)/(QEFF(I)**2)
80    CONTINUE
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
       SUBROUTINE FERMI(NSINE,CZERO)
C calculate initial CZERO by finding Fourier coefficients
C for the Fermi Function
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
       INCLUDE 'PARAM.E5'
C Input variables:
       INTEGER NSINE                     !number of coefficients
C Output variables
       REAL CZERO(CMAX)                  !Fourier coefficients
C Local variables:
       INTEGER ILEG,N                    !indices
       REAL RADIUS,R                     !radial step,radius
       REAL FERMIF,RRHO                  !Fermi Function
       REAL SUM                          !sum for normalization
       REAL THICK                        !thickness of Fermi function
       DATA THICK / 2.4 /
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
       FERMIF(R)=1./(1.+EXP(4.4*(R-RZERO)/THICK))
C
       DO 30 N=1,NSINE                   !zero sums
          CZERO(N)=0.
30     CONTINUE
C      radial integrals to find C's
       DO 50 ILEG=1,NLEG
          RADIUS=RMAX*(1+XLEG(ILEG))/2
          RRHO=RADIUS*FERMIF(RADIUS)     !Fourier transform of Eq. 5.57
          DO 40 N=1,NSINE                !Gaussian quad
             CZERO(N)=CZERO(N)+RRHO*SIN(N*PI*RADIUS/RMAX)*WLEG(ILEG)
40        CONTINUE
50     CONTINUE
C
C      normalize the C's to charge ZTARGT (Eq. 5.58)
       SUM=0.
       DO 70 N=1,NSINE
            IF (MOD(N,2) .EQ. 1) SUM=SUM+CZERO(N)/N
            IF (MOD(N,2) .EQ. 0) SUM=SUM-CZERO(N)/N
70     CONTINUE
       SUM=ZTARGT/(4*RMAX**2*SUM)
       DO 80 N=1,NBASIS
          CZERO(N)=CZERO(N)*SUM
80     CONTINUE
C
       RETURN
       END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE FIT(NSINE,CZERO,ITER,SIGT,FTOTAL,QBASIS,CHI,A,RHO,DRHO)
C calculates sigma (given CZERO), chi squared, the charge density,
C and error in charge density; displays the results
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E5'
      INCLUDE 'IO.ALL'
C Input variables:
      REAL CZERO(CMAX)                     !Fourier coefficients
      INTEGER NSINE                        !number of coefficients
      INTEGER ITER                         !number of iterations
C Output variables:
      REAL SIGT(DATMAX)                    !total cross section
      COMPLEX FTOTAL(DATMAX)               !total scattering amplitude
      REAL QBASIS                          !max num momentum transfer
      REAL RHO(NGRF)                       !charge density
      REAL DRHO(NGRF)                      !error in density
      DOUBLE PRECISION A(CMAX+1,CMAX+1)    !matrix for inverting
C Local variables:
      REAL CHI(NLEG)                       !profile functions
      COMPLEX FINNER                       !inner scattering amplitude
      INTEGER ILEG,IQ,N,IR,M               !indices
      REAL CHISQ                           !goodness of fit
      INTEGER NDOF                         !degrees of freedom in fit
      REAL SINES(CMAX)                     !table of sines
      REAL SUM,FAC                         !temp variable for DRHO
      REAL Z                               !total nuclear charge
      INTEGER SCREEN                       !send to terminal
      INTEGER PAPER                        !make a hardcopy
      INTEGER FILE                         !send to a file
      DATA SCREEN,PAPER,FILE/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     calculate total profile function at each b (Eq. 5.66a)
      DO 20 ILEG=1,NLEG
         CHI(ILEG)=-ZA*LOG((1+XLEG(ILEG))/2)
         DO 10 N=1,NSINE
            CHI(ILEG)=CHI(ILEG)+CZERO(N)*CHIN(ILEG,N)
10       CONTINUE
20    CONTINUE
C
C     calculate fit sigma, chisquare
      CHISQ=0
      NDOF=0
      DO 50 IQ=1,NPTS                          !loop over data points
C        calculate the inner and total scattering amplitude
         FINNER=0.
         DO 40 ILEG=1,NLEG                     !Eq. 5.62
           FINNER=FINNER+JTABLE(ILEG,IQ)*(EXP(2*SQRTM1*CHI(ILEG))-1.)
40       CONTINUE
         FINNER=-SQRTM1*KBEAM*RMAX**2*FINNER/2.
C        scattering amplitude
         FTOTAL(IQ)=(FINNER+FOUTER(IQ))
C
C        sigma in mbarnes/sr, with momentum transfer corr  (Eq. 5.60)
         SIGT(IQ)=10*COS(THETA(IQ)/2)**2*VC1**2*ABS(FTOTAL(IQ))**2
         IF (QEFF(IQ) .LE. QBASIS) THEN
           CHISQ=CHISQ+((SIGE(IQ)-SIGT(IQ))/DSIGE(IQ))**2  !Eq. 5.42
           NDOF=NDOF+1
         END IF
50    CONTINUE
      NDOF=NDOF-NSINE                        !degrees of freedom
C
C     calculate the density and its error
      Z=0.
      DO 70 IR=1,NGRF
         RHO(IR)=0.                            !zero sums
         DRHO(IR)=0.
         DO 60 N=1,NSINE
            SINES(N)=SIN(N*PI*RGRF(IR)/RMAX)   !common term
            RHO(IR)=RHO(IR)+CZERO(N)*SINES(N)  !Eq. 5.57; density*radius
            SUM=0.
            DO 80 M=1,N                        !sums to find err in dens
               FAC=2.
               IF (M .EQ. N) FAC=1.
               SUM=SUM+FAC*A(N,M)*SINES(M)     !Eq. 5.55, sum over M
80          CONTINUE
            DRHO(IR)=DRHO(IR)+SUM*SINES(N)     !Eq. 5.55, sum over N
60       CONTINUE
         DRHO(IR)=SQRT(ABS(DRHO(IR)))/RGRF(IR) !take out radius from RHO
         Z=Z+RHO(IR)*RGRF(IR)                  !integ dens for tot charge
         RHO(IR)=RHO(IR)/RGRF(IR)              !now RHO is just density
70    CONTINUE
      Z=Z*4*PI*RMAX/NGRF
C
      IF (TTERM)
     +  CALL TXTOUT(OUNIT,ITER,CHISQ,NDOF,NSINE,QBASIS,CZERO,A,Z)
      IF (TFILE)
     +  CALL TXTOUT(TUNIT,ITER,CHISQ,NDOF,NSINE,QBASIS,CZERO,A,Z)
      IF (GTERM) THEN
         CALL GRFOUT(SCREEN,RHO,SIGT,NSINE,DRHO)
         CALL CLEAR
      END IF
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE MINIMZ(CZERO,NSINE,SIGT,FTOTAL,QBASIS,CHI,A)
C finds the corrections to CZERO to minimize the fit
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E5'
C Input variables:
      REAL CZERO(CMAX)                    !Fourier coefficients (I/O)
      INTEGER NSINE                       !number of coefficients
      REAL SIGT(DATMAX)                   !total cross section
      REAL CHI(NLEG)                      !profile functions
      COMPLEX FTOTAL(DATMAX)              !total scattering amplitude
      REAL QBASIS                         !max num momentum transfer
      DOUBLE PRECISION A(CMAX+1,CMAX+1)   !matrix for inverting (I/O)
C Local variables:
      REAL BVEC(CMAX+1)                   !lhs of linear equation
      INTEGER NDIM                        !dimension of matrix
      COMPLEX DFDC                        !diff of F w.r.t. CZERO
      REAL W(CMAX)                        !diff of SIGT w.r.t. CZERO
      INTEGER IQ,N,ILEG,M                 !indices
      REAL SUM                            !temp value for matrix mulplct
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      WRITE (OUNIT,*) ' Calculating and inverting A...'
      NDIM=NSINE+1
C
C     zero the vector B and matrix A
      DO 10 N=1,NSINE
         BVEC(N)=0
         DO 20 M=1,N
            A(N,M)=0.
20       CONTINUE
10    CONTINUE
C
C     calculate the matrix A and vector B
      DO 70 IQ=1,NPTS
        IF (QEFF(IQ) .LT. QBASIS) THEN  !leave off Q's not desc by basis
          DO 40 N=1,NSINE               !first find W terms
            DFDC=0
            DO 30 ILEG=1,NLEG
               DFDC=DFDC+               !terms in W (Eq. 5.67b)
     +          JTABLE(ILEG,IQ)*EXP(2*SQRTM1*CHI(ILEG))*CHIN(ILEG,N)
30          CONTINUE
            DFDC=DFDC*KBEAM*RMAX**2
            W(N)=20.*VC1**4*COS(THETA(IQ)/2)**2   !Eq. 5.67a
     +           *REAL(CONJG(FTOTAL(IQ))*DFDC)    !W in mbarnes/sr
40        CONTINUE
C
          DO 60 N=1,NSINE                         !calculate matrix A
             DO 50 M=1,N                          !Eq. 5.48
                A(N,M)=A(N,M)+DBLE(W(N)*W(M)/DSIGE(IQ)**2)
50           CONTINUE                             !and vector B(Eq 5.48)
             BVEC(N)=BVEC(N)+(SIGE(IQ)-SIGT(IQ))*W(N)/DSIGE(IQ)**2
60        CONTINUE
         END IF
70     CONTINUE
C
C      include dZ/dCn terms, and fill out A using symmetry
       DO 100 N=1,NSINE                             !Eq 5.49a, 5.58
          IF (MOD(N,2) .EQ. 1) A(N,NDIM)=-A(1,1)/N  !scale by A(1,1)
          IF (MOD(N,2) .EQ. 0) A(N,NDIM)=A(1,1)/N
          A(NDIM,N)=A(N,NDIM)
          DO 90 M=1,N          !fill out A matrix using symmetry
             A(M,N)=A(N,M)
90        CONTINUE
100    CONTINUE
       A(NSINE+1,NSINE+1)=0.
C
       CALL MATINV(A,NDIM)     !invert the matrix
C
       DO 120 N=1,NSINE        !multiply A**-1 * B to solve for
          SUM=0.               !corrections to Czero
          DO 110 M=1,NSINE
             SUM=SUM+A(N,M)*BVEC(M)
110       CONTINUE
          CZERO(N)=CZERO(N)+SUM
120    CONTINUE
C
       RETURN
       END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
       SUBROUTINE MATINV(A,NDIM)
C inverts the matrix A of dimension NDIM using Gauss-Jordan elimination;
C A is replaced by its inverse
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E5'
C Input/output variables:
      DOUBLE PRECISION A(CMAX+1,CMAX+1) !matrix for inverting
      INTEGER NDIM                 !dimension of matrix
C Local variables:
      DOUBLE PRECISION P(CMAX+1),Q(CMAX+1) !temporary storage
      LOGICAL ZEROED(CMAX+1)       !keeps track of who's zeroed
      INTEGER I,J,K                !indices
      INTEGER KBIG                 !index of row being zeroed
      DOUBLE PRECISION PIVOT       !largest diag element in A
      REAL BIG                     !largest diag elem of non zeroed rows
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     which rows are zeroed? none so far
      DO 10 I=1,NDIM
         ZEROED(I)=.FALSE.
10    CONTINUE
C
C     loop over all rows
      DO 100 I=1,NDIM
         KBIG=0                    !search for largest diag element
         BIG=0                     !in rows not yet zeroed
         DO 20 J=1,NDIM
           IF (.NOT. ZEROED(J)) THEN
               IF (ABS(A(J,J)) .GT. BIG) THEN
                  BIG=ABS(A(J,J))
                  KBIG=J
               END IF
           END IF
20       CONTINUE
C
C        store the largest diagonal element
         IF (I .EQ. 1) PIVOT=A(KBIG,KBIG)
C
C        if all diagonals are zero, then the matrix is singular
         IF (KBIG .EQ. 0) THEN
            WRITE (OUNIT,*) ' Matrix is singular'
            RETURN
         END IF
C        matrix is ill conditioned if size of elements varies greatly
         IF (ABS(A(KBIG,KBIG)/PIVOT) .LT. 1.E-14) THEN
            WRITE (OUNIT,*) ' Matrix is ill conditioned'
            RETURN
         END IF
C
C        begin zeroing row KBIG
         ZEROED(KBIG)=.TRUE.
         Q(KBIG)=1/A(KBIG,KBIG)
         P(KBIG)=1.
         A(KBIG,KBIG)=0.
C
C        elements above the diagonal
         IF (KBIG .GT. 1) THEN
            DO 30 J=1,KBIG-1
               P(J)=A(J,KBIG)
               Q(J)=A(J,KBIG)*Q(KBIG)
               IF (.NOT. ZEROED(J)) Q(J)=-Q(J)
               A(J,KBIG)=0.
30          CONTINUE
        END IF
C
C       elements to the right of the diagonal
        IF (KBIG .LT. NDIM) THEN
            DO 40 J=KBIG+1,NDIM
               P(J)=A(KBIG,J)
               Q(J)=-A(KBIG,J)*Q(KBIG)
               IF (ZEROED(J)) P(J)=-P(J)
               A(KBIG,J)=0.
40          CONTINUE
        END IF
C
C      transform all of A
       DO 60 J=1,NDIM
          DO 50 K=J,NDIM
             A(J,K)=A(J,K)+P(J)*Q(K)
50        CONTINUE
60     CONTINUE
100   CONTINUE
C
C     symmetrize A**-1
      DO 110 J=2,NDIM
         DO 120 K=1,J-1
            A(J,K)=A(K,J)
120      CONTINUE
110   CONTINUE
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE INIT
C initializes constants, displays header screen,
C initializes arrays for input parameters
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
      INCLUDE 'MENU.ALL'
      INCLUDE 'PARAM.E5'
C Local parameters:
      CHARACTER*80 DESCRP          !program description
      DIMENSION DESCRP(20)
      INTEGER NHEAD,NTEXT,NGRAPH   !number of lines for each description
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     get environment parameters
      CALL SETUP
C
C     display header screen
      DESCRP(1)= 'EXAMPLE 5'
      DESCRP(2)= 'Determining Nuclear Charge Densities'
      NHEAD=2
C
C     text output description
      DESCRP(3)= 'Density parameters and quality of fit'
      NTEXT=1
C
C     graphics output description
      DESCRP(4)= 'Charge density and scattering cross section'
      NGRAPH=1
C
      CALL HEADER(DESCRP,NHEAD,NTEXT,NGRAPH)
C
C     calculate constants
      PI=4*ATAN(1.0)
      ALPHA=1./137.036
      HBARC=197.329
      SQRTM1=(0.,1.)
C     get data for Gauss-Legendre integration
      CALL GAUSS
C
C     setup menu arrays, beginning with constant part
      CALL MENU
C
      MPRMPT(4)='2) (not used)'
C
      MTYPE(13)=MTITLE
      MPRMPT(13)='Choice of nuclei:'
      MLOLIM(13)=2
      MHILIM(13)=1
C
      MTYPE(14)=MTITLE
      MPRMPT(14)='1) Calcium 40 '
      MLOLIM(14)=0
      MHILIM(14)=0
C
      MTYPE(15)=MTITLE
      MPRMPT(15)='2) Nickel 58 '
      MLOLIM(15)=0
      MHILIM(15)=0
C
      MTYPE(16)=MTITLE
      MPRMPT(16)='3) Lead 208 '
      MLOLIM(16)=0
      MHILIM(16)=1
C
      MTYPE(17)=MCHOIC
      MPRMPT(17)='Enter your choice'
      MTAG(17)='18 18 18'
      MLOLIM(17)=1
      MHILIM(17)=3
      MINTS(17)=1
      MREALS(17)=1.
C
      MTYPE(18)=SKIP
      MREALS(18)=35
C
      MTYPE(36)=SKIP
      MREALS(36)=60.
C
      MSTRNG(MINTS(75))= 'exmpl5.txt'
C
      MTYPE(76)=SKIP
      MREALS(76)=80.
C
      MSTRNG(MINTS(86))= 'exmpl5.grf'
C
      MTYPE(87)=SKIP
      MREALS(87)=90.
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE PARAM
C gets parameters from screen
C ends program on request
C closes old files
C maps menu variables to program variables
C opens new files
C calculates all derivative parameters
C performs checks on parameters
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'MENU.ALL'
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E5'
C Local variables:
      INTEGER INUCL                !map menu arrays to parameters
      PARAMETER (INUCL  = 17 )
C Function:
      LOGICAL LOGCVT               !converts 1 to true, others to false
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     get input from terminal
      CALL CLEAR
      CALL ASK(1,ISTOP)
C
C     stop program if requested
      IF (MREALS(IMAIN) .EQ. STOP) CALL FINISH
C
C     close files if necessary
      IF (TNAME .NE. MSTRNG(MINTS(ITNAME)))
     +     CALL FLCLOS(TNAME,TUNIT)
      IF (GNAME .NE. MSTRNG(MINTS(IGNAME)))
     +     CALL FLCLOS(GNAME,GUNIT)
C
C     set new parameter values
C     physical and numerical
      NUCL=MINTS(INUCL)
C
C     text output
      TTERM=LOGCVT(MINTS(ITTERM))
      TFILE=LOGCVT(MINTS(ITFILE))
      TNAME=MSTRNG(MINTS(ITNAME))
C
C     graphics output
      GTERM=LOGCVT(MINTS(IGTERM))
      GHRDCP=LOGCVT(MINTS(IGHRD))
      GFILE=LOGCVT(MINTS(IGFILE))
      GNAME=MSTRNG(MINTS(IGNAME))
C
C     open files
      IF (TFILE) CALL FLOPEN(TNAME,TUNIT)
      IF (GFILE) CALL FLOPEN(GNAME,GUNIT)
      !files may have been renamed
      MSTRNG(MINTS(ITNAME))=TNAME
      MSTRNG(MINTS(IGNAME))=GNAME
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE GAUSS
C establish Gauss-Legendre weights and abscissae for 20 points
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'PARAM.E5'
C Local variables:
      INTEGER ILEG                   !index for weights and abscissae
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      XLEG(1)=.993128599185094
      WLEG(1)=.017614007139152
      XLEG(2)=.963971927277913
      WLEG(2)=.040601429800386
      XLEG(3)=.912234428251325
      WLEG(3)=.062672048334109
      XLEG(4)=.839116971822218
      WLEG(4)=.083276741576704
      XLEG(5)=.74633190646015
      WLEG(5)=.10193011981724
      XLEG(6)=.636053680726515
      WLEG(6)=.118194531961518
      XLEG(7)=.510867001950827
      WLEG(7)=.131688638449176
      XLEG(8)=.373706088715419
      WLEG(8)=.142096109318382
      XLEG(9)=.227785851141645
      WLEG(9)=.149172986472603
      XLEG(10)=.076526521133497
      WLEG(10)=.152753387130725
C
      DO 10 ILEG=1,NLEG/2        !weights and abscissae are even and odd
         XLEG(21-ILEG)=-XLEG(ILEG)
         WLEG(21-ILEG)=WLEG(ILEG)
10    CONTINUE
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
       REAL FUNCTION BESSJ0(X)
C calculates zeroth order Bessel function at X
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Passed variables:
       REAL X
C Local variables:
	REAL TEMP,TEMP2,Y2,Y
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
        Y=X/3.
        IF(ABS(X) .LT. 3.0) THEN
             Y2=Y*Y
             TEMP=-.0039444+.00021*Y2
             TEMP=.0444479+Y2*TEMP
             TEMP=-.3163866+Y2*TEMP
             TEMP=1.2656208+Y2*TEMP
             TEMP=-2.2499997+Y2*TEMP
             BESSJ0=1+Y2*TEMP
        ELSE
             Y=1/Y
             TEMP=-7.2805E-04+1.4476E-04*Y
             TEMP=1.37237E-03+TEMP*Y
             TEMP=-9.512E-05+TEMP*Y
             TEMP=-.0055274+TEMP*Y
             TEMP=-7.7E-07+TEMP*Y
             TEMP=.79788456+TEMP*Y
             TEMP2=-2.9333E-04+1.3558E-04*Y
             TEMP2=-5.4125E-04+TEMP2*Y
             TEMP2=2.62573E-03+TEMP2*Y
             TEMP2=-3.954E-05+TEMP2*Y
             TEMP2=-4.166397E-02+TEMP2*Y
             TEMP2=X-.78539816+TEMP2*Y
             BESSJ0=TEMP*COS(TEMP2)/SQRT(X)
        END IF
        RETURN
        END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
       REAL FUNCTION BESSJ1(X)
C calculates first order Bessel function at X
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Passed variables:
       REAL X
C Local variables:
	REAL TEMP,TEMP2,Y2,Y
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
        Y=X/3.
        IF(ABS(X) .LT. 3.0) THEN
             Y2=Y*Y
             TEMP=-3.1761E-04+1.109E-05*Y2
             TEMP=4.43319E-03+Y2*TEMP
             TEMP=-3.954289E-02+Y2*TEMP
             TEMP=.21093573+Y2*TEMP
             TEMP=-.56249985+Y2*TEMP
             BESSJ1=X*(.5+Y2*TEMP)
        ELSE
           Y=1/Y
             TEMP=1.13653E-03-2.0033E-04*Y
             TEMP=-2.49511E-03+TEMP*Y
             TEMP=1.7105E-04+TEMP*Y
             TEMP=1.659667E-02+TEMP*Y
             TEMP=1.56E-06+TEMP*Y
             TEMP=.79788456+TEMP*Y
             TEMP2=7.9824E-04-2.9166E-04*Y
             TEMP2=7.4348E-04+TEMP2*Y
             TEMP2=-6.37879E-03+TEMP2*Y
             TEMP2=.0000565+TEMP2*Y
             TEMP2=.12499612+TEMP2*Y
             TEMP2=X-2.35619449+TEMP2*Y
             BESSJ1=TEMP*COS(TEMP2)/SQRT(X)
         END IF
         RETURN
         END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE PRMOUT(MUNIT)
C outputs parameter summary to the specified unit
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E5'
C Passed variables:
      INTEGER MUNIT            !unit number for output
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      IF (MUNIT .EQ. OUNIT) CALL CLEAR
C
      WRITE (MUNIT,2)
      WRITE (MUNIT,4)
      WRITE (MUNIT,6) TARGET
      WRITE (MUNIT,8) EBEAM
      WRITE (MUNIT,10) RMAX
      WRITE (MUNIT,12) NBASIS
      WRITE (MUNIT,14) QMAX
      WRITE (MUNIT,16) NBASIS*PI/RMAX
      WRITE (MUNIT,2)
C
2     FORMAT (' ')
4     FORMAT (' Output from example 5: Nuclear Charge Densities')
6     FORMAT (' For the target ',A10)
8     FORMAT (' the data are at a beam energy of ',F7.3,' MeV')
10    FORMAT (' the radial cutoff for the charge density=',F7.3,' fm')
12    FORMAT (' the number of sines used=', I2)
14    FORMAT (' the maximum experimental momentum transfer='
     +        ,F7.3,' fm**-1')
16    FORMAT (' the maximum numerical momentum transfer=',F7.3,'fm**-1')
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE TXTOUT(MUNIT,ITER,CHISQ,NDOF,NSINE,QBASIS,CZERO,A,Z)
C outputs the charge density parameters and goodness of fit to MUNIT
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables:
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E5'
C Input variables:
      INTEGER MUNIT                        !unit to write to
      REAL CZERO(CMAX)                     !Fourier coefficients
      INTEGER NSINE                        !number of coefficients
      INTEGER ITER                         !number of iterations
      REAL CHISQ                           !goodness of fit
      INTEGER NDOF                         !degrees of freedom in fit
      DOUBLE PRECISION A(CMAX+1,CMAX+1)    !matrix we're inverting
      REAL QBASIS                          !max num momentum transfer
      REAL Z                               !total charge
C Local variables:
      INTEGER N                            !index of CZERO
      REAL SIGMA                           !error of CZERO
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      WRITE (MUNIT,*) ' '
      WRITE (MUNIT,*) ' '
      WRITE (MUNIT,10) ITER
      WRITE (MUNIT,15) CHISQ,NDOF
      WRITE (MUNIT,20) NSINE,Z
      WRITE (MUNIT,25) QBASIS
      WRITE (MUNIT,*) ' '
      WRITE (MUNIT,30)
C
      DO 50 N=1,NSINE
         SIGMA=0.
         IF (A(N,N) .GT. 0) SIGMA=SQRT(A(N,N))
         WRITE (MUNIT,40) N,CZERO(N),SIGMA
50    CONTINUE
C
      IF (MUNIT .EQ. OUNIT) CALL PAUSE('to continue...',1)
C
10    FORMAT (' Iteration ', I4)
15    FORMAT (' Chi**2 = ',1PE15.8,' for ',I4,' degrees of freedom')
20    FORMAT (' Number of sines = ',I2, '  total charge =',F10.4)
25    FORMAT (' Maximum momentum transfer for this basis = ',1PE15.8,
     +        ' fm**-1')
30    FORMAT (' The expansion coefficients of the charge density '
     +        'and their errors are:')
40    FORMAT (' C(',I2,') = ',1PE15.8,' +- ',1PE15.8)
C
      RETURN
      END
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
      SUBROUTINE GRFOUT(DEVICE,RHO,SIGT,NSINE,DRHO)
C outputs differential cross section vs. momentum transfer
C and nuclear charge density (with error bars) vs. radius
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C Global variables
      INCLUDE 'IO.ALL'
      INCLUDE 'PARAM.E5'
      INCLUDE 'GRFDAT.ALL'
C Input variables:
      INTEGER DEVICE         !which device is being used?
      REAL SIGT(DATMAX)      !total cross section
      REAL RHO(NGRF)         !density for graphing
      REAL DRHO(NGRF)        !error in density
      INTEGER NSINE          !number of sines
C Local variables
      INTEGER IDATA,IR       !indexes data, density
      INTEGER EXPMAX,EXPMIN  !min and max exp for diff cross section
      CHARACTER*9 CEBEAM     !EBEAM as a character string
      INTEGER LENGTH         !length of character strings
      CHARACTER*9 CSINE      !number of sines as a string
      INTEGER SINLEN
      REAL X(2),Y(2)         !arrays for error bars
      INTEGER SCREEN                  !send to terminal
      INTEGER PAPER                   !make a hardcopy
      INTEGER FILE                    !send to a file
      DATA SCREEN,PAPER,FILE/1,2,3/
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
C     messages for the impatient
      IF (DEVICE .NE. SCREEN) WRITE (OUNIT,100)
C
C     calculate parameters for graphing the cross sections
      IF (DEVICE .NE. FILE) THEN
          NPLOT=1                        !how many plots?
          IPLOT=1
C
          YMAX=0.                        !find limits on data points
          YMIN=SIGT(1)
          DO 20 IDATA=1,NPTS
             IF (SIGT(IDATA) .GT. YMAX) YMAX=SIGT(IDATA)
             IF (SIGE(IDATA) .GT. YMAX) YMAX=SIGE(IDATA)
             IF (SIGT(IDATA) .LT. YMIN) YMIN=SIGT(IDATA)
             IF (SIGE(IDATA) .LT. YMIN) YMIN=SIGE(IDATA)
20        CONTINUE
C         find integer limits on exponent
          EXPMAX=INT(LOG10(YMAX))
          IF (YMAX .GT. 1.) EXPMAX =EXPMAX+1
          EXPMIN=INT(LOG10(YMIN))
          IF (YMIN .LT. 1.) EXPMIN=EXPMIN-1
          YMAX=10.**EXPMAX
          YMIN=10.**EXPMIN
C
          XMIN=QEFF(1)                 !more limits
          XMAX=QEFF(NPTS)
          Y0VAL=XMIN
          X0VAL=YMIN
C
          NPOINT=NPTS
C
          ILINE=1                      !line and symbol styles
          ISYM=1
          IFREQ=1
          NXTICK=5
          NYTICK=EXPMAX-EXPMIN
          IF (NYTICK .GT. 8) THEN      !keep number of ticks small
             IF (MOD(NYTICK,2) .EQ. 0) THEN
                NYTICK=NYTICK/2
             ELSE
                NYTICK=8
             END IF
          END IF
C
          CALL CONVRT(EBEAM,CEBEAM,LENGTH)            !titles and labels
          INFO = 'Calculated(X) and Experimental(0)'
          LABEL(1)= 'Qeffective (fm**-1)'
          LABEL(2)= 'Differential Cross Section (mBarnes/sr)'
          TITLE = ' Electron Scattering on '//TARGET
     +            //' at '//CEBEAM(1:LENGTH)//' MeV'
C
          CALL GTDEV(DEVICE)                   !device nomination
          IF (DEVICE .EQ. SCREEN) CALL GMODE   !change to graphics mode
          CALL LGLNAX                          !draw axes
      END IF
C
C     output cross sections vs. angle
      IF (DEVICE .EQ. FILE) THEN
          WRITE (GUNIT,200)
          WRITE (GUNIT,210)
          WRITE (GUNIT,220) (QEFF(IDATA),SIGT(IDATA),IDATA=1,NPTS)
      ELSE
         CALL XYPLOT(QEFF,SIGE)               !plot experimental data
         NPOINT=2
         IFREQ=0
         DO 80 IDATA=1,NPTS                    !with error bars
            X(1)=QEFF(IDATA)
            X(2)=QEFF(IDATA)
            Y(1)=SIGE(IDATA)+DSIGE(IDATA)
            Y(2)=SIGE(IDATA)-DSIGE(IDATA)
            CALL XYPLOT(X,Y)
80       CONTINUE
         NPOINT=NPTS
         IFREQ=1
         ISYM=4
         CALL XYPLOT (QEFF,SIGT)              !plot calculated sigma
         CALL GPAGE(DEVICE)
      END IF
C
C     calculate parameters for charge density
      IF (DEVICE .NE. FILE) THEN
          YMAX=0.                        !find limits on data points
          YMIN=0.
          DO 120 IR=1,NGRF
             IF (RHO(IR) .GT. YMAX) YMAX=RHO(IR)
120       CONTINUE
          XMIN=0.
          XMAX=RMAX
          Y0VAL=XMIN
          X0VAL=YMIN
C
          NPOINT=NGRF
C
          ILINE=1                      !line and symbol styles
          ISYM=4
          IFREQ=1
          NXTICK=5
          NYTICK=5
          IFREQ=0
C
          CALL ICNVRT(NSINE,CSINE,SINLEN)   !titles and labels
          INFO=' '
          LABEL(1)= 'Radius (fermis)'
          LABEL(2)= 'Nuclear charge density (fermi**-3)'
          TITLE = TARGET//' using '//CSINE(1:SINLEN)//' sine functions'
C
          CALL LNLNAX                          !draw axes
      END IF
C
C     output charge density and its error
      IF (DEVICE .EQ. FILE) THEN
         WRITE (GUNIT,*) '  '
         WRITE (GUNIT,300)
         WRITE (GUNIT,310)
         WRITE (GUNIT,320)(RGRF(IR),RHO(IR),DRHO(IR),IR=1,NGRF)
      ELSE
         CALL XYPLOT (RGRF,RHO)               !charge density
         NPOINT=2
         IFREQ=0
         DO 180 IR=1,NGRF                      !with error bars
            X(1)=RGRF(IR)
            X(2)=X(1)
            Y(1)=RHO(IR)-DRHO(IR)
            Y(2)=Y(1)+2*DRHO(IR)
            CALL XYPLOT(X,Y)
180      CONTINUE
      END IF
C
C     end graphing session
      IF (DEVICE .NE. FILE) CALL GPAGE(DEVICE)  !end graphics package
      IF (DEVICE .EQ. SCREEN) CALL TMODE        !switch to text mode
C
100   FORMAT (/,' Patience, please; output going to a file.')
200   FORMAT (10X,'Qeff (1/fermi)',9X,'Sigma (mBarnes/sr)')
210   FORMAT (10X,'--------------',9X,'------------------')
220   FORMAT (2(10X,1PE15.8))
300   FORMAT (12X,'R (fermi)',8X,'Charge density (fm**-3)',10X,'Error')
310   FORMAT (12X,'---------',8X,'-----------------------',10X,'-----')
320   FORMAT (3(9X,1PE15.8))
C
      RETURN
      END


program test
  real(kind = 8) :: PI = 3.1425

  print *, real(PI)

end program test


submodule (grid) grid_checker

implicit none (type, external)

contains

module procedure grid_check
!! Help avoid confusing errors or bad simulations
!! Must be called after both grid size and mpi gridding have been established...

real(wp) :: tol_inc, tol_inc_big, tol_big

!> check correct number of MPI images along x2 and x3
if (lx2all > 1) then
  if (modulo(lx2all, lid2) /= 0) then
    write(stderr,'(/,A,I6,A,I6,/)') 'ERROR:grid_size_root: Number of MPI images along x2', lid2, &
                                    ' not a factor of lx2all: ', lx2all
    error stop
  endif
endif

if (lx3all > 1) then
  if (modulo(lx3all, lid3) /= 0) then
    write(stderr,'(/,A,I6,A,I6,/)') 'ERROR:grid_size_root: Number of MPI images along x3', lid3, &
                                    ' not a factor of lx3all: ', lx3all
    error stop
  endif
endif

!> check for monotonic increasing

!tol_inc = 0.1
tol_inc = 1e-6     !< MZ - patched to function with dipole grids
tol_inc_big = 1d6
tol_big = 1e9
call is_monotonic_increasing(x%x1, tol_inc, tol_inc_big, tol_big, 'x1')
call is_monotonic_increasing(x%x1i, tol_inc, tol_inc_big, tol_big, 'x1i')
call is_monotonic_increasing(x%x2, tol_inc, tol_inc_big, tol_big, 'x2')
call is_monotonic_increasing(x%x2i, tol_inc, tol_inc_big, tol_big, 'x2i')
call is_monotonic_increasing(x%x3, tol_inc, tol_inc_big, tol_big, 'x3')
call is_monotonic_increasing(x%x3i, tol_inc, tol_inc_big, tol_big, 'x3i')

!> geo lat/lon

if (any(x%glat > 90) .or. any(x%glat < -90)) error stop 'geo latitude outside expected range'

if (any(x%glon < 0) .or. any(x%glon > 360)) error stop 'geo longitude outside expected range'

end procedure grid_check

subroutine is_monotonic_increasing(A, tol_inc, tol_inc_big, tol_big, name)

real(wp), intent(in) :: A(:), tol_inc, tol_inc_big, tol_big
character(*), intent(in) :: name

integer :: i

!> probably better than creating a temporary array
do i = 2,size(A)
  if(A(i) - A(i-1) < tol_inc) then
    write(stderr,*) 'ERROR:grid_check: ',name,' is not monotonic increasing'
    error stop
  endif
  if(A(i) - A(i-1) > tol_inc_big) then
    write(stderr,*) 'ERROR:grid_check: ',name,' has too large derivative'
    error stop
  endif
end do

!> not too big value
if (any(abs(A) > tol_big)) then
  write(stderr,*) 'ERROR:grid_check: ',name,' has too large values: ', maxval(A)
  error stop
end if

end subroutine is_monotonic_increasing

end submodule grid_checker


C     ( Last modified on 23 Dec 2000 at 22:01:38 )
      PROGRAM VF13MA
C
C  VF13 test driver for problems derived from SIF files.
C
C  Nick Gould, for CGT Productions.
C  July 1991.
C
      INTEGER          NMAX  , MMAX  , INF   , M , N , MAXFUN
      INTEGER          MCON  , LCN   , MEQ   , LW    , LIW   , IPRINT
      INTEGER          I , J , MGEQ
CTOY  PARAMETER ( NMAX = 10, MMAX = 10 )
CMED  PARAMETER ( NMAX = 100, MMAX = 100 )
CBIG  PARAMETER ( NMAX = 500, MMAX = 500 )
CCUS  PARAMETER ( NMAX = 200, MMAX = 200 )
      PARAMETER      ( LCN   = MMAX                      )
      PARAMETER      ( LW   = 5 * NMAX * NMAX / 2 + 43 * NMAX / 2 +
     *                        16 * MMAX + 14                         )
      PARAMETER      ( LIW  = NMAX + 1                               )
      INTEGER          IW    ( LIW )
CS    REAL             X     ( NMAX  ), BL    ( NMAX   ), BU( NMAX ),
CD    DOUBLE PRECISION X     ( NMAX  ), BL    ( NMAX   ), BU( NMAX ),
     *                 G     ( NMAX  ), C     ( MMAX   ),
     *                 CL    ( MMAX  ), CU    ( MMAX   ),
     *                 CN    ( LCN    , MMAX           ), W ( LW   )
      LOGICAL          EQUATN( MMAX  ), LINEAR( MMAX   )
      INTEGER          INPUT , IOUT
      LOGICAL          FIRSTG, DEBUG
      CHARACTER * 10   PNAME, VNAME( NMAX ), CNAME( MMAX )
      PARAMETER      ( INPUT = 55, IOUT = 6 )
CS    REAL             F, ACCREQ, ACC
CD    DOUBLE PRECISION F, ACCREQ, ACC
CS    PARAMETER      ( ACCREQ = 1.0E-7 )
CD    PARAMETER      ( ACCREQ = 1.0D-7 )
      REAL             CPU( 2 ), CALLS( 7 )
C     DEBUG = .TRUE.
      DEBUG = .FALSE.
C
C  Open the relevant file.
C
C    statements for OUTSDIF.d with generic UNIX OPEN statements.
      OPEN ( INPUT, FILE = 'OUTSDIF.d', FORM = 'FORMATTED',
     *       STATUS = 'OLD' )
      REWIND INPUT
C
C  Set up the data structures necessary to hold the problem functions.
C
      CALL VF13SE ( INPUT , IOUT  , N , M , MGEQ  , MEQ    , MCON ,
     *              X , BL, BU    , NMAX  , EQUATN, LINEAR,
     *              C , CL, CU    , MMAX  )
      IF ( DEBUG ) THEN
         WRITE( 6, 2030 ) ( I, X( I ), BL( I ), BU( I ), I = 1, N )
         IF ( MCON .GT. 0 ) WRITE( 6, 2060 ) ( I, C( I ), CL( I ),
     *        CU( I ), EQUATN( I ), LINEAR( I ), I = 1, MCON )
      END IF
C
C  Set up algorithmic input data.
C
      MAXFUN = 1000
      IPRINT = 0
      INF    = - 1
      ACC    = ACCREQ
      FIRSTG = .TRUE.
C
C  Start of main iteration loop.
C
   10 CONTINUE
C
C  Evaluate the objective function and constraints.
C
      CALL VF13FN ( N , MGEQ, MEQ, MCON, X , F, MMAX,
     *              C , BL, BU, CL, CU )
      IF ( DEBUG ) THEN
         WRITE( 6, 2010 ) F
         IF ( M .GT. 0 ) WRITE( 6, 2070 ) ( I, C( I ), I = 1, M )
      END IF
C
C  Evaluate the gradient of the objective and constraint functions.
C
      CALL VF13GR ( N , MGEQ  , MEQ   , MCON  , X     , MMAX  , C ,
     *              G, LCN, MMAX  , CN    , BL, BU, CL, CU, FIRSTG )
      IF ( DEBUG ) THEN
         WRITE( 6, 2080 )
         WRITE( 6, 2020 ) ( I, G( I ), I = 1, N )
         DO 11 J = 1, M
            WRITE( 6, 2090 ) J
            WRITE( 6, 2020 ) ( I, CN( I, J ), I = 1, N )
   11    CONTINUE
      END IF
C
C  Perform another iteration of the minimization.
C
CS      CALL VF13A ( N , M , MEQ, X, F , G , C , CN, LCN   , MAXFUN,
CD      CALL VF13AD( N , M , MEQ, X, F , G , C , CN, LCN   , MAXFUN,
     *             ACC   , IPRINT, INF   , W     , LW    , IW     )
      IF ( INF .EQ. 0 ) GO TO 10
      CALL CREPRT ( CALLS, CPU )
      CALL CNAMES( N, M, PNAME, VNAME, CNAME )
      WRITE( 6, 2110 ) F, ( I, VNAME( I ), X( I ), BL( I ), BU( I ),
     *                      I = 1, N )
      IF ( MCON .GT. 0 ) WRITE( 6, 2120 ) ( I, CNAME( I ), C( I ),
     *     CL( I ), CU( I ), EQUATN( I ), LINEAR( I ), I = 1, MCON )
      WRITE ( 6, 2000 ) PNAME, N , MCON, CALLS( 1 )  , CALLS( 2 ),
     *                  CALLS( 5 ), CALLS( 6 ), F, CPU( 1 ), CPU( 2 )
      STOP
 2000 FORMAT( /, 24('*'), ' CUTEr statistics ', 24('*') //
     *    ,' Code used               :  VF13',     /
     *    ,' Problem                 :  ', A10,    /
     *    ,' # variables             =      ', I10 /
     *    ,' # constraints           =      ', I10 /
     *    ,' # objective functions   =        ', F8.2 /
     *    ,' # objective gradients   =        ', F8.2 /
     *    ,' # constraints functions =        ', F8.2 /
     *    ,' # constraints gradients =        ', F8.2 /
     *    ,' Final f                 = ', E15.7 /
     *    ,' Set up time             =      ', 0P, F10.2, ' seconds' /
     *     ' Solve time              =      ', 0P, F10.2, ' seconds' //
     *     65('*') / )
 2010 FORMAT( /, ' Objective function value is ', 1P, D22.14 )
 2020 FORMAT( /, '     I      GRAD', /, ( I6, 1P, D12.4 ) )
 2030 FORMAT( /, ' After projection, the starting point:',
     *        /, '     I      X          BL          BU', /,
     *        ( I6, 1P, 3D12.4 ) )
 2060 FORMAT( /, ' the constraints:', /,
     *         '     I  MULTIPLIER     CL          CU      EQUALITY? ',
     *       '  LINEAR? ', /, ( I6, 1P, 3D12.4, 5X, L1, 10X, L1 ) )
 2070 FORMAT( /, ' the constraint values are:',
     *        /, '     I      C ', /, ( I6, 1P, D12.4 ) )
 2080 FORMAT( /, ' Objective function ' )
 2090 FORMAT( /, ' Constraint ', I6 )
 2100 FORMAT( /, ' Set up time = ', 0P, F12.2,
     *        /, '  Solve time = ', 0P, F12.2,
     *        /, '  Total time = ', 0P, F12.2, ' seconds' )
 2110 FORMAT( /, ' the objective function value: ', 1P, D12.4, /,
     *        /, ' the variables:', /,
     *        '     I name          value    lower bound upper bound',
     *        /, ( I6, 1X, A10, 1P, 3D12.4 ) )
 2120 FORMAT( /, ' the constraints:', /,
     *        '     I name          value    lower bound upper bound',
     *        ' equality?   linear? ',
     *        /, ( I6, 1X, A10, 1P, 3D12.4, 5X, L1, 10X, L1 ) )
C
C  End of VF13MA.
C
      END
C
      SUBROUTINE VF13SE( INPUT , IOUT  , N , M , MGEQ  , MEQ    ,
     *                   MCON  , X , BL, BU    , NMAX  , EQUATN,
     *                   LINEAR, V , CL, CU    , MMAX  )
      INTEGER            INPUT , IOUT  , N , M , MGEQ  , MEQ    , MCON
      INTEGER            NMAX  , MMAX
CS    REAL               X     ( NMAX ), BL    ( NMAX ), BU    ( NMAX )
CS    REAL               V     ( MMAX ), CL    ( MMAX ), CU    ( MMAX )
CD    DOUBLE PRECISION   X     ( NMAX ), BL    ( NMAX ), BU    ( NMAX )
CD    DOUBLE PRECISION   V     ( MMAX ), CL    ( MMAX ), CU    ( MMAX )
      LOGICAL            EQUATN( MMAX ), LINEAR( MMAX )
C
C  Set up the input data for the the VF13 minimizer.
C
C  Nick Gould, for CGT productions,
C  7th November, 1991.
C
      INTEGER            I
CS    REAL               BIGINF
CD    DOUBLE PRECISION   BIGINF
CS    PARAMETER        ( BIGINF = 9.0E+19 )
CD    PARAMETER        ( BIGINF = 9.0D+19 )

C
C  Set up the data structures necessary to hold the problem functions.
C
      CALL CSETUP ( INPUT , IOUT  , N     , MCON  , X , BL , BU   ,
     *              NMAX  , EQUATN, LINEAR, V , CL, CU     , MMAX,
     *              .TRUE., .FALSE., .FALSE. )
C
C  Count the number of general equality constraints.
C
      M    = MCON
      MGEQ = 0
      DO 20 I = 1, M
         IF ( EQUATN( I ) ) MGEQ = MGEQ + 1
   20 CONTINUE
C     IF ( M .GT. 0 ) WRITE( 6, 2010 ) ( I, V( I ), CL( I ), CU( I ),
C    *                             EQUATN( I ), LINEAR( I ), I = 1, M )
      MEQ = MGEQ
C
C  If constraints have both lower and upper bounds, they have to be
C  included twice!
C
      DO 40 I = MGEQ + 1, MCON
         IF ( CL( I ) .GT. - BIGINF .AND.
     *        CU( I ) .LT.   BIGINF ) M = M + 1
   40 CONTINUE
C
C  Include any simple bounds.
C
      DO 50 I = 1, N
         IF ( BL( I ) .EQ.  BU( I ) ) THEN
            MEQ = MEQ + 1
            M   = M   + 1
         ELSE
            IF ( BL( I ) .GT. - BIGINF ) M = M + 1
            IF ( BU( I ) .LT.   BIGINF ) M = M + 1
         END IF
   50 CONTINUE
      IF ( M .GT. MMAX ) THEN
         IF ( IOUT .GT. 0 )
     *      WRITE( IOUT, 2000 ) 'EQUATN', 'MMAX  ', M - MMAX
         STOP
      END IF
      RETURN
C
C  Non-executable statements.
C
 2000 FORMAT( /, ' ** Program CSETUP: array length ', A6, ' too small.',
     *        /, ' -- Miminimization abandoned.',
     *        /, ' -- Increase the parameter ', A6, ' by at least ', I8,
     *           ' and restart.'  )
C2010 FORMAT( /, ' the constraints:', /,
C    *         '     I  MULTIPLIER     CL          CU      EQUALITY? ',
C    *       '  LINEAR? ', /, ( I6, 1P, 3D12.4, 5X, L1, 10X, L1 ) )
C
C  End of VF13SE.
C
      END
C
      SUBROUTINE VF13FN( N , MGEQ, MEQ, MCON, X, F, LC,
     *                   C , BL, BU, CL, CU )
      INTEGER            N , MGEQ, MEQ, MCON, LC
CS    REAL               F
CD    DOUBLE PRECISION   F
CS    REAL               X     ( N    ), C     ( LC )
CD    DOUBLE PRECISION   X     ( N    ), C     ( LC )
CS    REAL               BL    ( N    ), BU    ( N    )
CS    REAL               CL    ( LC   ), CU    ( LC   )
CD    DOUBLE PRECISION   BL    ( N    ), BU    ( N    )
CD    DOUBLE PRECISION   CL    ( LC   ), CU    ( LC   )
C
C  Evaluate the objective function and constraints.
C
C  Nick Gould, for CGT productions.
C  November 1991.
C
      INTEGER            I , MT, MFIXED, MFIXVA
CS    REAL               BIGINF
CD    DOUBLE PRECISION   BIGINF
CS    PARAMETER        ( BIGINF = 9.0E+19 )
CD    PARAMETER        ( BIGINF = 9.0D+19 )
      CALL CFN ( N , MCON , X , F , LC, C )
C
C  If there are fixed variables, shift all the inequality constraint values.
C
      MFIXED = MEQ - MGEQ
      MFIXVA = MGEQ
      IF ( MFIXED .GT. 0 ) THEN
         DO 10 I = MCON, MGEQ + 1, - 1
            C( I + MFIXED ) = C( I )
   10    CONTINUE
      END IF
C
C  If constraints have both lower and upper bounds, they have to
C  be included twice! Reverse the signs of less-than-or-equal-to
C  constraints.
C
      MT      = MCON + MFIXED
      DO 40 I = MGEQ + 1, MCON
         IF ( CL( I ) .GT. - BIGINF .AND.
     *        CU( I ) .LT.   BIGINF ) THEN
            MT               = MT + 1
            C( MT          ) = CU( I ) - C( I + MFIXED )
            C( I  + MFIXED ) = C( I + MFIXED ) - CL( I )
         ELSE IF ( CL( I ) .GT. - BIGINF ) THEN
            C( I + MFIXED )  = C( I + MFIXED ) - CL( I )
         ELSE IF ( CU( I ) .LT.   BIGINF ) THEN
            C( I + MFIXED )  = CU( I ) - C( I + MFIXED )
         END IF
   40 CONTINUE
C
C  Include any simple bounds, including fixed variables.
C
      DO 50 I = 1, N
         IF ( BL( I ) .EQ.  BU( I ) ) THEN
            MFIXVA      = MFIXVA + 1
            C( MFIXVA ) = X( I ) - BL( I )
         ELSE
            IF ( BL( I ) .GT. - BIGINF ) THEN
               MT       = MT + 1
               C( MT  ) = X( I ) - BL( I )
            END IF
            IF ( BU( I ) .LT.   BIGINF ) THEN
               MT      = MT + 1
               C( MT ) = BU( I ) - X( I )
            END IF
         END IF
   50 CONTINUE
      RETURN
C
C  End of VF13FN.
C
      END
C  THIS VERSION: 03/06/1994 AT 11:38:39 AM.
      SUBROUTINE VF13GR( N , MGEQ  , MEQ  , MCON  , X , LV, V , G ,
     *                   LCN   , MMAX  , CN   , BL, BU, CL, CU, FIRSTG )
      INTEGER            N , MGEQ  , MEQ   , MCON , LV
      INTEGER            LCN   , MMAX
      LOGICAL            FIRSTG
CS    REAL               X( N ), G( N ), V( LV ), CN( LCN, MMAX )
CS    REAL               BL    ( N    ), BU    ( N    )
CS    REAL               CL    ( MMAX ), CU    ( MMAX )
CD    DOUBLE PRECISION   X( N ), G( N ), V( LV ), CN( LCN, MMAX )
CD    DOUBLE PRECISION   BL    ( N    ), BU    ( N    )
CD    DOUBLE PRECISION   CL    ( MMAX ), CU    ( MMAX )
C
C  Evaluate the gradient of the objective and constraint functions.
C
C  Nick Gould, for CGT productions,
C  November 1991.
C
      INTEGER            I , J , MT    , MFIXED, MFIXVA
CS    REAL               BIGINF, ZERO  , ONE
CD    DOUBLE PRECISION   BIGINF, ZERO  , ONE
CS    PARAMETER        ( ZERO  = 0.0E+0, ONE  = 1.0E+0 )
CD    PARAMETER        ( ZERO  = 0.0D+0, ONE  = 1.0D+0 )
CS    PARAMETER        ( BIGINF = 9.0E+19 )
CD    PARAMETER        ( BIGINF = 9.0D+19 )
C
C  Evaluate the gradient of the objective and constraint functions
C  at the initial point in a dense format.
C
      CALL CGR   ( N , MCON , X, .FALSE., MMAX, V , G ,
     *             .TRUE., LCN, MMAX , CN    )
C
C  If there are fixed variables, shift all the  gradients of the
C  inequality constraints.
C
      MFIXED = MEQ - MGEQ
      MFIXVA = MGEQ
      IF ( MFIXED .GT. 0 ) THEN
         DO 20 I = MCON, MGEQ + 1, - 1
            DO 10 J = 1, N
               CN( J, I + MFIXED ) = CN( J, I )
   10       CONTINUE
   20    CONTINUE
      END IF
C
C  If constraints have both lower and upper bounds, their gradients
C  have to be included twice! Reverse the signs of less-than-or-equal-
C  -to constraints.
C
      MT      = MCON + MFIXED
      DO 50 I = MGEQ + 1, MCON
         IF ( CL( I ) .GT. - BIGINF .AND.
     *        CU( I ) .LT.   BIGINF ) THEN
            MT      = MT + 1
            DO 30 J = 1, N
               CN( J, MT ) = - CN( J, I + MFIXED )
   30       CONTINUE
         ELSE IF ( CU( I ) .LT.   BIGINF ) THEN
           DO 40 J = 1, N
               CN( J, I + MFIXED ) = - CN( J, I + MFIXED )
   40       CONTINUE
         END IF
   50 CONTINUE
C
C  Include the gradients of any simple bounds, including
C  fixed variables.
C
      IF ( FIRSTG .OR. MFIXED .GT. 0 ) THEN
         DO 90 I = 1, N
            IF ( BL( I ) .EQ. BU( I ) ) THEN
               MFIXVA  = MFIXVA + 1
               DO 60 J = 1, N
                  CN( J, MFIXVA ) = ZERO
   60          CONTINUE
               CN( I, MFIXVA ) =  ONE
            ELSE
               IF ( FIRSTG ) THEN
                  IF ( BL( I ) .GT. - BIGINF ) THEN
                     MT      = MT + 1
                     DO 70 J = 1, N
                        CN( J, MT ) = ZERO
   70                CONTINUE
                     CN( I, MT ) =  ONE
                  END IF
                  IF ( BU( I ) .LT.   BIGINF ) THEN
                     MT      = MT + 1
                     DO 80 J = 1, N
                        CN( J, MT ) = ZERO
   80                CONTINUE
                     CN( I, MT ) =  - ONE
                  END IF
               END IF
            END IF
   90    CONTINUE
         FIRSTG = .FALSE.
      END IF
      RETURN
C
C  End of VF13GR.
C
      END


program alloc_test
    use :: precision_defs, only : dp
    use :: matrix_ops, only : init_matrix, print_matrix
    implicit none
    integer :: M, N, i, j
    real(kind=dp), allocatable, dimension(:,:) :: A
    character(len=1024) :: buffer
    character(len=:), allocatable :: label_str

    select case (command_argument_count())
        case (2)
            call get_command_argument(1, buffer)
            read (buffer, "(I20)") M
            call get_command_argument(2, buffer)
            read (buffer, "(I20)") N
        case (1)
            call get_command_argument(1, buffer)
            read (buffer, "(I20)") M
            N = M
        case default
            M = 4
            N = 5
    end select

    if (.not. allocated(A)) print '(A)', '# A not allocated yet'
    allocate(A(M, N))
    if (allocated(A)) print '(A)', '# A allocated'
    call init_matrix(A)
    label_str = "A"
    call print_matrix(A, label=label_str)
    A = reshape([ ((i*size(A, 2) + j, i = 0, size(A, 1) - 1), &
                   j = 1, size(A, 2)) ], shape(A))
    call print_matrix(A, "A'")
    deallocate(A)
    if (.not. allocated(A)) print '(A)', '# A no longer allocated'

end program alloc_test


! Copyright (c) 2015-2021, the ELSI team.
! All rights reserved.
!
! This file is part of ELSI and is distributed under the BSD 3-clause license,
! which may be found in the LICENSE file in the ELSI root directory.

!>
!! Provide implementations of the heapsort algorithm.
!!
module ELSI_SORT

   use ELSI_PRECISION, only: r8,i4,i8

   implicit none

   private

   public :: elsi_heapsort
   public :: elsi_permute
   public :: elsi_unpermute

   interface swap
      module procedure swap_i8
      module procedure swap_i4
      module procedure swap_r8
   end interface

   interface downheap
      module procedure downheap_i4
      module procedure downheap_i8
      module procedure downheap_r8
   end interface

   interface elsi_heapsort
      module procedure heapsort_i4
      module procedure heapsort_i8
      module procedure heapsort_r8
   end interface

   interface elsi_permute
      module procedure permute_i4
      module procedure permute_r8
      module procedure permute_c16
   end interface

   interface elsi_unpermute
      module procedure unpermute_r8
      module procedure unpermute_c16
   end interface

contains

!>
!! Sort a real(kind=r8) array by heapsort, returns an array of permutation.
!!
subroutine heapsort_r8(length,array,perm)

   implicit none

   integer(kind=i4), intent(in) :: length
   real(kind=r8), intent(inout) :: array(length)
   integer(kind=i4), intent(out) :: perm(length)

   integer(kind=i4) :: top
   integer(kind=i4) :: i

   do i = 1,length
      perm(i) = i
   end do

   top = length/2

   do i = top,1,-1
      call downheap(length,array,perm,i,length)
   end do

   i = length

   do while(i > 1)
      call swap(length,array,1,i)
      call swap(length,perm,1,i)

      i = i-1

      call downheap(length,array,perm,1,i)
   end do

end subroutine

!>
!! Restore the max-heap structure.
!!
subroutine downheap_r8(length,a_r8,b_i4,top,bottom)

   implicit none

   integer(kind=i4), intent(in) :: length
   real(kind=r8), intent(inout) :: a_r8(length)
   integer(kind=i4), intent(inout) :: b_i4(length)
   integer(kind=i4), intent(in) :: top
   integer(kind=i4), intent(in) :: bottom

   integer(kind=i4) :: v
   integer(kind=i4) :: w

   v = top
   w = 2*v

   do while(w <= bottom)
      if(w+1 <= bottom) then
         if(a_r8(w+1) > a_r8(w)) then
            w = w+1
         end if
      end if

      if(a_r8(v) >= a_r8(w)) then
         return
      else
         call swap(length,a_r8,v,w)
         call swap(length,b_i4,v,w)

         v = w
         w = 2*v
      end if
   end do

end subroutine

!>
!! Sort an integer(kind=i8) array by heapsort, returns an array of permutation.
!!
subroutine heapsort_i8(length,array,perm)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i8), intent(inout) :: array(length)
   integer(kind=i4), intent(out) :: perm(length)

   integer(kind=i4) :: top
   integer(kind=i4) :: i

   do i = 1,length
      perm(i) = i
   end do

   top = length/2

   do i = top,1,-1
      call downheap(length,array,perm,i,length)
   end do

   i = length

   do while(i > 1)
      call swap(length,array,1,i)
      call swap(length,perm,1,i)

      i = i-1

      call downheap(length,array,perm,1,i)
   end do

end subroutine

!>
!! Restore the max-heap structure.
!!
subroutine downheap_i8(length,a_i8,b_i4,top,bottom)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i8), intent(inout) :: a_i8(length)
   integer(kind=i4), intent(inout) :: b_i4(length)
   integer(kind=i4), intent(in) :: top
   integer(kind=i4), intent(in) :: bottom

   integer(kind=i4) :: v
   integer(kind=i4) :: w

   v = top
   w = 2*v

   do while(w <= bottom)
      if(w+1 <= bottom) then
         if(a_i8(w+1) > a_i8(w)) then
            w = w+1
         end if
      end if

      if(a_i8(v) >= a_i8(w)) then
         return
      else
         call swap(length,a_i8,v,w)
         call swap(length,b_i4,v,w)

         v = w
         w = 2*v
      end if
   end do

end subroutine

!>
!! Sort an integer(kind=i4) array by heapsort, returns an array of permutation.
!!
subroutine heapsort_i4(length,array,perm)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(inout) :: array(length)
   integer(kind=i4), intent(out) :: perm(length)

   integer(kind=i4) :: top
   integer(kind=i4) :: i

   do i = 1,length
      perm(i) = i
   end do

   top = length/2

   do i = top,1,-1
      call downheap(length,array,perm,i,length)
   end do

   i = length

   do while(i > 1)
      call swap(length,array,1,i)
      call swap(length,perm,1,i)

      i = i-1

      call downheap(length,array,perm,1,i)
   end do

end subroutine

!>
!! Restore the max-heap structure.
!!
subroutine downheap_i4(length,a_i4,b_i4,top,bottom)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(inout) :: a_i4(length)
   integer(kind=i4), intent(inout) :: b_i4(length)
   integer(kind=i4), intent(in) :: top
   integer(kind=i4), intent(in) :: bottom

   integer(kind=i4) :: v
   integer(kind=i4) :: w

   v = top
   w = 2*v

   do while(w <= bottom)
      if(w+1 <= bottom) then
         if(a_i4(w+1) > a_i4(w)) then
            w = w+1
         end if
      end if

      if(a_i4(v) >= a_i4(w)) then
         return
      else
         call swap(length,a_i4,v,w)
         call swap(length,b_i4,v,w)

         v = w
         w = 2*v
      end if
   end do

end subroutine

!>
!! Permute an integer(kind=i4) array.
!!
subroutine permute_i4(length,perm,array)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(in) :: perm(length)
   integer(kind=i4), intent(inout) :: array(length)

   integer(kind=i4) :: i
   integer(kind=i4) :: work(length)

   do i = 1,length
      work(i) = array(perm(i))
   end do

   array = work

end subroutine

!>
!! Permute a real(kind=r8) array.
!!
subroutine permute_r8(length,perm,array)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(in) :: perm(length)
   real(kind=r8), intent(inout) :: array(length)

   real(kind=r8) :: work(length)
   integer(kind=i4) :: i

   do i = 1,length
      work(i) = array(perm(i))
   end do

   array = work

end subroutine

!>
!! Permute a complex(kind=r8) array.
!!
subroutine permute_c16(length,perm,array)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(in) :: perm(length)
   complex(kind=r8), intent(inout) :: array(length)

   complex(kind=r8) :: work(length)
   integer(kind=i4) :: i

   do i = 1,length
      work(i) = array(perm(i))
   end do

   array = work

end subroutine

!>
!! Unpermute a real(kind=r8) array.
!!
subroutine unpermute_r8(length,perm,array)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(in) :: perm(length)
   real(kind=r8), intent(inout) :: array(length)

   real(kind=r8) :: work(length)
   integer(kind=i4) :: i

   do i = 1,length
      work(perm(i)) = array(i)
   end do

   array = work

end subroutine

!>
!! Unpermute a complex(kind=r8) array.
!!
subroutine unpermute_c16(length,perm,array)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(in) :: perm(length)
   complex(kind=r8), intent(inout) :: array(length)

   complex(kind=r8) :: work(length)
   integer(kind=i4) :: i

   do i = 1,length
      work(perm(i)) = array(i)
   end do

   array = work

end subroutine

!>
!! Swap two numbers in an integer(kind=i8) array.
!!
subroutine swap_i8(length,array,i,j)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i8), intent(inout) :: array(length)
   integer(kind=i4), intent(in) :: i
   integer(kind=i4), intent(in) :: j

   integer(kind=i8) :: tmp

   tmp = array(i)
   array(i) = array(j)
   array(j) = tmp

end subroutine

!>
!! Swap two numbers in an integer(kind=i4) array.
!!
subroutine swap_i4(length,array,i,j)

   implicit none

   integer(kind=i4), intent(in) :: length
   integer(kind=i4), intent(inout) :: array(length)
   integer(kind=i4), intent(in) :: i
   integer(kind=i4), intent(in) :: j

   integer(kind=i4) :: tmp

   tmp = array(i)
   array(i) = array(j)
   array(j) = tmp

end subroutine

!>
!! Swap two numbers in a real(kind=r8) array.
!!
subroutine swap_r8(length,array,i,j)

   implicit none

   integer(kind=i4), intent(in) :: length
   real(kind=r8), intent(inout) :: array(length)
   integer(kind=i4), intent(in) :: i
   integer(kind=i4), intent(in) :: j

   real(kind=r8) :: tmp

   tmp = array(i)
   array(i) = array(j)
   array(j) = tmp

end subroutine

end module ELSI_SORT


! { dg-do run }
! Test assignments of nested derived types with allocatable components(PR 20541).
!
! Contributed by Erik Edelmann  <eedelmann@gcc.gnu.org>
!            and Paul Thomas  <pault@gcc.gnu.org>
!
  type :: a
    integer, allocatable :: i(:)
  end type a

  type :: b
    type (a), allocatable :: at(:)
  end type b

  type(a) :: x(2)
  type(b) :: y(2), z(2)
  integer i, m(4)

  x(1) = a((/1,2,3,4/))
  x(2) = a((/1,2,3,4/)+10)

  y(1) = b((/x(1),x(2)/))
  y(2) = b((/x(2),x(1)/))

  y(2) = y(1)
  forall (j=1:2,k=1:4, y(1)%at(j)%i(k) .ne. y(2)%at(j)%i(k)) &
                             y(1)%at(j)%i(k) = 999
  if (any ((/((y(1)%at(j)%i(k), k=1,4),j=1,2)/) .eq. 999)) call abort ()

  z = y
  forall (i=1:2,j=1:2,k=1:4, z(i)%at(j)%i(k) .ne. y(i)%at(j)%i(k)) &
                             z(i)%at(j)%i(k) = 999
  if (any ((/(((z(i)%at(j)%i(k), k=1,4),j=1,2),i=1,2)/) .eq. 999)) call abort ()

end