!program main
!
!!*****************************************************************************80
!!
!!! MAIN is the main program for JACOBI_RULE.
!!
!!  Discussion:
!!
!!    This program computes a standard Gauss-Jacobi quadrature rule
!!    and writes it to a file.
!!
!!    The user specifies:
!!    * the ORDER (number of points) in the rule;
!!    * ALPHA, the exponent of (1-x);
!!    * BETA, the exponent of (1+x);
!!    * A, the left endpoint;
!!    * B, the right endpoint;
!!    * FILENAME, fhe root name of the output files.
!!
!!  Licensing:
!!
!!    This code is distributed under the GNU LGPL license.
!!
!!  Modified:
!!
!!    28 February 2010
!!
!!  Author:
!!
!!    John Burkardt
!!
!  implicit none
!
!  real ( kind = 8 ) a
!  real ( kind = 8 ) alpha
!  integer ( kind = 4 ) arg_num
!  real ( kind = 8 ) b
!  real ( kind = 8 ) beta
!  character ( len = 255 ) filename
!  integer ( kind = 4 ) iarg
!  integer ( kind = 4 ) iargc
!  integer ( kind = 4 ) ierror
!  integer ( kind = 4 ) kind
!  integer ( kind = 4 ) last
!  integer ( kind = 4 ) order
!  real ( kind = 8 ) r(2)
!  character ( len = 255 ) string
!  real ( kind = 8 ), allocatable, dimension ( : ) :: w
!  real ( kind = 8 ), allocatable, dimension ( : ) :: x
!
!  call timestamp ( )
!  write ( *, '(a)' ) ' '
!  write ( *, '(a)' ) 'JACOBI_RULE'
!  write ( *, '(a)' ) '  FORTRAN90 version'
!  write ( *, '(a)' ) ' '
!  write ( *, '(a)' ) '  Compute a Gauss-Jacobi rule for approximating'
!  write ( *, '(a)' ) &
!    '    Integral ( A <= x <= B ) (B-x)^alpha (x-A)^beta f(x) dx'
!  write ( *, '(a)' ) '  of order ORDER.'
!  write ( *, '(a)' ) ' '
!  write ( *, '(a)' ) &
!    '  The user specifies ORDER, ALPHA, BETA, A, B, and FILENAME.'
!  write ( *, '(a)' ) ' '
!  write ( *, '(a)' ) '  ORDER is the number of points:'
!  write ( *, '(a)' ) '  ALPHA is the exponent of (B-X)'
!  write ( *, '(a)' ) '  BETA is the exponent of (X-A):'
!  write ( *, '(a)' ) '  A is the left endpoint;'
!  write ( *, '(a)' ) '  B is the right endpoint;'
!  write ( *, '(a)' ) '  FILENAME is used to generate 3 files:'
!  write ( *, '(a)' ) '    filename_w.txt - the weight file'
!  write ( *, '(a)' ) '    filename_x.txt - the abscissa file.'
!  write ( *, '(a)' ) '    filename_r.txt - the region file.'
!!
!!  Get the number of command line arguments.
!!
!  arg_num = iargc ( )
!!
!!  Get ORDER.
!!
!  if ( 1 <= arg_num ) then
!    iarg = 1
!    call getarg ( iarg, string )
!    call s_to_i4 ( string, order, ierror, last )
!  else
!    write ( *, '(a)' ) ' '
!    write ( *, '(a)' ) '  Enter the rule order ORDER:'
!    read ( *, * ) order
!  end if
!!
!!  Get ALPHA
!!
!  if ( 2 <= arg_num ) then
!    iarg = 2
!    call getarg ( iarg, string )
!    call s_to_r8 ( string, alpha, ierror, last )
!  else
!    write ( *, '(a)' ) ' '
!    write ( *, '(a)' ) '  ALPHA is the exponent of (B-x) in the integral:'
!    write ( *, '(a)' ) '  Note that -1.0 < ALPHA is required.'
!    write ( *, '(a)' ) '  Enter the value of ALPHA:'
!    read ( *, * ) alpha
!  end if
!!
!!  Get BETA
!!
!  if ( 3 <= arg_num ) then
!    iarg = 3
!    call getarg ( iarg, string )
!    call s_to_r8 ( string, beta, ierror, last )
!  else
!    write ( *, '(a)' ) ' '
!    write ( *, '(a)' ) '  BETA is the exponent of (x-A) in the integral:'
!    write ( *, '(a)' ) '  Note that -1.0 < BETA is required.'
!    write ( *, '(a)' ) '  Enter the value of BETA:'
!    read ( *, * ) beta
!  end if
!!
!!  Get A.
!!
!  if ( 4 <= arg_num ) then
!    iarg = 4
!    call getarg ( iarg, string )
!    call s_to_r8 ( string, a, ierror, last )
!  else
!    write ( *, '(a)' ) ' '
!    write ( *, '(a)' ) '  Enter A, the left endpoint:'
!    read ( *, * ) a
!  end if
!!
!!  Get B.
!!
!  if ( 5 <= arg_num ) then
!    iarg = 5
!    call getarg ( iarg, string )
!    call s_to_r8 ( string, b, ierror, last )
!  else
!    write ( *, '(a)' ) ' '
!    write ( *, '(a)' ) '  Enter B, the right endpoint:'
!    read ( *, * ) b
!  end if
!!
!!  Get FILENAME.
!!
!  if ( 6 <= arg_num ) then
!    iarg = 6
!    call getarg ( iarg, filename )
!  else
!    write ( *, '(a)' ) ' '
!    write ( *, '(a)' ) &
!      '  Enter FILENAME, the "root name" of the quadrature files).'
!    read ( *, '(a)' ) filename
!  end if
!!
!!  Input summary.
!!
!  write ( *, '(a)' ) ' '
!  write ( *, '(a)' ) '  Input summary:'
!  write ( *, '(a)' ) ' '
!  write ( *, '(a,i8)'      ) '  ORDER = ', order
!  write ( *, '(a,g14.6)'   ) '  ALPHA = ', alpha
!  write ( *, '(a,g14.6)'   ) '  BETA = ', beta
!  write ( *, '(a,g14.6)'   ) '  A = ', a
!  write ( *, '(a,g14.6)'   ) '  B = ', b
!  write ( *, '(a)'         ) '  OUTPUT = "' // trim ( filename ) // '".'
!!
!!  Construct the rule.
!!
!  allocate ( w(order) )
!  allocate ( x(order) )
!
!  kind = 4
!  call cgqf ( order, kind, alpha, beta, a, b, x, w )
!!
!!  Write the rule.
!!
!  r(1) = a
!  r(2) = b
!
!  call rule_write ( order, x, w, r, filename )
!!
!!  Free memory.
!!
!  deallocate ( w )
!  deallocate ( x )
!!
!!  Terminate.
!!
!  write ( *, '(a)' ) ' '
!  write ( *, '(a)' ) 'JACOBI_RULE:'
!  write ( *, '(a)' ) '  Normal end of execution.'
!  write ( *, '(a)' ) ' '
!  call timestamp ( )
!
!  stop
!end
subroutine cdgqf ( nt, kind, alpha, beta, t, wts )

!*****************************************************************************80
!
!! CDGQF computes a Gauss quadrature formula with default A, B and simple knots.
!
!  Discussion:
!
!    This routine computes all the knots and weights of a Gauss quadrature
!    formula with a classical weight function with default values for A and B,
!    and only simple knots.
!
!    There are no moments checks and no printing is done.
!
!    Use routine EIQFS to evaluate a quadrature computed by CGQFS.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    04 January 2010
!
!  Author:
!
!    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    Sylvan Elhay, Jaroslav Kautsky,
!    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
!    Interpolatory Quadrature,
!    ACM Transactions on Mathematical Software,
!    Volume 13, Number 4, December 1987, pages 399-415.
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) NT, the number of knots.
!
!    Input, integer ( kind = 4 ) KIND, the rule.
!    1, Legendre,             (a,b)       1.0
!    2, Chebyshev,            (a,b)       ((b-x)*(x-a))^(-0.5)
!    3, Gegenbauer,           (a,b)       ((b-x)*(x-a))^alpha
!    4, Jacobi,               (a,b)       (b-x)^alpha*(x-a)^beta
!    5, Generalized Laguerre, (a,inf)     (x-a)^alpha*exp(-b*(x-a))
!    6, Generalized Hermite,  (-inf,inf)  |x-a|^alpha*exp(-b*(x-a)^2)
!    7, Exponential,          (a,b)       |x-(a+b)/2.0|^alpha
!    8, Rational,             (a,inf)     (x-a)^alpha*(x+b)^beta
!
!    Input, real ( kind = 8 ) ALPHA, the value of Alpha, if needed.
!
!    Input, real ( kind = 8 ) BETA, the value of Beta, if needed.
!
!    Output, real ( kind = 8 ) T(NT), the knots.
!
!    Output, real ( kind = 8 ) WTS(NT), the weights.
!
  implicit none

  integer ( kind = 4 ) nt

  real ( kind = 8 ) aj(nt)
  real ( kind = 8 ) alpha
  real ( kind = 8 ) beta
  real ( kind = 8 ) bj(nt)
  integer ( kind = 4 ) kind
  real ( kind = 8 ) t(nt)
  real ( kind = 8 ) wts(nt)
  real ( kind = 8 ) zemu

  call parchk ( kind, 2 * nt, alpha, beta )
!
!  Get the Jacobi matrix and zero-th moment.
!
  call class_matrix ( kind, nt, alpha, beta, aj, bj, zemu )
!
!  Compute the knots and weights.
!
  call sgqf ( nt, aj, bj, zemu, t, wts )

  return
end
subroutine cgqf ( nt, kind, alpha, beta, a, b, t, wts )

!*****************************************************************************80
!
!! CGQF computes knots and weights of a Gauss quadrature formula.
!
!  Discussion:
!
!    The user may specify the interval (A,B).
!
!    Only simple knots are produced.
!
!    Use routine EIQFS to evaluate this quadrature formula.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    16 February 2010
!
!  Author:
!
!    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    Sylvan Elhay, Jaroslav Kautsky,
!    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
!    Interpolatory Quadrature,
!    ACM Transactions on Mathematical Software,
!    Volume 13, Number 4, December 1987, pages 399-415.
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) NT, the number of knots.
!
!    Input, integer ( kind = 4 ) KIND, the rule.
!    1, Legendre,             (a,b)       1.0
!    2, Chebyshev Type 1,     (a,b)       ((b-x)*(x-a))^-0.5)
!    3, Gegenbauer,           (a,b)       ((b-x)*(x-a))^alpha
!    4, Jacobi,               (a,b)       (b-x)^alpha*(x-a)^beta
!    5, Generalized Laguerre, (a,+oo)     (x-a)^alpha*exp(-b*(x-a))
!    6, Generalized Hermite,  (-oo,+oo)   |x-a|^alpha*exp(-b*(x-a)^2)
!    7, Exponential,          (a,b)       |x-(a+b)/2.0|^alpha
!    8, Rational,             (a,+oo)     (x-a)^alpha*(x+b)^beta
!    9, Chebyshev Type 2,     (a,b)       ((b-x)*(x-a))^(+0.5)
!
!    Input, real ( kind = 8 ) ALPHA, the value of Alpha, if needed.
!
!    Input, real ( kind = 8 ) BETA, the value of Beta, if needed.
!
!    Input, real ( kind = 8 ) A, B, the interval endpoints, or
!    other parameters.
!
!    Output, real ( kind = 8 ) T(NT), the knots.
!
!    Output, real ( kind = 8 ) WTS(NT), the weights.
!
  implicit none

  integer ( kind = 4 ) nt

  real ( kind = 8 ) a
  real ( kind = 8 ) alpha
  real ( kind = 8 ) b
  real ( kind = 8 ) beta
  integer ( kind = 4 ) i
  integer ( kind = 4 ) kind
  integer ( kind = 4 ), allocatable :: mlt(:)
  integer ( kind = 4 ), allocatable :: ndx(:)
  real ( kind = 8 ) t(nt)
  real ( kind = 8 ) wts(nt)
!
!  Compute the Gauss quadrature formula for default values of A and B.
!
  call cdgqf ( nt, kind, alpha, beta, t, wts )
!
!  Prepare to scale the quadrature formula to other weight function with
!  valid A and B.
!
  allocate ( mlt(1:nt) )

  mlt(1:nt) = 1

  allocate ( ndx(1:nt) )

  do i = 1, nt
    ndx(i) = i
  end do

  call scqf ( nt, t, mlt, wts, nt, ndx, wts, t, kind, alpha, beta, a, b )

  deallocate ( mlt )
  deallocate ( ndx )

  return
end
subroutine ch_cap ( c )

!*****************************************************************************80
!
!! CH_CAP capitalizes a single character.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    19 July 1998
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Input/output, character C, the character to capitalize.
!
  implicit none

  character c
  integer ( kind = 4 ) itemp

  itemp = ichar ( c )

  if ( 97 <= itemp .and. itemp <= 122 ) then
    c = char ( itemp - 32 )
  end if

  return
end
function ch_eqi ( c1, c2 )

!*****************************************************************************80
!
!! CH_EQI is a case insensitive comparison of two characters for equality.
!
!  Example:
!
!    CH_EQI ( 'A', 'a' ) is .TRUE.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    28 July 2000
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Input, character C1, C2, the characters to compare.
!
!    Output, logical CH_EQI, the result of the comparison.
!
  implicit none

  logical ch_eqi
  character c1
  character c1_cap
  character c2
  character c2_cap

  c1_cap = c1
  c2_cap = c2

  call ch_cap ( c1_cap )
  call ch_cap ( c2_cap )

  if ( c1_cap == c2_cap ) then
    ch_eqi = .true.
  else
    ch_eqi = .false.
  end if

  return
end
subroutine ch_to_digit ( c, digit )

!*****************************************************************************80
!
!! CH_TO_DIGIT returns the value of a base 10 digit.
!
!  Example:
!
!     C   DIGIT
!    ---  -----
!    '0'    0
!    '1'    1
!    ...  ...
!    '9'    9
!    ' '    0
!    'X'   -1
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    04 August 1999
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Input, character C, the decimal digit, '0' through '9' or blank
!    are legal.
!
!    Output, integer ( kind = 4 ) DIGIT, the corresponding value.
!    If C was 'illegal', then DIGIT is -1.
!
  implicit none

  character c
  integer ( kind = 4 ) digit

  if ( lge ( c, '0' ) .and. lle ( c, '9' ) ) then

    digit = ichar ( c ) - 48

  else if ( c == ' ' ) then

    digit = 0

  else

    digit = -1

  end if

  return
end
subroutine class_matrix ( kind, m, alpha, beta, aj, bj, zemu )

!*****************************************************************************80
!
!! CLASS_MATRIX computes the Jacobi matrix for a quadrature rule.
!
!  Discussion:
!
!    This routine computes the diagonal AJ and sub-diagonal BJ
!    elements of the order M tridiagonal symmetric Jacobi matrix
!    associated with the polynomials orthogonal with respect to
!    the weight function specified by KIND.
!
!    For weight functions 1-7, M elements are defined in BJ even
!    though only M-1 are needed.  For weight function 8, BJ(M) is
!    set to zero.
!
!    The zero-th moment of the weight function is returned in ZEMU.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    27 December 2009
!
!  Author:
!
!    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    Sylvan Elhay, Jaroslav Kautsky,
!    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
!    Interpolatory Quadrature,
!    ACM Transactions on Mathematical Software,
!    Volume 13, Number 4, December 1987, pages 399-415.
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) KIND, the rule.
!    1, Legendre,             (a,b)       1.0
!    2, Chebyshev,            (a,b)       ((b-x)*(x-a))^(-0.5)
!    3, Gegenbauer,           (a,b)       ((b-x)*(x-a))^alpha
!    4, Jacobi,               (a,b)       (b-x)^alpha*(x-a)^beta
!    5, Generalized Laguerre, (a,inf)     (x-a)^alpha*exp(-b*(x-a))
!    6, Generalized Hermite,  (-inf,inf)  |x-a|^alpha*exp(-b*(x-a)^2)
!    7, Exponential,          (a,b)       |x-(a+b)/2.0|^alpha
!    8, Rational,             (a,inf)     (x-a)^alpha*(x+b)^beta
!
!    Input, integer ( kind = 4 ) M, the order of the Jacobi matrix.
!
!    Input, real ( kind = 8 ) ALPHA, the value of Alpha, if needed.
!
!    Input, real ( kind = 8 ) BETA, the value of Beta, if needed.
!
!    Output, real ( kind = 8 ) AJ(M), BJ(M), the diagonal and subdiagonal
!    of the Jacobi matrix.
!
!    Output, real ( kind = 8 ) ZEMU, the zero-th moment.
!
  implicit none

  integer ( kind = 4 ) m

  real ( kind = 8 ) a2b2
  real ( kind = 8 ) ab
  real ( kind = 8 ) aba
  real ( kind = 8 ) abi
  real ( kind = 8 ) abj
  real ( kind = 8 ) abti
  real ( kind = 8 ) aj(m)
  real ( kind = 8 ) alpha
  real ( kind = 8 ) apone
  real ( kind = 8 ) beta
  real ( kind = 8 ) bj(m)
  integer ( kind = 4 ) i
  integer ( kind = 4 ) kind
  real ( kind = 8 ), parameter :: pi = 3.14159265358979323846264338327950D+00
  real ( kind = 8 ) r8_gamma
  real ( kind = 8 ) temp
  real ( kind = 8 ) temp2
  real ( kind = 8 ) zemu

  temp = epsilon ( temp )

  call parchk ( kind, 2 * m - 1, alpha, beta )

  temp2 = 0.5D+00

  if ( 500.0D+00 * temp < abs ( ( r8_gamma ( temp2 ) )**2 - pi ) ) then
    write ( *, '(a)' ) ' '
    write ( *, '(a)' ) 'CLASS_MATRIX - Fatal error!'
    write ( *, '(a)' ) '  Gamma function does not match machine parameters.'
    stop
  end if

  if ( kind == 1 ) then

    ab = 0.0D+00

    zemu = 2.0D+00 / ( ab + 1.0D+00 )

    aj(1:m) = 0.0D+00

    do i = 1, m
      abi = i + ab * mod ( i, 2 )
      abj = 2 * i + ab
      bj(i) = abi * abi / ( abj * abj - 1.0D+00 )
    end do
    bj(1:m) =  sqrt ( bj(1:m) )

  else if ( kind == 2 ) then

    zemu = pi

    aj(1:m) = 0.0D+00

    bj(1) =  sqrt ( 0.5D+00 )
    bj(2:m) = 0.5D+00

  else if ( kind == 3 ) then

    ab = alpha * 2.0D+00
    zemu = 2.0D+00**( ab + 1.0D+00 ) * r8_gamma ( alpha + 1.0D+00 )**2 &
      / r8_gamma ( ab + 2.0D+00 )

    aj(1:m) = 0.0D+00
    bj(1) = 1.0D+00 / ( 2.0D+00 * alpha + 3.0D+00 )
    do i = 2, m
      bj(i) = i * ( i + ab ) / ( 4.0D+00 * ( i + alpha )**2 - 1.0D+00 )
    end do
    bj(1:m) =  sqrt ( bj(1:m) )

  else if ( kind == 4 ) then

    ab = alpha + beta
    abi = 2.0D+00 + ab
    zemu = 2.0D+00**( ab + 1.0D+00 ) * r8_gamma ( alpha + 1.0D+00 ) &
      * r8_gamma ( beta + 1.0D+00 ) / r8_gamma ( abi )
    aj(1) = ( beta - alpha ) / abi
    bj(1) = 4.0D+00 * ( 1.0 + alpha ) * ( 1.0D+00 + beta ) &
      / ( ( abi + 1.0D+00 ) * abi * abi )
    a2b2 = beta * beta - alpha * alpha

    do i = 2, m
      abi = 2.0D+00 * i + ab
      aj(i) = a2b2 / ( ( abi - 2.0D+00 ) * abi )
      abi = abi**2
      bj(i) = 4.0D+00 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) &
        / ( ( abi - 1.0D+00 ) * abi )
    end do
    bj(1:m) =  sqrt ( bj(1:m) )

  else if ( kind == 5 ) then

    zemu = r8_gamma ( alpha + 1.0D+00 )

    do i = 1, m
      aj(i) = 2.0D+00 * i - 1.0D+00 + alpha
      bj(i) = i * ( i + alpha )
    end do
    bj(1:m) =  sqrt ( bj(1:m) )

  else if ( kind == 6 ) then

    zemu = r8_gamma ( ( alpha + 1.0D+00 ) / 2.0D+00 )

    aj(1:m) = 0.0D+00

    do i = 1, m
      bj(i) = ( i + alpha * mod ( i, 2 ) ) / 2.0D+00
    end do
    bj(1:m) =  sqrt ( bj(1:m) )

  else if ( kind == 7 ) then

    ab = alpha
    zemu = 2.0D+00 / ( ab + 1.0D+00 )

    aj(1:m) = 0.0D+00

    do i = 1, m
      abi = i + ab * mod ( i, 2 )
      abj = 2 * i + ab
      bj(i) = abi * abi / ( abj * abj - 1.0D+00 )
    end do
    bj(1:m) =  sqrt ( bj(1:m) )

  else if ( kind == 8 ) then

    ab = alpha + beta
    zemu = r8_gamma ( alpha + 1.0D+00 ) * r8_gamma ( - ( ab + 1.0D+00 ) ) &
      / r8_gamma ( - beta )
    apone = alpha + 1.0D+00
    aba = ab * apone
    aj(1) = - apone / ( ab + 2.0D+00 )
    bj(1) = - aj(1) * ( beta + 1.0D+00 ) / ( ab + 2.0D+00 ) / ( ab + 3.0D+00 )
    do i = 2, m
      abti = ab + 2.0D+00 * i
      aj(i) = aba + 2.0D+00 * ( ab + i ) * ( i - 1 )
      aj(i) = - aj(i) / abti / ( abti - 2.0D+00 )
    end do

    do i = 2, m - 1
      abti = ab + 2.0D+00 * i
      bj(i) = i * ( alpha + i ) / ( abti - 1.0D+00 ) * ( beta + i ) &
        / ( abti**2 ) * ( ab + i ) / ( abti + 1.0D+00 )
    end do

    bj(m) = 0.0D+00
    bj(1:m) =  sqrt ( bj(1:m) )

  end if

  return
end
subroutine get_unit ( iunit )

!*****************************************************************************80
!
!! GET_UNIT returns a free FORTRAN unit number.
!
!  Discussion:
!
!    A "free" FORTRAN unit number is an integer between 1 and 99 which
!    is not currently associated with an I/O device.  A free FORTRAN unit
!    number is needed in order to open a file with the OPEN command.
!
!    If IUNIT = 0, then no free FORTRAN unit could be found, although
!    all 99 units were checked (except for units 5, 6 and 9, which
!    are commonly reserved for console I/O).
!
!    Otherwise, IUNIT is an integer between 1 and 99, representing a
!    free FORTRAN unit.  Note that GET_UNIT assumes that units 5 and 6
!    are special, and will never return those values.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    18 September 2005
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Output, integer ( kind = 4 ) IUNIT, the free unit number.
!
  implicit none

  integer ( kind = 4 ) i
  integer ( kind = 4 ) ios
  integer ( kind = 4 ) iunit
  logical lopen

  iunit = 0

  do i = 1, 99

    if ( i /= 5 .and. i /= 6 .and. i /= 9 ) then

      inquire ( unit = i, opened = lopen, iostat = ios )

      if ( ios == 0 ) then
        if ( .not. lopen ) then
          iunit = i
          return
        end if
      end if

    end if

  end do

  return
end
subroutine imtqlx ( n, d, e, z )

!*****************************************************************************80
!
!! IMTQLX diagonalizes a symmetric tridiagonal matrix.
!
!  Discussion:
!
!    This routine is a slightly modified version of the EISPACK routine to
!    perform the implicit QL algorithm on a symmetric tridiagonal matrix.
!
!    The authors thank the authors of EISPACK for permission to use this
!    routine.
!
!    It has been modified to produce the product Q' * Z, where Z is an input
!    vector and Q is the orthogonal matrix diagonalizing the input matrix.
!    The changes consist (essentially) of applying the orthogonal
!    transformations directly to Z as they are generated.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    27 December 2009
!
!  Author:
!
!    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    Sylvan Elhay, Jaroslav Kautsky,
!    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
!    Interpolatory Quadrature,
!    ACM Transactions on Mathematical Software,
!    Volume 13, Number 4, December 1987, pages 399-415.
!
!    Roger Martin, James Wilkinson,
!    The Implicit QL Algorithm,
!    Numerische Mathematik,
!    Volume 12, Number 5, December 1968, pages 377-383.
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) N, the order of the matrix.
!
!    Input/output, real ( kind = 8 ) D(N), the diagonal entries of the matrix.
!    On output, the information in D has been overwritten.
!
!    Input/output, real ( kind = 8 ) E(N), the subdiagonal entries of the
!    matrix, in entries E(1) through E(N-1).  On output, the information in
!    E has been overwritten.
!
!    Input/output, real ( kind = 8 ) Z(N).  On input, a vector.  On output,
!    the value of Q' * Z, where Q is the matrix that diagonalizes the
!    input symmetric tridiagonal matrix.
!
  implicit none

  integer ( kind = 4 ) n

  real ( kind = 8 ) b
  real ( kind = 8 ) c
  real ( kind = 8 ) d(n)
  real ( kind = 8 ) e(n)
  real ( kind = 8 ) f
  real ( kind = 8 ) g
  integer ( kind = 4 ) i
  integer ( kind = 4 ) ii
  integer ( kind = 4 ), parameter :: itn = 30
  integer ( kind = 4 ) j
  integer ( kind = 4 ) k
  integer ( kind = 4 ) l
  integer ( kind = 4 ) m
  integer ( kind = 4 ) mml
  real ( kind = 8 ) p
  real ( kind = 8 ) prec
  real ( kind = 8 ) r
  real ( kind = 8 ) s
  real ( kind = 8 ) z(n)

  prec = epsilon ( prec )

  if ( n == 1 ) then
    return
  end if

  e(n) = 0.0D+00

  do l = 1, n

    j = 0

    do

      do m = l, n

        if ( m == n ) then
          exit
        end if

        if ( abs ( e(m) ) <= prec * ( abs ( d(m) ) + abs ( d(m+1) ) ) ) then
          exit
        end if

      end do

      p = d(l)

      if ( m == l ) then
        exit
      end if

      if ( itn <= j ) then
        write ( *, '(a)' ) ' '
        write ( *, '(a)' ) 'IMTQLX - Fatal error!'
        write ( *, '(a)' ) '  Iteration limit exceeded.'
        write ( *, '(a,i8)' ) '  J = ', j
        write ( *, '(a,i8)' ) '  L = ', l
        write ( *, '(a,i8)' ) '  M = ', m
        write ( *, '(a,i8)' ) '  N = ', n
        stop
      end if

      j = j + 1
      g = ( d(l+1) - p ) / ( 2.0D+00 * e(l) )
      r =  sqrt ( g * g + 1.0D+00 )
      g = d(m) - p + e(l) / ( g + sign ( r, g ) )
      s = 1.0D+00
      c = 1.0D+00
      p = 0.0D+00
      mml = m - l

      do ii = 1, mml

        i = m - ii
        f = s * e(i)
        b = c * e(i)

        if ( abs ( g ) <= abs ( f ) ) then
          c = g / f
          r =  sqrt ( c * c + 1.0D+00 )
          e(i+1) = f * r
          s = 1.0D+00 / r
          c = c * s
        else
          s = f / g
          r =  sqrt ( s * s + 1.0D+00 )
          e(i+1) = g * r
          c = 1.0D+00 / r
          s = s * c
        end if

        g = d(i+1) - p
        r = ( d(i) - g ) * s + 2.0D+00 * c * b
        p = s * r
        d(i+1) = g + p
        g = c * r - b
        f = z(i+1)
        z(i+1) = s * z(i) + c * f
        z(i) = c * z(i) - s * f

      end do

      d(l) = d(l) - p
      e(l) = g
      e(m) = 0.0D+00

    end do

  end do
!
!  Sorting.
!
  do ii = 2, n

    i = ii - 1
    k = i
    p = d(i)

    do j = ii, n
      if ( d(j) < p ) then
        k = j
        p = d(j)
      end if
    end do

    if ( k /= i ) then
      d(k) = d(i)
      d(i) = p
      p = z(i)
      z(i) = z(k)
      z(k) = p
    end if

  end do

  return
end
subroutine parchk ( kind, m, alpha, beta )

!*****************************************************************************80
!
!! PARCHK checks parameters ALPHA and BETA for classical weight functions.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    27 December 2009
!
!  Author:
!
!    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    Sylvan Elhay, Jaroslav Kautsky,
!    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
!    Interpolatory Quadrature,
!    ACM Transactions on Mathematical Software,
!    Volume 13, Number 4, December 1987, pages 399-415.
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) KIND, the rule.
!    1, Legendre,             (a,b)       1.0
!    2, Chebyshev,            (a,b)       ((b-x)*(x-a))^(-0.5)
!    3, Gegenbauer,           (a,b)       ((b-x)*(x-a))^alpha
!    4, Jacobi,               (a,b)       (b-x)^alpha*(x-a)^beta
!    5, Generalized Laguerre, (a,inf)     (x-a)^alpha*exp(-b*(x-a))
!    6, Generalized Hermite,  (-inf,inf)  |x-a|^alpha*exp(-b*(x-a)^2)
!    7, Exponential,          (a,b)       |x-(a+b)/2.0|^alpha
!    8, Rational,             (a,inf)     (x-a)^alpha*(x+b)^beta
!
!    Input, integer ( kind = 4 ) M, the order of the highest moment to
!    be calculated.  This value is only needed when KIND = 8.
!
!    Input, real ( kind = 8 ) ALPHA, BETA, the parameters, if required
!    by the value of KIND.
!
  implicit none

  real ( kind = 8 ) alpha
  real ( kind = 8 ) beta
  integer ( kind = 4 ) kind
  integer ( kind = 4 ) m
  real ( kind = 8 ) tmp

  if ( kind <= 0 ) then
    write ( *, '(a)' ) ' '
    write ( *, '(a)' ) 'PARCHK - Fatal error!'
    write ( *, '(a)' ) '  KIND <= 0.'
    stop
  end if
!
!  Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential.
!
  if ( 3 <= kind .and. alpha <= -1.0D+00 ) then
    write ( *, '(a)' ) ' '
    write ( *, '(a)' ) 'PARCHK - Fatal error!'
    write ( *, '(a)' ) '  3 <= KIND and ALPHA <= -1.'
    stop
  end if
!
!  Check BETA for Jacobi.
!
  if ( kind == 4 .and. beta <= -1.0D+00 ) then
    write ( *, '(a)' ) ' '
    write ( *, '(a)' ) 'PARCHK - Fatal error!'
    write ( *, '(a)' ) '  KIND == 4 and BETA <= -1.0.'
    stop
  end if
!
!  Check ALPHA and BETA for rational.
!
  if ( kind == 8 ) then
    tmp = alpha + beta + m + 1.0D+00
    if ( 0.0D+00 <= tmp .or. tmp <= beta ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'PARCHK - Fatal error!'
      write ( *, '(a)' ) '  KIND == 8 but condition on ALPHA and BETA fails.'
      stop
    end if
  end if

  return
end
function r8_epsilon ( )

!*****************************************************************************80
!
!! R8_EPSILON returns the R8 roundoff unit.
!
!  Discussion:
!
!    The roundoff unit is a number R which is a power of 2 with the
!    property that, to the precision of the computer's arithmetic,
!      1 < 1 + R
!    but
!      1 = ( 1 + R / 2 )
!
!    FORTRAN90 provides the superior library routine
!
!      EPSILON ( X )
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    01 September 2012
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Output, real ( kind = 8 ) R8_EPSILON, the round-off unit.
!
  implicit none

  real ( kind = 8 ) r8_epsilon

  r8_epsilon = 2.220446049250313D-016

  return
end
function r8_gamma ( x )

!*****************************************************************************80
!
!! R8_GAMMA evaluates Gamma(X) for a real argument.
!
!  Discussion:
!
!    This routine calculates the gamma function for a real argument X.
!
!    Computation is based on an algorithm outlined in reference 1.
!    The program uses rational functions that approximate the gamma
!    function to at least 20 significant decimal digits.  Coefficients
!    for the approximation over the interval (1,2) are unpublished.
!    Those for the approximation for 12 <= X are from reference 2.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    11 February 2008
!
!  Author:
!
!    Original FORTRAN77 version by William Cody, Laura Stoltz.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    William Cody,
!    An Overview of Software Development for Special Functions,
!    in Numerical Analysis Dundee, 1975,
!    edited by GA Watson,
!    Lecture Notes in Mathematics 506,
!    Springer, 1976.
!
!    John Hart, Ward Cheney, Charles Lawson, Hans Maehly,
!    Charles Mesztenyi, John Rice, Henry Thatcher,
!    Christoph Witzgall,
!    Computer Approximations,
!    Wiley, 1968,
!    LC: QA297.C64.
!
!  Parameters:
!
!    Input, real ( kind = 8 ) X, the argument of the function.
!
!    Output, real ( kind = 8 ) R8_GAMMA, the value of the function.
!
  implicit none

  real ( kind = 8 ), dimension ( 7 ) :: c = (/ &
   -1.910444077728D-03, &
    8.4171387781295D-04, &
   -5.952379913043012D-04, &
    7.93650793500350248D-04, &
   -2.777777777777681622553D-03, &
    8.333333333333333331554247D-02, &
    5.7083835261D-03 /)
  real ( kind = 8 ), parameter :: eps = 2.22D-16
  real ( kind = 8 ) fact
  integer ( kind = 4 ) i
  integer ( kind = 4 ) n
  real ( kind = 8 ), dimension ( 8 ) :: p = (/ &
    -1.71618513886549492533811D+00, &
     2.47656508055759199108314D+01, &
    -3.79804256470945635097577D+02, &
     6.29331155312818442661052D+02, &
     8.66966202790413211295064D+02, &
    -3.14512729688483675254357D+04, &
    -3.61444134186911729807069D+04, &
     6.64561438202405440627855D+04 /)
  logical parity
  real ( kind = 8 ), parameter :: pi = 3.1415926535897932384626434D+00
  real ( kind = 8 ), dimension ( 8 ) :: q = (/ &
    -3.08402300119738975254353D+01, &
     3.15350626979604161529144D+02, &
    -1.01515636749021914166146D+03, &
    -3.10777167157231109440444D+03, &
     2.25381184209801510330112D+04, &
     4.75584627752788110767815D+03, &
    -1.34659959864969306392456D+05, &
    -1.15132259675553483497211D+05 /)
  real ( kind = 8 ) r8_gamma
  real ( kind = 8 ) res
  real ( kind = 8 ), parameter :: sqrtpi = 0.9189385332046727417803297D+00
  real ( kind = 8 ) sum
  real ( kind = 8 ) x
  real ( kind = 8 ), parameter :: xbig = 171.624D+00
  real ( kind = 8 ) xden
  real ( kind = 8 ), parameter :: xinf = 1.0D+30
  real ( kind = 8 ), parameter :: xminin = 2.23D-308
  real ( kind = 8 ) xnum
  real ( kind = 8 ) y
  real ( kind = 8 ) y1
  real ( kind = 8 ) ysq
  real ( kind = 8 ) z

  parity = .false.
  fact = 1.0D+00
  n = 0
  y = x
!
!  Argument is negative.
!
  if ( y <= 0.0D+00 ) then

    y = - x
    y1 = aint ( y )
    res = y - y1

    if ( res /= 0.0D+00 ) then

      if ( y1 /= aint ( y1 * 0.5D+00 ) * 2.0D+00 ) then
        parity = .true.
      end if

      fact = - pi / sin ( pi * res )
      y = y + 1.0D+00

    else

      res = xinf
      r8_gamma = res
      return

    end if

  end if
!
!  Argument is positive.
!
  if ( y < eps ) then
!
!  Argument < EPS.
!
    if ( xminin <= y ) then
      res = 1.0D+00 / y
    else
      res = xinf
      r8_gamma = res
      return
    end if

  else if ( y < 12.0D+00 ) then

    y1 = y
!
!  0.0 < argument < 1.0.
!
    if ( y < 1.0D+00 ) then

      z = y
      y = y + 1.0D+00
!
!  1.0 < argument < 12.0.
!  Reduce argument if necessary.
!
    else

      n = int ( y ) - 1
      y = y - real ( n, kind = 8 )
      z = y - 1.0D+00

    end if
!
!  Evaluate approximation for 1.0 < argument < 2.0.
!
    xnum = 0.0D+00
    xden = 1.0D+00
    do i = 1, 8
      xnum = ( xnum + p(i) ) * z
      xden = xden * z + q(i)
    end do

    res = xnum / xden + 1.0D+00
!
!  Adjust result for case  0.0 < argument < 1.0.
!
    if ( y1 < y ) then

      res = res / y1
!
!  Adjust result for case 2.0 < argument < 12.0.
!
    else if ( y < y1 ) then

      do i = 1, n
        res = res * y
        y = y + 1.0D+00
      end do

    end if

  else
!
!  Evaluate for 12.0 <= argument.
!
    if ( y <= xbig ) then

      ysq = y * y
      sum = c(7)
      do i = 1, 6
        sum = sum / ysq + c(i)
      end do
      sum = sum / y - y + sqrtpi
      sum = sum + ( y - 0.5D+00 ) * log ( y )
      res = exp ( sum )

    else

      res = xinf
      r8_gamma = res
      return

    end if

  end if
!
!  Final adjustments and return.
!
  if ( parity ) then
    res = - res
  end if

  if ( fact /= 1.0D+00 ) then
    res = fact / res
  end if

  r8_gamma = res

  return
end
subroutine r8mat_write ( output_filename, m, n, table )

!*****************************************************************************80
!
!! R8MAT_WRITE writes an R8MAT file.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    31 May 2009
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Input, character ( len = * ) OUTPUT_FILENAME, the output file name.
!
!    Input, integer ( kind = 4 ) M, the spatial dimension.
!
!    Input, integer ( kind = 4 ) N, the number of points.
!
!    Input, real ( kind = 8 ) TABLE(M,N), the table data.
!
  implicit none

  integer ( kind = 4 ) m
  integer ( kind = 4 ) n

  integer ( kind = 4 ) j
  character ( len = * )  output_filename
  integer ( kind = 4 ) output_status
  integer ( kind = 4 ) output_unit
  character ( len = 30 ) string
  real ( kind = 8 ) table(m,n)
!
!  Open the file.
!
  call get_unit ( output_unit )

  open ( unit = output_unit, file = output_filename, &
    status = 'replace', iostat = output_status )

  if ( output_status /= 0 ) then
    write ( *, '(a)' ) ' '
    write ( *, '(a)' ) 'R8MAT_WRITE - Fatal error!'
    write ( *, '(a,i8)' ) '  Could not open the output file "' // &
      trim ( output_filename ) // '" on unit ', output_unit
    output_unit = -1
    stop
  end if
!
!  Create a format string.
!
!  For less precision in the output file, try:
!
!                                            '(', m, 'g', 14, '.', 6, ')'
!
  if ( 0 < m .and. 0 < n ) then

    write ( string, '(a1,i8,a1,i8,a1,i8,a1)' ) '(', m, 'g', 24, '.', 16, ')'
!
!  Write the data.
!
    do j = 1, n
      write ( output_unit, string ) table(1:m,j)
    end do

  end if
!
!  Close the file.
!
  close ( unit = output_unit )

  return
end
subroutine rule_write ( order, x, w, r, filename )

!*****************************************************************************80
!
!! RULE_WRITE writes a quadrature rule to a file.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    18 February 2010
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) ORDER, the order of the rule.
!
!    Input, real ( kind = 8 ) X(ORDER), the abscissas.
!
!    Input, real ( kind = 8 ) W(ORDER), the weights.
!
!    Input, real ( kind = 8 ) R(2), defines the region.
!
!    Input, character ( len = * ) FILENAME, specifies the output.
!    'filename_w.txt', 'filename_x.txt', 'filename_r.txt' defining weights,
!    abscissas, and region.
!
  implicit none

  integer ( kind = 4 ) order

  character ( len = * ) filename
  character ( len = 255 ) filename_r
  character ( len = 255 ) filename_w
  character ( len = 255 ) filename_x
  real ( kind = 8 ) r(2)
  real ( kind = 8 ) w(order)
  real ( kind = 8 ) x(order)

  filename_w = trim ( filename ) // '_w.txt'
  filename_x = trim ( filename ) // '_x.txt'
  filename_r = trim ( filename ) // '_r.txt'

  write ( *, '(a)' ) ' '
  write ( *, '(a)' ) '  Creating quadrature files.'
  write ( *, '(a)' ) ' '
  write ( *, '(a)' ) '  "Root" file name is   "' // trim ( filename ) // '".'
  write ( *, '(a)' ) ' '
  write ( *, '(a)' ) '  Weight file will be   "' // trim ( filename_w ) // '".'
  write ( *, '(a)' ) '  Abscissa file will be "' // trim ( filename_x ) // '".'
  write ( *, '(a)' ) '  Region file will be   "' // trim ( filename_r ) // '".'

  call r8mat_write ( filename_w, 1, order, w )
  call r8mat_write ( filename_x, 1, order, x )
  call r8mat_write ( filename_r, 1, 2,     r )

  return
end
subroutine s_to_i4 ( s, ival, ierror, length )

!*****************************************************************************80
!
!! S_TO_I4 reads an I4 from a string.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    28 June 2000
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Input, character ( len = * ) S, a string to be examined.
!
!    Output, integer ( kind = 4 ) IVAL, the integer value read from the string.
!    If the string is blank, then IVAL will be returned 0.
!
!    Output, integer ( kind = 4 ) IERROR, an error flag.
!    0, no error.
!    1, an error occurred.
!
!    Output, integer ( kind = 4 ) LENGTH, the number of characters of S
!    used to make IVAL.
!
  implicit none

  character c
  integer ( kind = 4 ) i
  integer ( kind = 4 ) ierror
  integer ( kind = 4 ) isgn
  integer ( kind = 4 ) istate
  integer ( kind = 4 ) ival
  integer ( kind = 4 ) length
  character ( len = * ) s

  ierror = 0
  istate = 0
  isgn = 1
  ival = 0

  do i = 1, len_trim ( s )

    c = s(i:i)
!
!  Haven't read anything.
!
    if ( istate == 0 ) then

      if ( c == ' ' ) then

      else if ( c == '-' ) then
        istate = 1
        isgn = -1
      else if ( c == '+' ) then
        istate = 1
        isgn = + 1
      else if ( lle ( '0', c ) .and. lle ( c, '9' ) ) then
        istate = 2
        ival = ichar ( c ) - ichar ( '0' )
      else
        ierror = 1
        return
      end if
!
!  Have read the sign, expecting digits.
!
    else if ( istate == 1 ) then

      if ( c == ' ' ) then

      else if ( lle ( '0', c ) .and. lle ( c, '9' ) ) then
        istate = 2
        ival = ichar ( c ) - ichar ( '0' )
      else
        ierror = 1
        return
      end if
!
!  Have read at least one digit, expecting more.
!
    else if ( istate == 2 ) then

      if ( lle ( '0', c ) .and. lle ( c, '9' ) ) then
        ival = 10 * ival + ichar ( c ) - ichar ( '0' )
      else
        ival = isgn * ival
        length = i - 1
        return
      end if

    end if

  end do
!
!  If we read all the characters in the string, see if we're OK.
!
  if ( istate == 2 ) then
    ival = isgn * ival
    length = len_trim ( s )
  else
    ierror = 1
    length = 0
  end if

  return
end
subroutine s_to_r8 ( s, dval, ierror, length )

!*****************************************************************************80
!
!! S_TO_R8 reads an R8 from a string.
!
!  Discussion:
!
!    The routine will read as many characters as possible until it reaches
!    the end of the string, or encounters a character which cannot be
!    part of the number.
!
!    Legal input is:
!
!       1 blanks,
!       2 '+' or '-' sign,
!       2.5 blanks
!       3 integer part,
!       4 decimal point,
!       5 fraction part,
!       6 'E' or 'e' or 'D' or 'd', exponent marker,
!       7 exponent sign,
!       8 exponent integer part,
!       9 exponent decimal point,
!      10 exponent fraction part,
!      11 blanks,
!      12 final comma or semicolon,
!
!    with most quantities optional.
!
!  Example:
!
!    S                 DVAL
!
!    '1'               1.0
!    '     1   '       1.0
!    '1A'              1.0
!    '12,34,56'        12.0
!    '  34 7'          34.0
!    '-1E2ABCD'        -100.0
!    '-1X2ABCD'        -1.0
!    ' 2E-1'           0.2
!    '23.45'           23.45
!    '-4.2E+2'         -420.0
!    '17d2'            1700.0
!    '-14e-2'         -0.14
!    'e2'              100.0
!    '-12.73e-9.23'   -12.73 * 10.0^(-9.23)
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    07 September 2004
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    Input, character ( len = * ) S, the string containing the
!    data to be read.  Reading will begin at position 1 and
!    terminate at the end of the string, or when no more
!    characters can be read to form a legal real.  Blanks,
!    commas, or other nonnumeric data will, in particular,
!    cause the conversion to halt.
!
!    Output, real ( kind = 8 ) DVAL, the value read from the string.
!
!    Output, integer ( kind = 4 ) IERROR, error flag.
!    0, no errors occurred.
!    1, 2, 6 or 7, the input number was garbled.  The
!    value of IERROR is the last type of input successfully
!    read.  For instance, 1 means initial blanks, 2 means
!    a plus or minus sign, and so on.
!
!    Output, integer ( kind = 4 ) LENGTH, the number of characters read
!    to form the number, including any terminating
!    characters such as a trailing comma or blanks.
!
  implicit none

  character c
  logical ch_eqi
  real ( kind = 8 ) dval
  integer ( kind = 4 ) ierror
  integer ( kind = 4 ) ihave
  integer ( kind = 4 ) isgn
  integer ( kind = 4 ) iterm
  integer ( kind = 4 ) jbot
  integer ( kind = 4 ) jsgn
  integer ( kind = 4 ) jtop
  integer ( kind = 4 ) length
  integer ( kind = 4 ) nchar
  integer ( kind = 4 ) ndig
  real ( kind = 8 ) rbot
  real ( kind = 8 ) rexp
  real ( kind = 8 ) rtop
  character ( len = * ) s

  nchar = len_trim ( s )

  ierror = 0
  dval = 0.0D+00
  length = -1
  isgn = 1
  rtop = 0
  rbot = 1
  jsgn = 1
  jtop = 0
  jbot = 1
  ihave = 1
  iterm = 0

  do

    length = length + 1

    if ( nchar < length+1 ) then
      exit
    end if

    c = s(length+1:length+1)
!
!  Blank character.
!
    if ( c == ' ' ) then

      if ( ihave == 2 ) then

      else if ( ihave == 6 .or. ihave == 7 ) then
        iterm = 1
      else if ( 1 < ihave ) then
        ihave = 11
      end if
!
!  Comma.
!
    else if ( c == ',' .or. c == ';' ) then

      if ( ihave /= 1 ) then
        iterm = 1
        ihave = 12
        length = length + 1
      end if
!
!  Minus sign.
!
    else if ( c == '-' ) then

      if ( ihave == 1 ) then
        ihave = 2
        isgn = -1
      else if ( ihave == 6 ) then
        ihave = 7
        jsgn = -1
      else
        iterm = 1
      end if
!
!  Plus sign.
!
    else if ( c == '+' ) then

      if ( ihave == 1 ) then
        ihave = 2
      else if ( ihave == 6 ) then
        ihave = 7
      else
        iterm = 1
      end if
!
!  Decimal point.
!
    else if ( c == '.' ) then

      if ( ihave < 4 ) then
        ihave = 4
      else if ( 6 <= ihave .and. ihave <= 8 ) then
        ihave = 9
      else
        iterm = 1
      end if
!
!  Scientific notation exponent marker.
!
    else if ( ch_eqi ( c, 'E' ) .or. ch_eqi ( c, 'D' ) ) then

      if ( ihave < 6 ) then
        ihave = 6
      else
        iterm = 1
      end if
!
!  Digit.
!
    else if (  ihave < 11 .and. lle ( '0', c ) .and. lle ( c, '9' ) ) then

      if ( ihave <= 2 ) then
        ihave = 3
      else if ( ihave == 4 ) then
        ihave = 5
      else if ( ihave == 6 .or. ihave == 7 ) then
        ihave = 8
      else if ( ihave == 9 ) then
        ihave = 10
      end if

      call ch_to_digit ( c, ndig )

      if ( ihave == 3 ) then
        rtop = 10.0D+00 * rtop + real ( ndig, kind = 8 )
      else if ( ihave == 5 ) then
        rtop = 10.0D+00 * rtop + real ( ndig, kind = 8 )
        rbot = 10.0D+00 * rbot
      else if ( ihave == 8 ) then
        jtop = 10 * jtop + ndig
      else if ( ihave == 10 ) then
        jtop = 10 * jtop + ndig
        jbot = 10 * jbot
      end if
!
!  Anything else is regarded as a terminator.
!
    else
      iterm = 1
    end if
!
!  If we haven't seen a terminator, and we haven't examined the
!  entire string, go get the next character.
!
    if ( iterm == 1 ) then
      exit
    end if

  end do
!
!  If we haven't seen a terminator, and we have examined the
!  entire string, then we're done, and LENGTH is equal to NCHAR.
!
  if ( iterm /= 1 .and. length+1 == nchar ) then
    length = nchar
  end if
!
!  Number seems to have terminated.  Have we got a legal number?
!  Not if we terminated in states 1, 2, 6 or 7!
!
  if ( ihave == 1 .or. ihave == 2 .or. ihave == 6 .or. ihave == 7 ) then
    ierror = ihave
    write ( *, '(a)' ) ' '
    write ( *, '(a)' ) 'S_TO_R8 - Serious error!'
    write ( *, '(a)' ) '  Illegal or nonnumeric input:'
    write ( *, '(a)' ) '    ' // trim ( s )
    return
  end if
!
!  Number seems OK.  Form it.
!
  if ( jtop == 0 ) then
    rexp = 1.0D+00
  else
    if ( jbot == 1 ) then
      rexp = 10.0D+00 ** ( jsgn * jtop )
    else
      rexp = 10.0D+00 ** ( real ( jsgn * jtop, kind = 8 ) &
        / real ( jbot, kind = 8 ) )
    end if
  end if

  dval = real ( isgn, kind = 8 ) * rexp * rtop / rbot

  return
end
subroutine scqf ( nt, t, mlt, wts, nwts, ndx, swts, st, kind, alpha, beta, a, &
  b )

!*****************************************************************************80
!
!! SCQF scales a quadrature formula to a nonstandard interval.
!
!  Discussion:
!
!    The arrays WTS and SWTS may coincide.
!
!    The arrays T and ST may coincide.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    27 December 2009
!
!  Author:
!
!    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    Sylvan Elhay, Jaroslav Kautsky,
!    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
!    Interpolatory Quadrature,
!    ACM Transactions on Mathematical Software,
!    Volume 13, Number 4, December 1987, pages 399-415.
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) NT, the number of knots.
!
!    Input, real ( kind = 8 ) T(NT), the original knots.
!
!    Input, integer ( kind = 4 ) MLT(NT), the multiplicity of the knots.
!
!    Input, real ( kind = 8 ) WTS(NWTS), the weights.
!
!    Input, integer ( kind = 4 ) NWTS, the number of weights.
!
!    Input, integer ( kind = 4 ) NDX(NT), used to index the array WTS.
!    For more details see the comments in CAWIQ.
!
!    Output, real ( kind = 8 ) SWTS(NWTS), the scaled weights.
!
!    Output, real ( kind = 8 ) ST(NT), the scaled knots.
!
!    Input, integer ( kind = 4 ) KIND, the rule.
!    1, Legendre,             (a,b)       1.0
!    2, Chebyshev Type 1,     (a,b)       ((b-x)*(x-a))^(-0.5)
!    3, Gegenbauer,           (a,b)       ((b-x)*(x-a))^alpha
!    4, Jacobi,               (a,b)       (b-x)^alpha*(x-a)^beta
!    5, Generalized Laguerre, (a,+oo)     (x-a)^alpha*exp(-b*(x-a))
!    6, Generalized Hermite,  (-oo,+oo)   |x-a|^alpha*exp(-b*(x-a)^2)
!    7, Exponential,          (a,b)       |x-(a+b)/2.0|^alpha
!    8, Rational,             (a,+oo)     (x-a)^alpha*(x+b)^beta
!    9, Chebyshev Type 2,     (a,b)       ((b-x)*(x-a))^(+0.5)
!
!    Input, real ( kind = 8 ) ALPHA, the value of Alpha, if needed.
!
!    Input, real ( kind = 8 ) BETA, the value of Beta, if needed.
!
!    Input, real ( kind = 8 ) A, B, the interval endpoints.
!
  implicit none

  integer ( kind = 4 ) nt
  integer ( kind = 4 ) nwts

  real ( kind = 8 ) a
  real ( kind = 8 ) al
  real ( kind = 8 ) alpha
  real ( kind = 8 ) b
  real ( kind = 8 ) be
  real ( kind = 8 ) beta
  integer ( kind = 4 ) i
  integer ( kind = 4 ) k
  integer ( kind = 4 ) kind
  integer ( kind = 4 ) l
  integer ( kind = 4 ) mlt(nt)
  integer ( kind = 4 ) ndx(nt)
  real ( kind = 8 ) p
  real ( kind = 8 ) shft
  real ( kind = 8 ) slp
  real ( kind = 8 ) st(nt)
  real ( kind = 8 ) swts(nwts)
  real ( kind = 8 ) t(nt)
  real ( kind = 8 ) temp
  real ( kind = 8 ) tmp
  real ( kind = 8 ) wts(nwts)

  temp = epsilon ( temp )

  call parchk ( kind, 1, alpha, beta )

  if ( kind == 1 ) then

    al = 0.0D+00
    be = 0.0D+00

    if ( abs ( b - a ) <= temp ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  |B - A| too small.'
      stop
    end if

    shft = ( a + b ) / 2.0D+00
    slp = ( b - a ) / 2.0D+00

  else if ( kind == 2 ) then

    al = -0.5D+00
    be = -0.5D+00

    if ( abs ( b - a ) <= temp ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  |B - A| too small.'
      stop
    end if

    shft = ( a + b ) / 2.0D+00
    slp = ( b - a ) / 2.0D+00

  else if ( kind == 3 ) then

    al = alpha
    be = alpha

    if ( abs ( b - a ) <= temp ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  |B - A| too small.'
      stop
    end if

    shft = ( a + b ) / 2.0D+00
    slp = ( b - a ) / 2.0D+00

  else if ( kind == 4 ) then

    al = alpha
    be = beta

    if ( abs ( b - a ) <= temp ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  |B - A| too small.'
      stop
    end if

    shft = ( a + b ) / 2.0D+00
    slp = ( b - a ) / 2.0D+00

  else if ( kind == 5 ) then

    if ( b <= 0.0D+00 ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  B <= 0'
      stop
    end if

    shft = a
    slp = 1.0D+00 / b
    al = alpha
    be = 0.0D+00

  else if ( kind == 6 ) then

    if ( b <= 0.0D+00 ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  B <= 0.'
      stop
    end if

    shft = a
    slp = 1.0D+00 / sqrt ( b )
    al = alpha
    be = 0.0D+00

  else if ( kind == 7 ) then

    al = alpha
    be = 0.0D+00

    if ( abs ( b - a ) <= temp ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  |B - A| too small.'
      stop
    end if

    shft = ( a + b ) / 2.0D+00
    slp = ( b - a ) / 2.0D+00

  else if ( kind == 8 ) then

    if ( a + b <= 0.0D+00 ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  A + B <= 0.'
      stop
    end if

    shft = a
    slp = a + b
    al = alpha
    be = beta

  else if ( kind == 9 ) then

    al = 0.5D+00
    be = 0.5D+00

    if ( abs ( b - a ) <= temp ) then
      write ( *, '(a)' ) ' '
      write ( *, '(a)' ) 'SCQF - Fatal error!'
      write ( *, '(a)' ) '  |B - A| too small.'
      stop
    end if

    shft = ( a + b ) / 2.0D+00
    slp = ( b - a ) / 2.0D+00

  end if

  p = slp**( al + be + 1.0D+00 )

  do k = 1, nt

    st(k) = shft + slp * t(k)
    l = abs ( ndx(k) )

    if ( l /= 0 ) then
      tmp = p
      do i = l, l + mlt(k) - 1
        swts(i) = wts(i) * tmp
        tmp = tmp * slp
      end do
    end if

  end do

  return
end
subroutine sgqf ( nt, aj, bj, zemu, t, wts )

!*****************************************************************************80
!
!! SGQF computes knots and weights of a Gauss Quadrature formula.
!
!  Discussion:
!
!    This routine computes all the knots and weights of a Gauss quadrature
!    formula with simple knots from the Jacobi matrix and the zero-th
!    moment of the weight function, using the Golub-Welsch technique.
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    04 January 2010
!
!  Author:
!
!    Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky.
!    FORTRAN90 version by John Burkardt.
!
!  Reference:
!
!    Sylvan Elhay, Jaroslav Kautsky,
!    Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of
!    Interpolatory Quadrature,
!    ACM Transactions on Mathematical Software,
!    Volume 13, Number 4, December 1987, pages 399-415.
!
!  Parameters:
!
!    Input, integer ( kind = 4 ) NT, the number of knots.
!
!    Input, real ( kind = 8 ) AJ(NT), the diagonal of the Jacobi matrix.
!
!    Input/output, real ( kind = 8 ) BJ(NT), the subdiagonal of the Jacobi
!    matrix, in entries 1 through NT-1.  On output, BJ has been overwritten.
!
!    Input, real ( kind = 8 ) ZEMU, the zero-th moment of the weight function.
!
!    Output, real ( kind = 8 ) T(NT), the knots.
!
!    Output, real ( kind = 8 ) WTS(NT), the weights.
!
  implicit none

  integer ( kind = 4 ) nt

  real ( kind = 8 ) aj(nt)
  real ( kind = 8 ) bj(nt)
  real ( kind = 8 ) t(nt)
  real ( kind = 8 ) wts(nt)
  real ( kind = 8 ) zemu
!
!  Exit if the zero-th moment is not positive.
!
  if ( zemu <= 0.0D+00 ) then
    write ( *, '(a)' ) ' '
    write ( *, '(a)' ) 'SGQF - Fatal error!'
    write ( *, '(a)' ) '  ZEMU <= 0.'
    stop
  end if
!
!  Set up vectors for IMTQLX.
!
  t(1:nt) = aj(1:nt)

  wts(1) = sqrt ( zemu )
  wts(2:nt) = 0.0D+00
!
!  Diagonalize the Jacobi matrix.
!
  call imtqlx ( nt, t, bj, wts )

  wts(1:nt) = wts(1:nt)**2

  return
end
subroutine timestamp ( )

!*****************************************************************************80
!
!! TIMESTAMP prints the current YMDHMS date as a time stamp.
!
!  Example:
!
!    31 May 2001   9:45:54.872 AM
!
!  Licensing:
!
!    This code is distributed under the GNU LGPL license.
!
!  Modified:
!
!    18 May 2013
!
!  Author:
!
!    John Burkardt
!
!  Parameters:
!
!    None
!
  implicit none

  character ( len = 8 ) ampm
  integer ( kind = 4 ) d
  integer ( kind = 4 ) h
  integer ( kind = 4 ) m
  integer ( kind = 4 ) mm
  character ( len = 9 ), parameter, dimension(12) :: month = (/ &
    'January  ', 'February ', 'March    ', 'April    ', &
    'May      ', 'June     ', 'July     ', 'August   ', &
    'September', 'October  ', 'November ', 'December ' /)
  integer ( kind = 4 ) n
  integer ( kind = 4 ) s
  integer ( kind = 4 ) values(8)
  integer ( kind = 4 ) y

  call date_and_time ( values = values )

  y = values(1)
  m = values(2)
  d = values(3)
  h = values(5)
  n = values(6)
  s = values(7)
  mm = values(8)

  if ( h < 12 ) then
    ampm = 'AM'
  else if ( h == 12 ) then
    if ( n == 0 .and. s == 0 ) then
      ampm = 'Noon'
    else
      ampm = 'PM'
    end if
  else
    h = h - 12
    if ( h < 12 ) then
      ampm = 'PM'
    else if ( h == 12 ) then
      if ( n == 0 .and. s == 0 ) then
        ampm = 'Midnight'
      else
        ampm = 'AM'
      end if
    end if
  end if

  write ( *, '(i2,1x,a,1x,i4,2x,i2,a1,i2.2,a1,i2.2,a1,i3.3,1x,a)' ) &
    d, trim ( month(m) ), y, h, ':', n, ':', s, '.', mm, trim ( ampm )

  return
end


! $UWHPSC/codes/fortran/roots/testzeroin.f90

program main

    use myfcn
    ! This module holds n, a, and provides function power(x)

    implicit none
    real(kind=8) :: x, x1, x2, y, tol
    real(kind=8), external :: zeroin

    print *, "Test routine for computing n'th root of a"
    print *, "Input a "
    read *, a
    print *, "Input n "
    read *, n
    print *, "Input x1,x2:  interval containing zero"
    read *, x1, x2

    tol = 1.d-10  ! tolerance requested to zeroin

    y = zeroin(x1, x2, power, tol)

    print *, 'Estimated value: ', y
    print *, 'Correct   value: ', a ** (1.d0/n)

end program main


module statistics
    use, intrinsic :: iso_fortran_env, only : dp => REAL64
    implicit none

    private
    type, public :: stats_type
        real(kind=dp) :: data_sum, data_sum2
        integer :: n
    end type stats_type
    public :: init_stats, add_stats, mean_stats, stddev_stats

contains

    subroutine init_stats(stats)
        implicit none
        type(stats_type), intent(inout) :: stats
        stats%data_sum = 0.0_dp
        stats%data_sum2 = 0.0_dp
        stats%n = 0
    end subroutine init_stats

    subroutine add_stats(stats, value)
        implicit none
        type(stats_type), intent(inout) :: stats
        real(kind=dp), intent(in) :: value
        stats%data_sum = stats%data_sum + value
        stats%data_sum2 = stats%data_sum2 + value**2
        stats%n = stats%n + 1
    end subroutine add_stats

    real(kind=dp) function mean_stats(stats)
        implicit none
        type(stats_type), intent(in) :: stats
        mean_stats = stats%data_sum/stats%n
    end function mean_stats

    real(kind=dp) function stddev_stats(stats)
        implicit none
        type(stats_type), intent(in) :: stats
        real(Kind=dp) :: mean_value
        mean_value = mean_stats(stats)
        stddev_stats = sqrt(stats%data_sum2/stats%n - mean_value*mean_value)
    end function stddev_stats

end module statistics


! Module for all the functions and subroutines used
! If functions are inside a module, then other functions and subroutines
! inside the module can access it easily. No "external" referencing
! needed inside a module
! Module name and file name need not be the same. But it is okay to be
! the same. If file name is different, then .o file has the filename
! and .mod has the module name. Use the .mod file's name inside the call
! while use .o file's name for building and execution

module maths1

    contains

    function get_iden(n)

        implicit none
        integer, intent(in) :: n
        integer :: i
        real*8, dimension(n,n) :: get_iden

        get_iden = 0

        do i=1,n
            get_iden(i,i) = 1.0
        end do

    end function get_iden

    function get_ab(a,b,n)

        implicit none
        integer, intent(in) :: n
        integer :: i,j
        real*8, dimension(n,n), intent(in) :: a
        real*8, dimension(n), intent(in) :: b
        real*8, dimension(n,n+1) :: get_ab

        do i=1,n
            do j=1,n+1
                if(j<=n) then
                    get_ab(i,j) = a(i,j)
                else
                    get_ab(i,j) = b(i)
                end if
            end do
        end do

    end function get_ab

    function get_a(n,m)

        implicit none
        integer, intent(in) :: n,m
        integer :: i,j
        real*8, dimension(n,m) :: get_a

        do i = 1,n
            do j = 1,m
                print "('Enter the value of Mat(',i2,',',i2,'):')",i,j
                read *, get_a(i,j)
            end do
        end do

    end function get_a

    function get_b(n)

        implicit none
        integer, intent(in) :: n
        integer :: i
        real*8, dimension(n) :: get_b

        do i = 1,n
            print "('Enter the value of Mat(',i2,'):')",i
            read *, get_b(i)
        end do

    end function get_b

    subroutine print_mat2(a,n,m)

        implicit none
        integer, intent(in) :: n,m
        real*8, dimension(n,m), intent(in) :: a
        integer :: i,j

        do i=1,n
            write(*,'("|")',advance='no')
            do j=1,m
                write(*,'(f8.3,t3)',advance='no') a(i,j)
            end do
            write(*,'("|")')
        end do

    end subroutine

    subroutine print_mat1(b,n)

        implicit none
        integer, intent(in) :: n
        real*8, dimension(n), intent(in) :: b
        integer :: i

        do i=1,n
            write(*,'("|",f8.3," |")',advance='yes') b(i)
        end do

    end subroutine

    subroutine gauss_fwel_bsolve(aib,x,n)

        implicit none
        integer, intent(in) :: n
        real*8, intent(inout), dimension(n,n+1) :: aib
        real*8, dimension(n,1), intent(out) :: x
        integer :: i,j,k
        real*8 :: t1,t2
        real*8 ,dimension(1):: t3

        x = 0

        do i = 1,n-1
            t1 = aib(i,i)
            do j = i+1,n
                t2 = aib(j,i)
                do k = i,n+1
                    aib(j,k) = aib(j,k)- aib(i,k)*t2/t1
                end do
            end do
        end do

        print *,"The Matrix Aib after process:"
        call print_mat2(aib,n,n+1)

        do i=n,1,-1
            t3 = matmul(aib(i,1:n),x) ! This matrix multiplication returns
                                      ! a 1d matrix
            x(i,1) = (aib(i,n+1) - t3(1))/aib(i,i) ! 2D matrix work here
        end do

    end subroutine gauss_fwel_bsolve

    subroutine cram(x,a,b,n)

        implicit none
        integer, intent(in) :: n
        real*8, dimension(n,n,n+1), intent(inout) :: a
        real*8, intent(in), dimension(n) :: b
        real*8 :: det_a
        integer :: i
        real*8, dimension(n,1), intent(out) :: x

        det_a = detf(a(:,:,1),n)

        do i=1,n
            a(:,:,i+1) = a(:,:,1)
            a(:,i,i+1) = b
            x(i,1) = detf(a(:,:,i+1),n)/det_a
        end do

    end subroutine cram

    recursive real*8 function detf(mat, n) result(det)

        implicit none
        integer, intent(in) :: n
        real*8, intent(in), dimension(n,n) :: mat
        real*8, dimension(n-1,n-1) :: sl
        integer :: i

        det = 0

        if (n == 1) then
            det = mat(1,1)
        else
            do i = 1,n
                call slicef(sl,mat,n,1,i)
                det = det + ((-1.0)**(1+i))*mat(1,i)*detf(sl,n-1)
            end do
        end if

    end function detf

    subroutine slicef(sl, mat, n, row, column)

        implicit none
        integer, intent(in) :: n,row,column
        real*8, dimension(n,n), intent(in) :: mat
        real*8, dimension(n-1,n-1), intent(out) :: sl
        logical, dimension(n,n) :: mask

        mask = .true.
        mask(row,:) = .false.
        mask(:,column) = .false.

        sl = reshape(pack(mat,mask),(/n-1,n-1/))

    end subroutine slicef

    end module maths1


program test_moment
    use stdlib_experimental_error, only: check
    use stdlib_experimental_kinds, only: sp, dp, int32, int64
    use stdlib_experimental_stats, only: moment
    use,intrinsic :: ieee_arithmetic, only : ieee_is_nan
    implicit none

    real(sp), parameter :: sptol = 1000 * epsilon(1._sp)
    real(dp), parameter :: dptol = 1000 * epsilon(1._dp)

    real(dp) :: d1(5) = [1.0_dp, 2.0_dp, 3.0_dp, 4.0_dp, 5.0_dp]
    real(dp) :: d(4, 3) = reshape([1._dp, 3._dp, 5._dp, 7._dp,&
                                   2._dp, 4._dp, 6._dp, 8._dp,&
                                   9._dp, 10._dp, 11._dp, 12._dp], [4, 3])

    complex(sp) :: cs1(5) = [ cmplx(0.57706_sp, 0.00000_sp),&
                            cmplx(0.00000_sp, 1.44065_sp),&
                            cmplx(1.26401_sp, 0.00000_sp),&
                            cmplx(0.00000_sp, 0.88833_sp),&
                            cmplx(1.14352_sp, 0.00000_sp)]
    complex(sp) :: cs(5,3)

    call test_sp(real(d1,sp), real(d,sp))
    call test_dp(d1, d)
    call test_int32(int(d1, int32), int(d, int32))
    call test_int64(int(d1, int64), int(d, int64))

    cs(:,1) = cs1
    cs(:,2) = cs1*3_sp
    cs(:,3) = cs1*1.5_sp
    call test_csp(cs1, cs)

contains
    subroutine test_sp(x1, x2)
        real(sp), intent(in) :: x1(:), x2(:, :)

        integer :: order
        real(sp), allocatable :: x3(:, :, :)

        order = 1

        !1dim
        print*,' test_sp_1dim', order
        call check( abs(moment(x1, order)) < sptol)
        call check( abs(moment(x1, order, dim=1)) < sptol)

        print*,' test_sp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_sp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5))) < sptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5))) < sptol)

        !2dim
        print*,' test_sp_2dim', order
        call check( abs(moment(x2, order)) < sptol)
        call check( all( abs( moment(x2, order, 1)) < sptol))
        call check( all( abs( moment(x2, order, 2)) < sptol))

        print*,' test_sp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_sp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))) < sptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11))) < sptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11))) < sptol))

        !3dim
        allocate(x3(size(x2,1),size(x2,2),3))
        x3(:,:,1)=x2;
        x3(:,:,2)=x2*2;
        x3(:,:,3)=x2*4;

        print*,' test_sp_3dim', order
        call check( abs(moment(x3, order)) < sptol)
        call check( all( abs( moment(x3, order, 1)) < sptol))
        call check( all( abs( moment(x3, order, 2)) < sptol))
        call check( all( abs( moment(x3, order, 3)) < sptol))

        print*,' test_sp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_sp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) ) < sptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45))) < sptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45))) < sptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45))) < sptol ))

        order = 2

        !1dim
        print*,' test_sp_1dim', order
        call check( abs(moment(x1, order) - 2._sp) < sptol)
        call check( abs(moment(x1, order, dim=1) - 2._sp) < sptol)

        print*,' test_sp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_sp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5)) - 1.25_sp) < sptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5)) - 1.25_sp) < sptol)

        !2dim
        print*,' test_sp_2dim', order
        call check( abs(moment(x2, order) - 107.25_sp/9.) < sptol)
        call check( all( abs( moment(x2, order, 1) - [5._sp, 5._sp, 1.25_sp]) < sptol))
        call check( all( abs( moment(x2, order, 2) -&
                           [19.0, 43. / 3., 31. / 3. , 7.0]*2./3.) < sptol))

        print*,' test_sp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_sp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))- 2.75_sp*3.) < sptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11)) -&
                      [5._sp, 5._sp, 0.25_sp]) < sptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11)) -&
                      [19._sp*2./3., 43._sp/9.*2., 0.25_sp , 0.25_sp]) < sptol))

        !3dim
        print*,' test_sp_3dim', order
        call check( abs(moment(x3, order) - 153.4_sp*35./36.) < sptol)
        call check( all( abs( moment(x3, order, 1) -&
                 reshape([20._sp / 3., 20._sp / 3., 5._sp / 3.,&
                          4* 20._sp / 3., 4* 20._sp / 3., 4* 5._sp / 3.,&
                          16* 20._sp / 3., 16* 20._sp / 3., 16* 5._sp / 3.],&
                          [size(x3,2), size(x3,3)])*3._sp/4.)&
                 < sptol))
        call check( all( abs( moment(x3, order, 2) -&
                 reshape([19._sp, 43._sp / 3., 31._sp / 3. , 7.0_sp,&
                          4* 19.0_sp, 4* 43._sp / 3., 4* 31._sp / 3. , 4* 7.0_sp,&
                          16* 19.0_sp, 16* 43._sp / 3., 16* 31._sp / 3. , 16* 7.0_sp],&
                          [size(x3,1), size(x3,3)] )*2._sp/3.)&
                 < sptol))
        call check( all( abs( moment(x3, order, 3) -&
                 reshape([ 7._sp/3., 21._sp, 175._sp/3.,&
                           343._sp/3., 28._sp/3., 112._sp/3.,&
                           84._sp, 448._sp/3., 189._sp,&
                           700._sp/3., 847._sp/3., 336._sp],&
                           [size(x3,1), size(x3,2)] )*2./3.)&
                 < sptol))

        print*,' test_sp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_sp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) -&
                      7.7370242214532876_dp ) < sptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45)) -&
                      reshape([5._sp, 5._sp, 1.25_sp,  20._sp, 20._sp, 5._sp,&
                               80._sp, 80._sp, 32._sp/3.],&
                               [size(x3, 2), size(x3, 3)])) < sptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45)) -&
                      reshape([ 38._sp/3., 86._sp/9., 62._sp/9., 14._sp/3., 152._sp/3.,&
                                344._sp/9., 248._sp/9., 168._sp/9., 1824._sp/9.,&
                                1376._sp/9., 992._sp/9., 4._sp&
                               ],&
                      [size(x3, 1), size(x3, 3)])) < sptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45)) -&
                     reshape([14._sp/9., 14._sp, 350._sp/9., 686._sp/9., 56._sp/9.,&
                              224._sp/9., 56._sp, 896._sp/9., 126._sp, 1400._sp/9.,&
                              1694._sp/9., 36._sp&
                               ], [size(x3,1), size(x3,2)] ))&
                     < sptol ))

    end subroutine

    subroutine test_dp(x1, x2)
        real(dp), intent(in) :: x1(:), x2(:, :)

        integer :: order
        real(dp), allocatable :: x3(:, :, :)

        order = 1

        !1dim
        print*,' test_dp_1dim', order
        call check( abs(moment(x1, order)) < dptol)
        call check( abs(moment(x1, order, dim=1)) < dptol)

        print*,' test_dp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_dp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5))) < dptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5))) < dptol)

        !2dim
        print*,' test_dp_2dim', order
        call check( abs(moment(x2, order)) < dptol)
        call check( all( abs( moment(x2, order, 1)) < dptol))
        call check( all( abs( moment(x2, order, 2)) < dptol))

        print*,' test_dp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_dp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))) < dptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11))) < dptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11))) < dptol))

        !3dim
        allocate(x3(size(x2,1),size(x2,2),3))
        x3(:,:,1)=x2;
        x3(:,:,2)=x2*2;
        x3(:,:,3)=x2*4;

        print*,' test_dp_3dim', order
        call check( abs(moment(x3, order)) < dptol)
        call check( all( abs( moment(x3, order, 1)) < dptol))
        call check( all( abs( moment(x3, order, 2)) < dptol))
        call check( all( abs( moment(x3, order, 3)) < dptol))

        print*,' test_dp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_dp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) ) < dptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45))) < dptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45))) < dptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45))) < dptol ))

        order = 2

        !1dim
        print*,' test_dp_1dim', order
        call check( abs(moment(x1, order) - 2._dp) < dptol)
        call check( abs(moment(x1, order, dim=1) - 2._dp) < dptol)

        print*,' test_dp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_dp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5)) - 1.25_dp) < dptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5)) - 1.25_dp) < dptol)

        !2dim
        print*,' test_dp_2dim', order
        call check( abs(moment(x2, order) - 107.25_dp/9.) < dptol)
        call check( all( abs( moment(x2, order, 1) - [5._dp, 5._dp, 1.25_dp]) < dptol))
        call check( all( abs( moment(x2, order, 2) -&
                      [19._dp, 43._dp / 3., 31._dp / 3. , 7._dp]*2._dp/3.) < dptol))

        print*,' test_dp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_dp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))- 2.75_dp*3.) < dptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11)) -&
                      [5._dp, 5._dp, 0.25_dp]) < dptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11)) -&
                      [19._dp*2./3., 43._dp/9.*2., 0.25_dp , 0.25_dp]) < dptol))

        !3dim
        print*,' test_dp_3dim', order
        call check( abs(moment(x3, order) - 153.4_dp*35./36.) < dptol)
        call check( all( abs( moment(x3, order, 1) -&
                 reshape([20._dp / 3., 20._dp / 3., 5._dp / 3.,&
                          4* 20._dp / 3., 4* 20._dp / 3., 4* 5._dp / 3.,&
                          16* 20._dp / 3., 16* 20._dp / 3., 16* 5._dp / 3.],&
                          [size(x3,2), size(x3,3)])*3._dp/4.)&
                 < dptol))
        call check( all( abs( moment(x3, order, 2) -&
                 reshape([19._dp, 43._dp / 3., 31._dp / 3. , 7.0_dp,&
                          4* 19.0_dp, 4* 43._dp / 3., 4* 31._dp / 3. , 4* 7.0_dp,&
                          16* 19.0_dp, 16* 43._dp / 3., 16* 31._dp / 3. , 16* 7.0_dp],&
                          [size(x3,1), size(x3,3)] )*2._dp/3.)&
                 < dptol))
        call check( all( abs( moment(x3, order, 3) -&
                 reshape([ 7._dp/3., 21._dp, 175._dp/3.,&
                           343._dp/3., 28._dp/3., 112._dp/3.,&
                           84._dp, 448._dp/3., 189._dp,&
                           700._dp/3., 847._dp/3., 336._dp],&
                           [size(x3,1), size(x3,2)] )*2./3.)&
                 < dptol))

        print*,' test_dp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_dp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) -&
                          7.7370242214532876_dp ) < dptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45)) -&
                      reshape([5._dp, 5._dp, 1.25_dp,  20._dp, 20._dp, 5._dp,&
                               80._dp, 80._dp, 32._dp/3.],&
                               [size(x3, 2), size(x3, 3)])) < dptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45)) -&
                      reshape([ 38._dp/3., 86._dp/9., 62._dp/9., 14._dp/3., 152._dp/3.,&
                                344._dp/9., 248._dp/9., 168._dp/9., 1824._dp/9.,&
                                1376._dp/9., 992._dp/9., 4._dp&
                               ],&
                      [size(x3, 1), size(x3, 3)])) < dptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45)) -&
                     reshape([14._dp/9., 14._dp, 350._dp/9., 686._dp/9., 56._dp/9.,&
                              224._dp/9., 56._dp, 896._dp/9., 126._dp, 1400._dp/9.,&
                              1694._dp/9., 36._dp&
                               ], [size(x3,1), size(x3,2)] ))&
                     < dptol ))

    end subroutine

    subroutine test_int32(x1, x2)
        integer(int32), intent(in) :: x1(:), x2(:, :)

        integer :: order
        integer(int32), allocatable :: x3(:, :, :)

        order = 1

        !1dim
        print*,' test_dp_1dim', order
        call check( abs(moment(x1, order)) < dptol)
        call check( abs(moment(x1, order, dim=1)) < dptol)

        print*,' test_dp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_dp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5))) < dptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5))) < dptol)

        !2dim
        print*,' test_dp_2dim', order
        call check( abs(moment(x2, order)) < dptol)
        call check( all( abs( moment(x2, order, 1)) < dptol))
        call check( all( abs( moment(x2, order, 2)) < dptol))

        print*,' test_dp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_dp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))) < dptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11))) < dptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11))) < dptol))

        !3dim
        allocate(x3(size(x2,1),size(x2,2),3))
        x3(:,:,1)=x2;
        x3(:,:,2)=x2*2;
        x3(:,:,3)=x2*4;

        print*,' test_dp_3dim', order
        call check( abs(moment(x3, order)) < dptol)
        call check( all( abs( moment(x3, order, 1)) < dptol))
        call check( all( abs( moment(x3, order, 2)) < dptol))
        call check( all( abs( moment(x3, order, 3)) < dptol))

        print*,' test_dp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_dp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) ) < dptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45))) < dptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45))) < dptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45))) < dptol ))

        order = 2

        !1dim
        print*,' test_dp_1dim', order
        call check( abs(moment(x1, order) - 2._dp) < dptol)
        call check( abs(moment(x1, order, dim=1) - 2._dp) < dptol)

        print*,' test_dp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_dp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5)) - 1.25_dp) < dptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5)) - 1.25_dp) < dptol)

        !2dim
        print*,' test_dp_2dim', order
        call check( abs(moment(x2, order) - 107.25_dp/9.) < dptol)
        call check( all( abs( moment(x2, order, 1) - [5._dp, 5._dp, 1.25_dp]) < dptol))
        call check( all( abs( moment(x2, order, 2) -&
                      [19._dp, 43._dp / 3., 31._dp / 3. , 7._dp]*2._dp/3.) < dptol))

        print*,' test_dp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_dp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))- 2.75_dp*3.) < dptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11)) -&
                      [5._dp, 5._dp, 0.25_dp]) < dptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11)) -&
                      [19._dp*2./3., 43._dp/9.*2., 0.25_dp , 0.25_dp]) < dptol))

        !3dim
        print*,' test_dp_3dim', order
        call check( abs(moment(x3, order) - 153.4_dp*35./36.) < dptol)
        call check( all( abs( moment(x3, order, 1) -&
                 reshape([20._dp / 3., 20._dp / 3., 5._dp / 3.,&
                          4* 20._dp / 3., 4* 20._dp / 3., 4* 5._dp / 3.,&
                          16* 20._dp / 3., 16* 20._dp / 3., 16* 5._dp / 3.],&
                          [size(x3,2), size(x3,3)])*3._dp/4.)&
                 < dptol))
        call check( all( abs( moment(x3, order, 2) -&
                 reshape([19._dp, 43._dp / 3., 31._dp / 3. , 7.0_dp,&
                          4* 19.0_dp, 4* 43._dp / 3., 4* 31._dp / 3. , 4* 7.0_dp,&
                          16* 19.0_dp, 16* 43._dp / 3., 16* 31._dp / 3. , 16* 7.0_dp],&
                          [size(x3,1), size(x3,3)] )*2._dp/3.)&
                 < dptol))
        call check( all( abs( moment(x3, order, 3) -&
                 reshape([ 7._dp/3., 21._dp, 175._dp/3.,&
                           343._dp/3., 28._dp/3., 112._dp/3.,&
                           84._dp, 448._dp/3., 189._dp,&
                           700._dp/3., 847._dp/3., 336._dp],&
                           [size(x3,1), size(x3,2)] )*2./3.)&
                 < dptol))

        print*,' test_dp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_dp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) -&
                          7.7370242214532876_dp ) < dptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45)) -&
                      reshape([5._dp, 5._dp, 1.25_dp,  20._dp, 20._dp, 5._dp,&
                               80._dp, 80._dp, 32._dp/3.],&
                               [size(x3, 2), size(x3, 3)])) < dptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45)) -&
                      reshape([ 38._dp/3., 86._dp/9., 62._dp/9., 14._dp/3., 152._dp/3.,&
                                344._dp/9., 248._dp/9., 168._dp/9., 1824._dp/9.,&
                                1376._dp/9., 992._dp/9., 4._dp&
                               ],&
                      [size(x3, 1), size(x3, 3)])) < dptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45)) -&
                     reshape([14._dp/9., 14._dp, 350._dp/9., 686._dp/9., 56._dp/9.,&
                              224._dp/9., 56._dp, 896._dp/9., 126._dp, 1400._dp/9.,&
                              1694._dp/9., 36._dp&
                               ], [size(x3,1), size(x3,2)] ))&
                     < dptol ))

    end subroutine

    subroutine test_int64(x1, x2)
        integer(int64), intent(in) :: x1(:), x2(:, :)

        integer :: order
        integer(int64), allocatable :: x3(:, :, :)

        order = 1

        !1dim
        print*,' test_dp_1dim', order
        call check( abs(moment(x1, order)) < dptol)
        call check( abs(moment(x1, order, dim=1)) < dptol)

        print*,' test_dp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_dp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5))) < dptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5))) < dptol)

        !2dim
        print*,' test_dp_2dim', order
        call check( abs(moment(x2, order)) < dptol)
        call check( all( abs( moment(x2, order, 1)) < dptol))
        call check( all( abs( moment(x2, order, 2)) < dptol))

        print*,' test_dp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_dp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))) < dptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11))) < dptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11))) < dptol))

        !3dim
        allocate(x3(size(x2,1),size(x2,2),3))
        x3(:,:,1)=x2;
        x3(:,:,2)=x2*2;
        x3(:,:,3)=x2*4;

        print*,' test_dp_3dim', order
        call check( abs(moment(x3, order)) < dptol)
        call check( all( abs( moment(x3, order, 1)) < dptol))
        call check( all( abs( moment(x3, order, 2)) < dptol))
        call check( all( abs( moment(x3, order, 3)) < dptol))

        print*,' test_dp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_dp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) ) < dptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45))) < dptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45))) < dptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45))) < dptol ))

        order = 2

        !1dim
        print*,' test_dp_1dim', order
        call check( abs(moment(x1, order) - 2._dp) < dptol)
        call check( abs(moment(x1, order, dim=1) - 2._dp) < dptol)

        print*,' test_dp_1dim_mask', order
        call check( ieee_is_nan(moment(x1, order, mask = .false.)))
        call check( ieee_is_nan(moment(x1, order, 1, mask = .false.)))

        print*,' test_dp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (x1 < 5)) - 1.25_dp) < dptol)
        call check( abs(moment(x1, order, 1, mask = (x1 < 5)) - 1.25_dp) < dptol)

        !2dim
        print*,' test_dp_2dim', order
        call check( abs(moment(x2, order) - 107.25_dp/9.) < dptol)
        call check( all( abs( moment(x2, order, 1) - [5._dp, 5._dp, 1.25_dp]) < dptol))
        call check( all( abs( moment(x2, order, 2) -&
                      [19._dp, 43._dp / 3., 31._dp / 3. , 7._dp]*2._dp/3.) < dptol))

        print*,' test_dp_2dim_mask', order
        call check( ieee_is_nan(moment(x2, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x2, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x2, order, 2, mask = .false.))))

        print*,' test_dp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (x2 < 11))- 2.75_dp*3.) < dptol)
        call check( all( abs( moment(x2, order, 1, mask = (x2 < 11)) -&
                      [5._dp, 5._dp, 0.25_dp]) < dptol))
        call check( all( abs( moment(x2, order, 2, mask = (x2 < 11)) -&
                      [19._dp*2./3., 43._dp/9.*2., 0.25_dp , 0.25_dp]) < dptol))

        !3dim
        print*,' test_dp_3dim', order
        call check( abs(moment(x3, order) - 153.4_dp*35./36.) < dptol)
        call check( all( abs( moment(x3, order, 1) -&
                 reshape([20._dp / 3., 20._dp / 3., 5._dp / 3.,&
                          4* 20._dp / 3., 4* 20._dp / 3., 4* 5._dp / 3.,&
                          16* 20._dp / 3., 16* 20._dp / 3., 16* 5._dp / 3.],&
                          [size(x3,2), size(x3,3)])*3._dp/4.)&
                 < dptol))
        call check( all( abs( moment(x3, order, 2) -&
                 reshape([19._dp, 43._dp / 3., 31._dp / 3. , 7.0_dp,&
                          4* 19.0_dp, 4* 43._dp / 3., 4* 31._dp / 3. , 4* 7.0_dp,&
                          16* 19.0_dp, 16* 43._dp / 3., 16* 31._dp / 3. , 16* 7.0_dp],&
                          [size(x3,1), size(x3,3)] )*2._dp/3.)&
                 < dptol))
        call check( all( abs( moment(x3, order, 3) -&
                 reshape([ 7._dp/3., 21._dp, 175._dp/3.,&
                           343._dp/3., 28._dp/3., 112._dp/3.,&
                           84._dp, 448._dp/3., 189._dp,&
                           700._dp/3., 847._dp/3., 336._dp],&
                           [size(x3,1), size(x3,2)] )*2./3.)&
                 < dptol))

        print*,' test_dp_3dim_mask', order
        call check( ieee_is_nan(moment(x3, order, mask = .false.)))
        call check( any(ieee_is_nan(moment(x3, order, 1, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 2, mask = .false.))))
        call check( any(ieee_is_nan(moment(x3, order, 3, mask = .false.))))

        print*,' test_dp_3dim_mask_array', order
        call check( abs(moment(x3, order, mask = (x3 < 11)) -&
                          7.7370242214532876_dp ) < dptol)
        call check( all( abs( moment(x3, order, 1, mask = (x3 < 45)) -&
                      reshape([5._dp, 5._dp, 1.25_dp,  20._dp, 20._dp, 5._dp,&
                               80._dp, 80._dp, 32._dp/3.],&
                               [size(x3, 2), size(x3, 3)])) < dptol ))
        call check( all( abs( moment(x3, order, 2, mask = (x3 < 45)) -&
                      reshape([ 38._dp/3., 86._dp/9., 62._dp/9., 14._dp/3., 152._dp/3.,&
                                344._dp/9., 248._dp/9., 168._dp/9., 1824._dp/9.,&
                                1376._dp/9., 992._dp/9., 4._dp&
                               ],&
                      [size(x3, 1), size(x3, 3)])) < dptol ))
        call check( all( abs( moment(x3, order, 3, mask = (x3 < 45)) -&
                     reshape([14._dp/9., 14._dp, 350._dp/9., 686._dp/9., 56._dp/9.,&
                              224._dp/9., 56._dp, 896._dp/9., 126._dp, 1400._dp/9.,&
                              1694._dp/9., 36._dp&
                               ], [size(x3,1), size(x3,2)] ))&
                     < dptol ))

    end subroutine

    subroutine test_csp(x1, x2)
        complex(sp), intent(in) :: x1(:), x2(:, :)

        integer :: order

        order = 1

        !1dim
        print*,' test_sp_1dim', order
        call check( abs(moment(x1, order)) < sptol)
        call check( abs(moment(x1, order, dim=1)) < sptol)

        print*,' test_sp_1dim_mask', order
        call check( ieee_is_nan(abs(moment(x1, order, mask = .false.))))
        call check( ieee_is_nan(abs(moment(x1, order, 1, mask = .false.))))

        print*,' test_sp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (aimag(x1) == 0))) < sptol)
        call check( abs(moment(x1, order, 1, mask = (aimag(x1) == 0))) < sptol)

        !2dim
        print*,' test_sp_2dim', order
        call check( abs(moment(x2, order)) < sptol)
        call check( all( abs( moment(x2, order, 1)) < sptol))
        call check( all( abs( moment(x2, order, 2)) < sptol))

        print*,' test_sp_2dim_mask', order
        call check( ieee_is_nan(abs(moment(x2, order, mask = .false.))))
        call check( any(ieee_is_nan(abs(moment(x2, order, 1, mask = .false.)))))
        call check( any(ieee_is_nan(abs(moment(x2, order, 2, mask = .false.)))))

        print*,' test_sp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (aimag(x2) == 0))) < sptol)
        call check( all( abs( moment(x2, order, 1, mask = (aimag(x2) == 0))) < sptol))
        call check( any(ieee_is_nan( abs( moment(x2, order, 2,&
                          mask = (aimag(x2) == 0))))))

        order = 2

        !1dim
        print*,' test_sp_1dim', order
        call check( abs(moment(x1, order) - (-6.459422410E-02,-0.556084037)) < sptol)
        call check( abs(moment(x1, order, dim=1) -&
                        (-6.459422410E-02,-0.556084037)) < sptol)

        print*,' test_sp_1dim_mask', order
        call check( ieee_is_nan(abs(moment(x1, order, mask = .false.))))
        call check( ieee_is_nan(abs(moment(x1, order, 1, mask = .false.))))

        print*,' test_sp_1dim_mask_array', order
        call check( abs(moment(x1, order, mask = (aimag(x1) == 0)) -&
                          (8.969944715E-02,0.00000000)) < sptol)
        call check( abs(moment(x1, order, 1, mask = (aimag(x1) == 0)) -&
                          (8.969944715E-02,0.00000000)) < sptol)

        !2dim
        print*,' test_sp_2dim', order
        call check( abs(moment(x2, order) - (-0.163121477,-1.86906016)) < sptol)
        call check( all( abs( moment(x2, order, 1) -&
                     [(-6.459422410E-02,-0.556084037),&
                      (-0.581347823,-5.00475645),&
                      (-0.145336956,-1.25118911)]&
                     ) < sptol))
        call check( all( abs( moment(x2, order, 2) -&
                     [(0.240498722,0.00000000),&
                     (-1.49895227,0.00000000),&
                     (1.15390968,0.00000000),&
                     (-0.569927275,0.00000000),&
                     (0.944405317,0.00000000)]&
                     ) < sptol))

        print*,' test_sp_2dim_mask', order
        call check( ieee_is_nan(abs(moment(x2, order, mask = .false.))))
        call check( any(ieee_is_nan(abs(moment(x2, order, 1, mask = .false.)))))
        call check( any(ieee_is_nan(abs(moment(x2, order, 2, mask = .false.)))))

        print*,' test_sp_2dim_mask_array', order
        call check( abs(moment(x2, order, mask = (aimag(x2) == 0))-&
                     (1.08109438,0.00000000)) < sptol)
        call check( all( abs( moment(x2, order, 1, mask = (aimag(x2)==0)) -&
                      [(8.969944715E-02,0.00000000),&
                       (0.807295084,0.00000000),&
                       (0.201823771,0.00000000)]&
                       ) < sptol))

    end subroutine
end program