SUBROUTINE kaiser(a, nrows, n, eigenv, trace, sume, ier)

!  EIGENVALUES AND VECTORS OF A SYMMETRIC +VE DEFINITE MATRIX,
!  USING KAISER'S METHOD.
!  REFERENCE: KAISER,H.F. 'THE JK METHOD: A PROCEDURE FOR FINDING THE
!  EIGENVALUES OF A REAL SYMMETRIC MATRIX', COMPUT.J., VOL.15, 271-273, 1972.

!  ARGUMENTS:-
!  A       = INPUT, AN ARRAY CONTAINING THE MATRIX
!            OUTPUT, THE COLUMNS OF A CONTAIN THE NORMALIZED EIGENVECTORS
!            OF A.   N.B. A IS OVERWRITTEN !
!  NROWS   = INPUT, THE FIRST DIMENSION OF A IN THE CALLING PROGRAM.
!  N       = INPUT, THE ORDER OF A, I.E. NO. OF COLUMNS.
!            N MUST BE <= NROWS.
!  EIGENV()= OUTPUT, A VECTOR CONTAINING THE ORDERED EIGENVALUES.
!  TRACE   = OUTPUT, THE TRACE OF THE INPUT MATRIX.
!  SUME    = OUTPUT, THE SUM OF THE EIGENVALUES COMPUTED.
!            N.B. ANY SYMMETRIC MATRIX MAY BE INPUT, BUT IF IT IS NOT +VE
!            DEFINITE, THE ABSOLUTE VALUES OF THE EIGENVALUES WILL BE FOUND.
!            IF TRACE = SUME, THEN ALL OF THE EIGENVALUES ARE POSITIVE
!            OR ZERO.   IF SUME > TRACE, THE DIFFERENCE IS TWICE THE SUM OF
!            THE EIGENVALUES WHICH HAVE BEEN GIVEN THE WRONG SIGNS !
!  IER     = OUTPUT, ERROR INDICATOR
!             = 0 NO ERROR
!             = 1 N > NROWS OR N < 1
!             = 2 FAILED TO CONVERGE IN 10 ITERATIONS

!  LATEST REVISION - 6 September 1990
!  Fortran 90 version - 20 November 1998

!*************************************************************************

IMPLICIT NONE
INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(14, 60)

REAL (dp), INTENT(IN OUT) :: a(:,:)
INTEGER, INTENT(IN)       :: nrows
INTEGER, INTENT(IN)       :: n
REAL (dp), INTENT(OUT)    :: eigenv(:)
REAL (dp), INTENT(OUT)    :: trace
REAL (dp), INTENT(OUT)    :: sume
INTEGER, INTENT(OUT)      :: ier

! Local variables

REAL (dp), PARAMETER :: small = 1.0e-12_dp, zero = 0.0_dp, half = 0.5_dp,  &
                        one = 1.0_dp
INTEGER   :: i, iter, j, k, ncount, nn
REAL (dp) :: absp, absq, COS, ctn, eps, halfp, p, q, SIN, ss, TAN, temp, xj, xk

!   CALCULATE CONVERGENCE TOLERANCE, EPS.
!   CALCULATE TRACE.   INITIAL SETTINGS.

ier = 1
IF(n < 1 .OR. n > nrows) RETURN
ier = 0
iter = 0
trace = zero
ss = zero
DO j = 1,n
  trace = trace + a(j,j)
  DO i = 1,n
    ss = ss + a(i,j)**2
  END DO
END DO
sume = zero
eps = small*ss/n
nn = n*(n-1)/2
ncount = nn

!   ORTHOGONALIZE PAIRS OF COLUMNS J & K, K > J.

20 DO j = 1,n-1
  DO k = j+1,n

!   CALCULATE PLANAR ROTATION REQUIRED

    halfp = zero
    q = zero
    DO i = 1,n
      xj = a(i,j)
      xk = a(i,k)
      halfp = halfp + xj*xk
      q = q + (xj+xk) * (xj-xk)
    END DO
    p = halfp + halfp
    absp = ABS(p)

!   If P is very small, the vectors are almost orthogonal.
!   Skip the rotation if Q >= 0 (correct ordering).

    IF (absp < eps .AND. q >= zero) THEN
      ncount = ncount - 1
      IF (ncount <= 0) GO TO 160
      CYCLE
    END IF

!   Rotation needed.

    absq = ABS(q)
    IF(absp <= absq) THEN
      TAN = absp/absq
      COS = one/SQRT(one + TAN*TAN)
      SIN = TAN*COS
    ELSE
      ctn = absq/absp
      SIN = one/SQRT(one + ctn*ctn)
      COS = ctn*SIN
    END IF
    COS = SQRT((one + COS)*half)
    SIN = SIN/(COS + COS)
    IF(q < zero) THEN
      temp = COS
      COS = SIN
      SIN = temp
    END IF
    IF(p < zero) SIN = -SIN

!   PERFORM ROTATION

    DO i = 1,n
      temp = a(i,j)
      a(i,j) = temp*COS + a(i,k)*SIN
      a(i,k) = -temp*SIN + a(i,k)*COS
    END DO
  END DO
END DO
ncount = nn
iter = iter + 1
IF(iter < 10) GO TO 20
ier = 2

!   CONVERGED, OR GAVE UP AFTER 10 ITERATIONS

160 DO j = 1,n
  temp = SUM( a(1:n,j)**2 )
  eigenv(j) = SQRT(temp)
  sume = sume + eigenv(j)
END DO

!   SCALE COLUMNS TO HAVE UNIT LENGTH

DO j = 1,n
  IF (eigenv(j) > zero) THEN
    temp = one/eigenv(j)
  ELSE
    temp = zero
  END IF
  a(1:n,j) = a(1:n,j)*temp
END DO

RETURN
END SUBROUTINE kaiser


      subroutine clawpack46_setaux(maxmx,maxmy,mbc,mx,my,
     &      xlower,ylower,dx,dy,maux,aux)
      implicit none

      integer mbc, mx, my, maux, maxmx, maxmy
      double precision xlower, ylower, dx, dy
      double precision  aux(1-mbc:maxmx+mbc,1-mbc:maxmy+mbc,maux)

      integer i, j
      double precision xc, yc, pi,s
      integer example

      common /compi/ pi
      common /comex/ example

      do i = 1-mbc,mx+mbc
         do j = 1-mbc,my+mbc
c           # coordinates of lower left corner of grid cell:
            xc = xlower + (i-0.5)*dx
            yc = ylower + (j-0.5)*dy

            s = sqrt(2.d0)
            if (example .eq. 1) then
               aux(i,j,1) = s*(cos(pi*xc)**2 + 0.5d0)
               aux(i,j,2) = s*(sin(pi*yc)**2 + 0.5d0)
            else
               aux(i,j,1) = s*(cos(pi*xc)**2 - 0.5d0)
               aux(i,j,2) = s*(sin(pi*yc)**2 - 0.5d0)
            endif

         enddo
      enddo

      return
      end


      SUBROUTINE drealft(data,n,isign)
      INTEGER isign,n
      DOUBLE PRECISION data(n)
CU    USES dfour1
      INTEGER i,i1,i2,i3,i4,n2p3
      DOUBLE PRECISION c1,c2,h1i,h1r,h2i,h2r,wis,wrs
      DOUBLE PRECISION theta,wi,wpi,wpr,wr,wtemp
      theta=3.141592653589793d0/dble(n/2)
      c1=0.5d0
      if (isign.eq.1) then
        c2=-0.5d0
        call dfour1(data,n/2,+1)
      else
        c2=0.5d0
        theta=-theta
      endif
      wpr=-2.0d0*sin(0.5d0*theta)**2
      wpi=sin(theta)
      wr=1.0d0+wpr
      wi=wpi
      n2p3=n+3
      do 11 i=2,n/4
        i1=2*i-1
        i2=i1+1
        i3=n2p3-i2
        i4=i3+1
        wrs=wr
        wis=wi
        h1r=c1*(data(i1)+data(i3))
        h1i=c1*(data(i2)-data(i4))
        h2r=-c2*(data(i2)+data(i4))
        h2i=c2*(data(i1)-data(i3))
        data(i1)=h1r+wrs*h2r-wis*h2i
        data(i2)=h1i+wrs*h2i+wis*h2r
        data(i3)=h1r-wrs*h2r+wis*h2i
        data(i4)=-h1i+wrs*h2i+wis*h2r
        wtemp=wr
        wr=wr*wpr-wi*wpi+wr
        wi=wi*wpr+wtemp*wpi+wi
11    continue
      if (isign.eq.1) then
        h1r=data(1)
        data(1)=h1r+data(2)
        data(2)=h1r-data(2)
      else
        h1r=data(1)
        data(1)=c1*(h1r+data(2))
        data(2)=c1*(h1r-data(2))
        call dfour1(data,n/2,-1)
      endif
      return
      END

NR-Functions/Numerical Recipes- Example & Functions/Functions/drealft.for


program gaussseli
    !This program simply takes in an nxn matrix, and an nx1 matrix, converts into a reduced row echelon form using gauss jordan FULL pivoting,
    !,then calculates the determinant of nxn, if determinant is non-singular the program proceeds to calculate inverse
    !and solution of (nXn) x = (nX1) form equation (i.e. Ax=b)
    !Various parts of the code are highlighted by comments as to what they do.
    implicit none
    integer :: n,i,k,j
    integer, allocatable :: indices(:)
    real , allocatable :: A(:,:), temp(:)
    real :: q, ep=10**(-7)
    print*, "Give the dimension of matrix A in form AX=b"
    read*, n
    allocate(A(n,n+1+n), temp(n+n+1), indices(n))   !Allocate nxn for original matrix, nx1 for b, nxn for I all concatenated
    !!!!!!!!!!!!!!!!!!!!!!!!!!!! READING MATRIX FROM USER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    print*, "Give the rows of matrix A"
    do i=1,n
        read*, A(i,1:n)
    enddo
    print*,"Give values of b"
    do i=1,n
        read*, A(i,n+1)
    enddo
    !!!!!!!!!!!!! MATRIX FORM IS A(augmented) = A(read)|b(read)|I CONCATENATED AND PROCESSED TOGETHER THROUGHOUT !!!!!!!!!!!!!!
    do i=1,n
        A(i,n+i+1) =1   !getting the identity of the third part in matrix
    enddo
    print*, "MATRIX = A | b | Identity"
    do i=1,n
        print*,A(i,:)
    enddo
    do i=1,n
        indices(i) = i    ! to keep track of solution number for later during full pivoting column shifts
    enddo
    print*, "================================================"
    !!!!!!!!!!!!!!!! CONVERTING THE MATRIX TO UPPER TRIANGULAR REDUCED ECHELON !!!!!!!!!!!!!!!!!!!
    do k = 1,n
        call fullpivot(A(k:,k:),A,indices,k)
        do j=k+1,n
            q=(A(j,k))/A(k,k)
            do i=k,n+n+1
                A(j,i) = A(j,i) - q* A(k,i)       !finally making the lower triangular terms zero
            enddo
        enddo
    enddo
    !!!!!!!!!!!!!!!!!!!!!!!!! CONVERSION DONE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    print*, "The modified/augmented matrix:"
    do i=1,n
        print*,A(i,:)
    enddo
    print*, "====================================================="
    !!!!!!!!!! CHECK DETERMINANT AFTER REDUCING IT TO UPPER TRIANGULAR !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    print*, "Checking determinant"
    q = 1    ! determinant
    do i=1,n
        q = q * A(i,i)      !determinant is simply the product of diagonal elements in upper diagonal
    enddo
    print*, "The determinant is:", q
    If (abs(q) .le. ep) then
        print*, "Determinant is SINGULAR, unsolvable"
        STOP
    endif
    print*, "====================================================="
    !!!!!!!!!!!!!!!!!!!!!!!!!!!CALCULATE FINAL RESULT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    temp =0
    temp(n) = (A(n,n+1))/A(n,n)
    do i = n-1,1,-1
        q=0
        do j=i+1,n
            q = q + A(i,j)*temp(j)
        enddo
        temp(i)= (A(i,n+1) -q)/A(i,i)
    enddo
    do i=1,n
    print*, "The", indices(i), ' solution is', temp(i)
    enddo
    print*, "========================================================="

    contains
    subroutine fullpivot(submatrix,matrix,solindices,row_ind)
        real :: submatrix(:,:),matrix(:,:)
        real, allocatable :: tempmat(:)
        integer :: q(2),pos(2),row_ind,dummy, solindices(:)

        q=shape(submatrix)
        print*, "=============================submatrix==================================="
        do i=1,q(1)
            print*,submatrix(i,:)
        enddo
        pos = maxloc(abs(submatrix(:,:q(1))))   !position of the biggest element in the square submatrix

        if (pos(2) .ne. 1) then      ! check if highest element belongs to first column, if no then swap columns first
            allocate(tempmat(q(1)))
            tempmat = A(:,pos(2)+row_ind-1) ; A(:,pos(2)+row_ind-1) = A(:,row_ind) ; A(:,row_ind) = tempmat
            dummy = solindices(pos(2)+row_ind-1) ; solindices(pos(2)+row_ind-1) = solindices(row_ind)
            solindices(row_ind) = dummy
            deallocate(tempmat)     !the above lines do column swap and swap the indices as well to keep track of variables/indices
        endif
        if (pos(1) .ne. 1) then         !check if highest element now belongs to the first row, if not then swap rows
            allocate(tempmat(q(2)))
            tempmat = submatrix(pos(1),:) ; submatrix(pos(1),:) = submatrix(1,:) ; submatrix(1,:) = tempmat
            deallocate(tempmat)
        endif
    end subroutine fullpivot

end program gaussseli


!*****************************************************************************************
!> author: Jacob Williams
!
!  General math routines

    module math_module

    use kind_module,    only: wp
    use numbers_module, only: pi,twopi

    implicit none

    private

    public :: cube_root
    public :: wrap_angle

    contains
!*****************************************************************************************

!*****************************************************************************************
!>
!  Wrap an angle (in rad) from -pi to pi.

    pure elemental function wrap_angle(a) result(r)

    implicit none

    real(wp),intent(in) :: a
    real(wp)            :: r

    r = mod(a,twopi)
    if (abs(r)>pi) r = r - sign(twopi,r)

    end function wrap_angle
!*****************************************************************************************

!*****************************************************************************************
!> author: Jacob Williams
!
!  Cube root of a number (real solution only).

    pure elemental function cube_root(x) result(y)

    use numbers_module, only: one,three

    implicit none

    real(wp),intent(in) :: x
    real(wp)            :: y

    real(wp),parameter :: one_third = one/three

    y = sign( abs(x) ** one_third , x )

    end function cube_root
!*****************************************************************************************

!*****************************************************************************************
    end module math_module
!*****************************************************************************************


program complex_04
implicit none

complex :: x
real :: a, b

x = (1.0,-3.0)
a = real(x)
b = aimag(x)
print *, a, b
if (abs(a - 1) > 1e-5) error stop
if (abs(b - (-3)) > 1e-5) error stop

end program


program main
    use plantFEM
    implicit none

    ! 静的型宣言
    type(Random_) :: random
    type(IO_) :: f
    real(real64),allocatable :: dat(:,:)
    real(real64),allocatable :: dat1(:,:)
    real(real64),allocatable :: dat2(:,:)

    ! 乱数入り配列の作成
    dat = random%randn(3,5)

    ! 配列の表示
    call print(dat)

    ! 計算＋配列の表示
    call print(dat*10.0d0)
    call print(dat+2.0d0*dat)

    ! 配列サイズの表示
    call showsize(dat)

    ! 配列の書き出し
    call savetxt(dat,"./","array1",".txt")

    ! 配列の読み出し
    dat1 = loadtxt("./","array1",".txt")

    ! 配列の表示
    call print(dat1)

    ! または、たくさん配列を並べるときにはこれが便利
    call f%open("./"//"array2"//".txt")
    call save(f%fh, dat)
    call save(f%fh, dat)
    call save(f%fh, dat)
    call f%close()

    ! 読む時
    call f%open("./"//"array2"//".txt")
    call load(f%fh, dat)
    call load(f%fh, dat1)
    call load(f%fh, dat2)
    call f%close()

    call print(dat1)

end program


      PROGRAM xsplint
C     driver for routine splint, which calls spline
      INTEGER NP
      REAL PI
      PARAMETER(NP=10,PI=3.141593)
      INTEGER i,nfunc
      REAL f,x,y,yp1,ypn,xa(NP),ya(NP),y2(NP)
      do 14 nfunc=1,2
        if (nfunc.eq.1) then
          write(*,*) 'Sine function from 0 to PI'
          do 11 i=1,NP
            xa(i)=i*PI/NP
            ya(i)=sin(xa(i))
11        continue
          yp1=cos(xa(1))
          ypn=cos(xa(NP))
        else if (nfunc.eq.2) then
          write(*,*) 'Exponential function from 0 to 1'
          do 12 i=1,NP
            xa(i)=1.0*i/NP
            ya(i)=exp(xa(i))
12        continue
          yp1=exp(xa(1))
          ypn=exp(xa(NP))
        else
          stop
        endif
C     call SPLINE to get second derivatives
        call spline(xa,ya,NP,yp1,ypn,y2)
C     call SPLINT for interpolations
        write(*,'(1x,t10,a1,t20,a4,t28,a13)') 'x','f(x)','interpolation'
        do 13 i=1,10
          if (nfunc.eq.1) then
            x=(-0.05+i/10.0)*PI
            f=sin(x)
          else if (nfunc.eq.2) then
            x=-0.05+i/10.0
            f=exp(x)
          endif
          call splint(xa,ya,y2,NP,x,y)
          write(*,'(1x,3f12.6)') x,f,y
13      continue
        write(*,*) '***********************************'
        write(*,*) 'Press RETURN'
        read(*,*)
14    continue
      END

NR-Functions/Numerical Recipes- Example & Functions/Examples/xsplint.for


program simple
  implicit none

  integer :: x
  real    :: t
  real :: v, s, y, fooz
  logical :: check
  real :: foon

  real :: d
  real  :: c

   y = x ** 1 !x * x

  x = 20.0  ! initial
  t = 3.0   !  values
  v = x / t
  s = abs(v)
  d = (y / t) / c

  check = s == v
  if (check) then
     print *, "Velocity is positive"
  endif

  print *, s, square( v )
  call squareS(c, d)
  print *, c, d

contains

  real function square(x)
    real :: x
    square = x * x
  end function square

  subroutine squareS(x, y)
    real :: x, y
    intent(in) :: x
    intent(out) :: y
    y = x * x
  end subroutine squareS

end program


program compute_pi
    use, intrinsic :: iso_fortran_env, only : I8 => INT64
    implicit none
    real, parameter :: PI = acos(-1.0)
    integer(kind=I8), parameter :: nr_tries = 500000000
    integer(kind=I8), codimension[*] :: nr_success
    integer(Kind=I8) :: i
    real :: x, y

    nr_success = 0
    if (this_image() == 1) &
        print '(A, I0, A)', 'running with ', num_images(), ' images'
    do i = 1, nr_tries/num_images()
        call random_number(x)
        call random_number(y)
        if (x**2 + y**2 <= 1.0) nr_success = nr_success + 1
    end do
    sync all
    call co_sum(nr_success, result_image=1)
    if (this_image() == 1) then
        print '(A, F10.7)', 'sampled pi = ', 4.0*real(nr_success)/real(nr_tries)
        print '(A, F10.7)', 'real pi = ', PI
    end if
end program compute_pi


C++ Replace "DZABS" = .Y.//.N.//"ABS"
      DOUBLE PRECISION FUNCTION DZABS(Z)
c Copyright (c) 1996 California Institute of Technology, Pasadena, CA.
c ALL RIGHTS RESERVED.
c Based on Government Sponsored Research NAS7-03001.
C>> 1995-10-30 DZABS  Krogh   Fixed so M77CON can get S.P. for C conv.
C>> 1987-12-07 DZABS  Lawson  Initial code.
C--Z replaces "?":
C
C     Returns sqrt(Z(1)**2 + Z(2)**2)
C     Lawson and Chiu, JPL, Oct 1987
C
      DOUBLE PRECISION Z(2), A, B, ONE, ZERO
      PARAMETER(ONE=1.0D0, ZERO=0.0D0)
C
      A = ABS(Z(1))
      B = ABS(Z(2))
      IF (A .GT. B) THEN
        DZABS = A * SQRT(ONE+(B/A)**2)
      ELSE IF (B .NE. ZERO) THEN
        DZABS = B * SQRT(ONE+(A/B)**2)
      ELSE
        DZABS = ZERO
      END IF
      RETURN
      END


*       This program :calculate Roots of
*       f(x)=exp(x)*ln(x)-x*x
*       by using Bisections

        Dl=1.0E-06
        A=1.0
        B=2.0
        Dx=B-A
        Istep=0
        Do 100while(abs(Dx).GT.Dl)
        X0=(A+B)/2.0
        If(f(A)*f(x0).LT.0)then
        B=x0
        Dx=B-A
        Else
        A=x0
        Dx=B-A
        End If
        Istep=Istep+1
100     End do
        Write(6,999)Istep,x0,Dx
        Stop
999     Format(I4,2F16.8)
        End
        function f(x)
        f=exp(x)*ALOG(x)-x*x
        Return
        End

last28-52009/Example/Root using Bisections/Root using Bisections.f


! The example RHS from VODE

subroutine f_rhs(neq, t, y, ydot)
  use amrex_fort_module, only : rt => amrex_real
  integer, intent(in) :: neq
  real(rt)         t, y(neq), ydot(neq)

  ydot(1) = -.04e0_rt*y(1) + 1.e4_rt*y(2)*y(3)
  ydot(3) = 3.e7_rt*y(2)*y(2)
  ydot(2) = -ydot(1) - ydot(3)

end subroutine f_rhs

subroutine jac(neq, t, y, dfdy)
  integer, intent(in) :: neq
  real(rt)         rpar, t, y(neq), dfdy(neq,neq)
  dfdy(:,:) = 0.0e0_rt

  dfdy(1,1) = -.04e0_rt
  dfdy(1,2) = 1.e4_rt*y(3)
  dfdy(1,3) = 1.e4_rt*y(2)
  dfdy(2,1) = .04e0_rt
  dfdy(2,3) = -dfdy(1,3)
  dfdy(3,2) = 6.e7_rt*y(2)
  dfdy(2,2) = -dfdy(1,2) - dfdy(3,2)

end subroutine jac


subroutine interpolate(vU, qp, qm, order, n)

  implicit none

  integer, intent(in):: n, order

  real*8, dimension(n), intent(in) :: vU
  real*8, dimension(n), intent(out) :: qm
  real*8, dimension(0:n-1), intent(out) :: qp

  !f2py intent(inplace):: vU, qm, qp

  integer:: i

  real*8:: c1,c2,c3, b1, b2, b3, b4, b5, d1, e1,e2

  ! second order
  d1 = 0.5
  ! third order
  c1 = -1./6.
  c2 =  5./6.
  c3 =  2./6.
  ! fourth order
  e1 = -1./12
  e2 = 7./12.
  ! fifth order
  b1 = 2./60.
  b2 = -13./60.
  b3 = 47./60.
  b4 = 27./60.
  b5 = -3./60.

  if (order.eq.5) then
     !
     qp(0) = 0.
     !
     i=1
     qp(i) = vU(i)
     qm(i) = vU(i)
     !
     i=2
     qp(i) = c1*vU(i-1) + c2*vU(i) + c3*vU(i+1)
     qm(i) = c3*vU(i-1) + c2*vU(i) + c1*vU(i+1)
     !
     do i=3,n-3
        qp(i) = b1*vU(i-2) + b2*vU(i-1) + b3*vU(i) + b4*vU(i+1) + b5*vU(i+2)
        qm(i) = b5*vU(i-2) + b4*vU(i-1) + b3*vU(i) + b2*vU(i+1) + b1*vU(i+2)
     enddo
     !
     i=n-2
     qp(i) = c1*vU(i-1) + c2*vU(i) + c3*vU(i+1)
     qm(i) = c3*vU(i-1) + c2*vU(i) + c1*vU(i+1)
     !
     i=n-1
     qp(i) = vU(i)
     qm(i) = vU(i)
     !
     qm(n) = vU(n)
     !
  elseif (order.eq.3) then
     !
     qp(0) = 0.
     !
     i=1
     qp(i) = vU(i)
     qm(i) = vU(i)
     !
     do i=2,n-2
        qp(i) = c1*vU(i-1) + c2*vU(i) + c3*vU(i+1)
        qm(i) = c3*vU(i-1) + c2*vU(i) + c1*vU(i+1)
     enddo
     !
     i=n-1
     qp(i) = vU(i)
     qm(i) = vU(i)
     !
     qm(n) = vu(n)
     !
  !1st order
  elseif (order.eq.1) then
     !
     qp(0) = 0.
     !
     do i=1,n-1
        qp(i) = vU(i)
        qm(i) = vU(i)
     enddo
     !
     qm(n) = vU(n)
     !
  ! 2nd order
  elseif (order.eq.2) then
     qm(1)=0.5*vu(1)
     do i=2,n
        qm(i)=0.5*(vU(i-1)+vU(i))
     enddo
  ! 4th order
  elseif (order.eq.4) then
     i=1
     qm(i)=e2*(vU(i))+e1*(vU(i+1))
     i=2
     qm(i)=e2*(vU(i-1)+vU(i))+e1*(vU(i+1))
     do i=3,n-1
        qm(i)=e2*(vU(i-1)+vU(i))+e1*(vU(i-2)+vU(i+1))
     enddo
     i=n
     qm(i)=e2*(vU(i-1)+vU(i))+e1*(vU(i-2))
  endif

end subroutine interpolate


module m_cardano
  implicit none
contains
  subroutine cardano(a,b,c,x)
    !3次方程式をカルダノの公式により解く
    !x**3 + a*x**2 + b*x + c = 0
    implicit none
    integer :: i
    complex(8),intent(in) :: a,b,c
    complex(8),parameter :: omega = (-1d0 + sqrt(cmplx(-3d0)))/2d0
    complex(8) :: u,v,p,q,d
    complex(8),intent(out) :: x(:)

    p = b/3d0 - a**2/9d0
    q = c/2d0 + a**3/27d0 -a*b/6d0
    d = q**2+p**3
    u = (-cmplx(q) + sqrt(cmplx(d)))**(1d0/3d0)

    if(abs(u) /= 0.0d0) then
      !uv = -p
      v = -cmplx(p)/u

      x(1) = u + v -cmplx(a)/3.0d0
      x(2) = u*omega + v*omega**2 -cmplx(a)/3.0d0
      x(3) = u*omega**2 + v*omega -cmplx(a)/3.0d0
    else
      v = (-cmplx(2*q))**(1.0d0/3.0d0)

      x(1) = v -cmplx(a)/3.0d0
      x(2) = v*omega -cmplx(a)/3.0d0
      x(3) = v*omega**2 -cmplx(a)/3.0d0
    endif
  end subroutine cardano
end module m_cardano


! Mikayla Webber
! 4670 Numerical Analysis
! Homework G Due 12.1.17

! use at least three numerical methods to solve:
! dy/dt = te^(3t) - 2y
! y(0) = 0
! for 0 <= t <= 2
! for each method obtain at least 100 data points on your approximation and produce a graph for each method.

program WebberHomeworkGQuestion2Method1
  implicit none

  integer :: i, neq, nsteps
  double precision :: a, b, dt, tin, tout
  double precision, allocatable, dimension(:, :) :: archive
  double precision, allocatable, dimension(:) :: t, u, f1, yin, yout

  neq = 1
  a = 0.0d0
  b = 2.0d0
  nsteps = 1000 ! at least 100

  allocate(yin(neq), yout(neq), t(0:nsteps), u(neq), f1(neq), archive(neq,0:nsteps))

  dt = ((b - a) / dble(nsteps))

  do i = 0, nsteps
    t(i) = (a + dble(i) * dt)
  end do

  archive (:,0) = (/ 1.0d0, 0.0d0, 0.0d0, 1.0d0 /) ! initial state vector
  yin = archive(:,0)

  do i = 0, (nsteps - 1)
    tin = t(i)
    tout = t(i + 1)
    yin = archive(:,i)
    call computef(neq, tin, yin, f1)
    yout = (yin + (tout - tin) * f1)
    archive(:,i+1) = yout
  end do

  print*, 'Creating "out5.2.1"'
  open(unit=8, file='out5.2.1', status='replace')

  do i = 0, nsteps
    write(8,*) t(i), archive(1,i)
  end do

  close(8)
  deallocate(yin, yout, t, u, f1, archive)

  stop
end program WebberHomeworkGQuestion2Method1

!-----------------------------------------------------------------------

subroutine computef(neq, t, y, f)
  implicit none
  integer :: neq
  double precision :: f(neq)
  double precision, intent(in) :: t, y(neq)
  ! This subroutine computes the RHS of the differential equation:
  !  dy
  !  -- = f(t, y)
  !  dt
  ! where y is the array of unknowns, indexed from one to neq and f is the array of right sides.

  !y(0) = 0
  f(1) = (t * dexp(3.0d0 * t) - 2.0d0 * y(1))

  return
end


PROGRAM se_logistic
! Generate artificial data to see how much bias there is in
! the estimated standard errors.

USE Logistic_Regression
IMPLICIT NONE

REAL (dp)  :: chisq, devnce, beta(0:1), se_beta(0:1), p, z(10), dev,  &
              aver(0:1) = 0.0_dp, sumbb(0:1) = 0.0_dp, aver_se(0:1) = 0.0_dp
INTEGER    :: k, i, case, n(5), s(5), ngroups = 5, ndf, ier
INTEGER, ALLOCATABLE  :: seed(:)
REAL (dp), PARAMETER  :: x(5,1) = RESHAPE(  &
                                  (/ -2.1972_dp, -0.8473_dp, 0.0_dp,  &
                                      0.8473_dp,  2.1972_dp /), (/ 5, 1 /) )

CALL RANDOM_SEED(SIZE=k)
ALLOCATE( seed(k) )

WRITE(*, '(a, i2, a)')' Enter ', k, ' integers for random no. seeds: '
READ(*, *) seed
WRITE(*, '(a, (7i10))') ' Random no. seeds: ', seed
CALL RANDOM_SEED(PUT=seed)

n = 10
DO case = 1, 10000
!     Generate binomial samples from samples of size 10,
!     with p = 0.1, 0.3, 0.5, 0.7 & 0.9
  DO i = 1, 5
    p = 0.1_dp * (2*i - 1)
    CALL RANDOM_NUMBER( z )
    s(i) = COUNT( z < p )
  END DO

  CALL logistic(ngroups, x, 1, s, n, chisq, devnce, ndf, beta, se_beta, ier)

!     Update the average
  dev = beta(0) - aver(0)
  aver(0) = aver(0) + dev/case
  sumbb(0) = sumbb(0) + dev*(beta(0) - aver(0))
  dev = beta(1) - aver(1)
  aver(1) = aver(1) + dev/case
  sumbb(1) = sumbb(1) + dev*(beta(1) - aver(1))
  aver_se = aver_se + (se_beta - aver_se) / case
END DO

sumbb = SQRT( sumbb / 9999. )
WRITE(*, '(a, 2f9.5)') ' Average estimates of beta = ', aver
WRITE(*, '(a, 2f9.5)') ' Std. devn. of sample beta = ', sumbb
WRITE(*, '(a, 2f9.5)') ' Average se_beta           = ', aver_se

STOP
END PROGRAM se_logistic


!*********************************************************
!>
! Collection of statisitcal calculations:
!
! * meanArr - Calculates mean of an array
! * stdDev - Calculates Mean and Std. Deviation
!
! Future:
! * bootstrap, etc.

module statTests
  use randomNumbers
  use sorting
  implicit none

  private
  integer, parameter :: dp = kind(0.d0)

  public :: medianArr
  public :: meanArr
  public :: stdDev
  public :: bootstrap
  public :: jackknife
  public :: chiSqTest

  interface medianArr
    module procedure median_i, median_r, median_d
  end interface

  interface meanArr
    module procedure mean_i, mean_r, mean_d
  end interface

  interface stdDev
    module procedure stdDev_i, stdDev_r, stdDev_d
  end interface

  interface bootstrap
    module procedure bootstrap_i, bootstrap_r, bootstrap_d
  end interface

contains

  real(dp) function median_i(array)
    implicit none
    integer :: n, array(:)

    n = size(array,1)
    if(mod(n,2).eq.0) then
      median_i = array(n/2)
    else
      median_i = (array((n+1)/2-1)+array((n+1)/2+1))/2.d0
    end if
  end function

  real(dp) function median_r(array)
    implicit none
    integer :: n
    real :: array(:)

    n = size(array,1)
    if(mod(n,2).eq.0) then
      median_r = array(n/2)
    else
      median_r = (array((n+1)/2-1)+array((n+1)/2+1))/2.d0
    end if
  end function

  real(dp) function median_d(array)
    implicit none
    integer :: n
    real(dp) :: array(:)

    n = size(array,1)
    if(mod(n,2).eq.0) then
      median_d = array(n/2)
    else
      median_d = (array((n+1)/2-1)+array((n+1)/2+1))/2.d0
    end if
  end function

  real(dp) function mean_i(array)
    implicit none
    integer :: i, n, array(:)
    real(dp) :: arraySum

    n = size(array,1)
    arraySum = 0.d0
    do i=1,n
      arraySum = arraySum+dble(array(i))
    end do
    mean_i = arraySum/dble(n)
  end function

  real(dp) function mean_r(array)
    implicit none
    integer :: i, n
    real :: array(:)
    real(dp) :: arraySum

    n = size(array,1)
    arraySum = 0.d0
    do i=1,n
      arraySum = arraySum+dble(array(i))
    end do
    mean_r = arraySum/dble(n)
  end function

  real(dp) function mean_d(array)
    implicit none
    integer :: i, n
    real(dp) :: array(:), arraySum

    n = size(array,1)
    arraySum = 0.d0
    do i=1,n
      arraySum = arraySum+array(i)
    end do
    mean_d = arraySum/dble(n)
  end function

  subroutine stdDev_i(array, mean, sigma)
    implicit none
    integer :: i, n, array(:)
    real(dp) :: arrayStdDev, mean, sigma

    n = size(array,1)
    mean = meanArr(array)
    arrayStdDev = 0.d0
    do i=1,n
      arrayStdDev = arrayStdDev+(dble(array(i))-mean)* &
          (dble(array(i))-mean)
    end do
    arrayStdDev = arrayStdDev/dble(n)
    sigma = sqrt(arrayStdDev)
  end subroutine

  subroutine stdDev_r(array, mean, sigma)
    implicit none
    integer :: i, n
    real :: array(:)
    real(dp) :: arrayStdDev, mean, sigma

    n = size(array,1)
    mean = meanArr(array)
    arrayStdDev = 0.d0
    do i=1,n
      arrayStdDev = arrayStdDev+(dble(array(i))-mean)* &
          (dble(array(i))-mean)
    end do
    arrayStdDev = arrayStdDev/dble(n)
    sigma = sqrt(arrayStdDev)
  end subroutine

  subroutine stdDev_d(array, mean, sigma)
    implicit none
    integer :: i, n
    real(dp) :: array(:), arrayStdDev, mean, sigma

    n = size(array,1)
    mean = meanArr(array)
    arrayStdDev = 0.d0
    do i=1,n
      arrayStdDev = arrayStdDev+(array(i)-mean)* &
          (array(i)-mean)
    end do
    arrayStdDev = arrayStdDev/dble(n)
    sigma = sqrt(arrayStdDev)
  end subroutine

  subroutine bootstrap_i(array, mean, sigma, nboot)
    implicit none
    integer :: i, n, nboot, boot_i, clock, array(:)
    real(dp) :: mean, sigma, bootMedian(nboot), sum, var
    real(dp), allocatable :: bootArr(:)

    call system_clock(count=clock)
    call randSeedGenerator(clock)
    n = size(array,1)
    sum = 0.d0
    allocate(bootArr(n))
    do boot_i=1,nboot
      do i=1,n
        bootArr(i) = array(xorshift128Int(n)+1)
      end do
      call qsort(bootArr)
      bootMedian(boot_i) = medianArr(bootArr)
      sum = sum + bootMedian(boot_i)
    end do
    deallocate(bootArr)
    mean = sum/real(nboot,dp)
    var = 0.d0
    do boot_i=1,nboot
      var = var + (bootMedian(boot_i)-mean)*(bootMedian(boot_i)-mean)
    end do
    var = var/real(nboot-1,dp)
    sigma = sqrt(var)
  end subroutine

  subroutine bootstrap_r(array, mean, sigma, nboot)
    implicit none
    integer :: i, n, nboot, boot_i, clock
    real :: array(:)
    real(dp) :: mean, sigma, bootMedian(nboot), sum, var
    real(dp), allocatable :: bootArr(:)

    call system_clock(count=clock)
    call randSeedGenerator(clock)
    n = size(array,1)
    sum = 0.d0
    allocate(bootArr(n))
    do boot_i=1,nboot
      do i=1,n
        bootArr(i) = array(xorshift128Int(n)+1)
      end do
      call qsort(bootArr)
      bootMedian(boot_i) = medianArr(bootArr)
      sum = sum + bootMedian(boot_i)
    end do
    deallocate(bootArr)
    mean = sum/real(nboot,dp)
    var = 0.d0
    do boot_i=1,nboot
      var = var + (bootMedian(boot_i)-mean)*(bootMedian(boot_i)-mean)
    end do
    var = var/real(nboot-1,dp)
    sigma = sqrt(var)
  end subroutine

  subroutine bootstrap_d(array, mean, sigma, nboot)
    implicit none
    integer :: i, n, nboot, boot_i, clock
    real(dp) :: array(:), mean, sigma, bootMedian(nboot), sum, var
    real(dp), allocatable :: bootArr(:)

    call system_clock(count=clock)
    call randSeedGenerator(clock)
    n = size(array,1)
    sum = 0.d0
    allocate(bootArr(n))
    do boot_i=1,nboot
      do i=1,n
        bootArr(i) = array(xorshift128Int(n)+1)
      end do
      call qsort(bootArr)
      bootMedian(boot_i) = medianArr(bootArr)
      sum = sum + bootMedian(boot_i)
    end do
    deallocate(bootArr)
    mean = sum/real(nboot,dp)
    var = 0.d0
    do boot_i=1,nboot
      var = var + (bootMedian(boot_i)-mean)*(bootMedian(boot_i)-mean)
    end do
    var = var/real(nboot-1,dp)
    sigma = sqrt(var)
  end subroutine

  subroutine jackknife(array, mean, sigma)
    implicit none
    integer :: i, n
    real(dp) :: array(:), mean, sigma, var, sum
    real(dp), allocatable :: jack_arr(:)

    n = size(array,1)
    sum = 0.d0
    do i=1,n
      sum = sum + array(i)
    end do
    mean = 0.d0
    allocate(jack_arr(n))
    do i=1,n
      jack_arr(i) = sum - array(i)
      jack_arr(i) = jack_arr(i)/real(n-1,dp)
      mean = mean + jack_arr(i)
    end do
    mean = mean/real(n,dp)
    var = 0.d0
    do i=1,n
      var = var + (mean-jack_arr(i))*(mean-jack_arr(i))
    end do
    deallocate(jack_arr)
    var = var*real(n-1,dp)/real(n,dp)
    sigma = sqrt(var)
  end subroutine

  subroutine chiSqTest(array, numBins, startPoint, stopPoint, chiSq)
    implicit none
    integer :: i, n, numBins, binPoint
    real(dp) :: array(:), startPoint, stopPoint, stepPoint, chiSqSum
    real(dp) :: expected, chiSq
    integer, allocatable :: chiSqArray(:)

    n = size(array,1)
    stepPoint = (stopPoint-startPoint)/real(numBins,dp)
    allocate(chiSqArray(numBins))

    expected = real(n,dp)/real(numBins,dp)

    do i=1,numBins
      chiSqArray(i) = 0
    end do

    do i=1,n
      binPoint = int(array(i)/stepPoint)+1
      chiSqArray(binPoint) = chiSqArray(binPoint) + 1
    end do

    chiSqSum = 0d0
    do i=1,numBins
      chiSqSum = chiSqSum + (real(chiSqArray(i),dp)-expected)*(real(chiSqArray(i),dp)-expected)
    end do

    chiSqSum = chiSqSum/expected
    chiSq = chiSqSum
  end subroutine

end module


      MODULE m_diflgr
      CONTAINS
      REAL FUNCTION diflgr(x,f)
c     **********************************************************
c     differentiate the function f,
c     given at the points x0,x1,x2,
c     at the point x1 by lagrange interpolation
c     e.wimmer
c     ***********************************************************
C     .. Array Arguments ..

      IMPLICIT NONE
      REAL f(0:2),x(0:2)
C     ..
      diflgr = (x(1)-x(2))*f(0)/ ((x(0)-x(1))* (x(0)-x(2))) +
     +         (2.0e0*x(1)-x(2)-x(0))*f(1)/ ((x(1)-x(0))* (x(1)-x(2))) +
     +         (x(1)-x(0))*f(2)/ ((x(2)-x(0))* (x(2)-x(1)))
c     print *,'x=',x
c     print *,'f=',f
c     print *,'diflgr=',diflgr
      RETURN
      END FUNCTION
      END


module math_constants

  !

  use program_constants

  implicit none

  public

  ! Geometry
  real(dp), parameter :: deg_per_rad = 57.295779513082320876798155_dp
  real(dp), parameter :: rad_per_deg = 0.017453292519943295769237_dp

  ! Euler's constant e
  real(dp), parameter :: e_value     = 2.718281828459045235360287_dp
  real(dp), parameter :: e_recip     = 0.3678794411714423215955238_dp
  real(dp), parameter :: log10_of_e  = 0.4342944819032518276511289_dp

  ! Euler-Mascheroni constant
  real(dp), parameter :: euler        = 0.577215664901532860606_dp
  real(dp), parameter :: euler_log    = -0.5495393129816448223_dp
  real(dp), parameter :: gamma        = 0.577215664901532860606512_dp
  real(dp), parameter :: gamma_log    = -0.5495393129816448223376612_dp

  ! Golden Ratio
  real(dp), parameter :: golden_ratio = 1.618033988749894848_dp

  ! Logarithms
  real(dp), parameter :: ln_2         = 0.6931471805599453094172321_dp
  real(dp), parameter :: ln_10        = 2.3025850929940456840179915_dp
  real(dp), parameter :: log10_of_2   = 0.3010299956639811952137389_dp

  ! Pi
  real(dp), parameter :: pi_value     = 3.141592653589793238462643_dp
  real(dp), parameter :: pi_ln        = 1.144729885849400174143427_dp
  real(dp), parameter :: pi_log10     = 0.4971498726941338543512683_dp
  real(dp), parameter :: pi_over_2    = 1.570796326794896619231322_dp
  real(dp), parameter :: pi_over_3    = 1.047197551196597746154214_dp
  real(dp), parameter :: pi_over_4    = 0.7853981633974483096156608_dp
  real(dp), parameter :: pi_recip     = 0.3183098861837906715377675_dp
  real(dp), parameter :: pi_squared   = 9.869604401089358618834491_dp
  real(dp), parameter :: pi_sq_root   = 1.772453850905516027298167_dp

  ! Roots
  real(dp), parameter :: sq_root_of_2 = 1.4142135623730950488_dp
  real(dp), parameter :: sq_root_of_3 = 1.7320508075688772935_dp

end module math_constants

!!$program math_test
!!$  use math_constants                   ! access all constants
!!$  real :: pi                           ! define local data type
!!$  print *, 'pi_value: ', pi_value      ! display a constant
!!$  pi = pi_value; print *, 'pi = ', pi  ! convert to lower precision
!!$end program math_test


C
C $Id: bcdp2l.f,v 1.4 2008-07-27 00:17:29 haley Exp $
C
C                Copyright (C)  2000
C        University Corporation for Atmospheric Research
C                All Rights Reserved
C
C The use of this Software is governed by a License Agreement.
C
      REAL FUNCTION BCDP2L(PX,PY,X1,Y1,X2,Y2)
C
C  Calculate the undirected distance from a point (PX,PY) to a line
C  passing through the two points (X1,Y1) and (X2,Y2).  Use the formula
C  for the distance from a point (PX,PY) to a line  A*X+B*Y+C = 0
C  given by:
C
C     ABS(A*PX+B*PY+C)/SQRT(A**2+B**2)
C
      IF (X1 .EQ. X2) THEN
        IF (Y1 .EQ. Y2) THEN
C
C  Return the distance from (PX,PY) to the point (X1,Y1) which is greater
C  than or equal to the distance from (PX,PY) to any line passing through
C  (X1,Y1) = (X2,Y2).
C
          BCDP2L = SQRT((PY-Y1)**2+(PX-X1)**2)
          GO TO 10
        ENDIF
        BCDP2L = ABS(PX-X1)
        GO TO 10
      ELSE
        CONST = (Y1-Y2)/(X2-X1)
        A = CONST
        B = 1.
        C = -(CONST*X1+Y1)
        BCDP2L = ABS(A*PX+B*PY+C)/SQRT(A*A+B*B)
        GO TO 10
      ENDIF
C
   10 CONTINUE
      RETURN
      END


C$Procedure      VSEP  ( Angular separation of vectors, 3 dimensions )

      DOUBLE PRECISION FUNCTION VSEP ( V1, V2 )

C$ Abstract
C
C      Find the separation angle in radians between two double
C      precision, 3-dimensional vectors.  This angle is defined as zero
C      if either vector is zero.
C
C$ Disclaimer
C
C     THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
C     CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
C     GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
C     ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
C     PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
C     TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
C     WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
C     PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
C     SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
C     SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
C
C     IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
C     BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
C     LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
C     INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
C     REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
C     REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
C
C     RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
C     THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
C     CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
C     ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
C
C$ Required_Reading
C
C     None.
C
C$ Keywords
C
C      ANGLE,  VECTOR
C
C$ Declarations

      DOUBLE PRECISION  V1 ( 3 )
      DOUBLE PRECISION  V2 ( 3 )

C$ Brief_I/O
C
C      VARIABLE  I/O  DESCRIPTION
C      --------  ---  --------------------------------------------------
C       V1        I     First vector.
C       V2        I     Second vector.
C
C
C$ Detailed_Input
C
C      V1      is an arbitrary double precision, 3-dimensional vector.
C      V2      is also an arbitrary double precision, 3-dimensional
C              vector.  V1 or V2 or both may be the zero vector.
C
C$ Detailed_Output
C
C      VSEP    is the angle between V1 and V2 expressed in radians.
C              VSEP is strictly non-negative.  If either V1 or V2 is
C              the zero vector, then VSEP is defined to be 0 radians.
C
C$ Parameters
C
C      None.
C
C$ Particulars
C
C      In the plane, it is a simple matter to calculate the angle
C      between two vectors once the two vectors have been made to be
C      unit length.  Then, since the two vectors form the two equal
C      sides of an isosceles triangle, the length of the third side
C      is given by the expression
C
C            LENGTH = 2.0 * SINE ( VSEP/2.0 )
C
C      The length is given by the magnitude of the difference of the
C      two unit vectors
C
C            LENGTH = NORM ( U1 - U2 )
C
C      Once the length is found, the value of VSEP may be calculated
C      by inverting the first expression given above as
C
C            VSEP = 2.0 * ARCSINE ( LENGTH/2.0 )
C
C      This expression becomes increasingly unstable when VSEP gets
C      larger than PI/2 or 90 degrees.  In this situation (which is
C      easily detected by determining the sign of the dot product of
C      V1 and V2) the supplementary angle is calculated first and
C      then VSEP is given by
C
C            VSEP = PI - SUPPLEMENTARY_ANGLE
C
C$ Examples
C
C      The following table gives sample values for V1, V2 and VSEP
C      implied by the inputs.
C
C      V1                        V2                     VSEP
C      ----------------------------------------------------------------
C      (1, 0, 0)                  (1, 0, 0)             0.0D0
C      (1, 0, 0)                  (0, 1, 0)             PI/2 (=1.571...)
C
C
C$ Restrictions
C
C      The user is required to insure that the input vectors will not
C      cause floating point overflow upon calculation of the vector
C      dot product since no error detection or correction code is
C      implemented.  In practice, this is not a significant
C      restriction.
C
C$ Exceptions
C
C     Error free.
C
C$ Files
C
C      None
C
C$ Author_and_Institution
C
C      K.R. Gehringer  (JPL)
C      W.M. Owen       (JPL)
C      W.L. Taber      (JPL)
C
C$ Literature_References
C
C      None
C
C$ Version
C
C-    SPICELIB Version 1.1.1, 17-APR-2006 (EDW)
C
C       Typo correction to the value of PI/2 in the Examples
C       section, 1.571 instead of 1.71.
C
C-    SPICELIB Version 1.1.0, 29-FEB-1996 (KRG)
C
C        The declaration for the SPICELIB function PI is now
C        preceded by an EXTERNAL statement declaring PI to be an
C        external function. This removes a conflict with any
C        compilers that have a PI intrinsic function.
C
C-    SPICELIB Version 1.0.1, 10-MAR-1992 (WLT)
C
C        Comment section for permuted index source lines was added
C        following the header.
C
C-    SPICELIB Version 1.0.0, 31-JAN-1990 (WMO)
C
C-&

C$ Index_Entries
C
C     angular separation of 3-dimensional vectors
C
C-&

C$ Revisions
C
C-    SPICELIB Version 1.1.0, 29-FEB-1996 (KRG)
C
C        The declaration for the SPICELIB function PI is now
C        preceded by an EXTERNAL statement declaring PI to be an
C        external function. This removes a conflict with any
C        compilers that have a PI intrinsic function.
C
C-    SPICELIB Version 1.0.1, 10-MAR-1992 (WLT)
C
C        Comment section for permuted index source lines was added
C        following the header.
C
C-    SPICELIB Version 1.0.0, 31-JAN-1990 (WMO)
C
C-    Beta Version 1.0.1, 10-JAN-1989 (WLT)
C
C     Error free specification added.
C
C-&

C
C     SPICELIB functions
C
      EXTERNAL              PI
      DOUBLE PRECISION      PI
      DOUBLE PRECISION      VDOT
      DOUBLE PRECISION      VNORM
C
C     Local Variables
C
C     The following declarations represent, respectively:
C        Magnitudes of V1, V2
C        Either of the difference vectors: V1-V2 or V1-(-V2)
C        Unit vectors parallel to V1 and V2
C
      DOUBLE PRECISION      DMAG1
      DOUBLE PRECISION      DMAG2
      DOUBLE PRECISION      VTEMP(3)
      DOUBLE PRECISION      U1(3)
      DOUBLE PRECISION      U2(3)
C
C  Calculate the magnitudes of V1 and V2; if either is 0, VSEP = 0
C
      CALL UNORM ( V1, U1, DMAG1 )
      IF ( DMAG1 .EQ. 0.D0 ) THEN
         VSEP = 0.D0
         RETURN
      END IF

      CALL UNORM ( V2, U2, DMAG2 )
      IF ( DMAG2 .EQ. 0.D0 ) THEN
         VSEP = 0.D0
         RETURN
      END IF

      IF      ( VDOT(U1,U2) .GT. 0 ) THEN
         VTEMP(1) = U1(1) - U2(1)
         VTEMP(2) = U1(2) - U2(2)
         VTEMP(3) = U1(3) - U2(3)

         VSEP = 2.0D0 * ASIN (0.5D0 * VNORM(VTEMP))

      ELSE IF ( VDOT(U1,U2) .LT. 0 ) THEN
         VTEMP(1) = U1(1) + U2(1)
         VTEMP(2) = U1(2) + U2(2)
         VTEMP(3) = U1(3) + U2(3)

         VSEP = PI() - 2.0D0 * ASIN (0.5D0 * VNORM(VTEMP))

      ELSE
         VSEP = PI() / 2.0D0
      END IF

      RETURN
      END


FUNCTION disper(g,T,h,n) RESULT(kh)
! By Allan P. Engsig-Karup.
USE Precision
USE Constants
IMPLICIT NONE
INTEGER :: n
REAL(KIND=long) :: g, T, h, kh, w
! determine the dimensionless dispersion parameter kh
! for wave equations using the dispersion relation.
w  = 2*pi/T
kh = w**2*h/g
kh = khsolve(g,w,kh,h,n)

CONTAINS

FUNCTION khsolve(g,w,kh,h,n) RESULT(khout)
! By Allan P. Engsig-Karup.
USE Precision
USE Constants
IMPLICIT NONE
INTEGER :: i, n
REAL(KIND=long) :: g, T, h, kh, w, khout
! to be used within the function disper for iterative solution of dispersion relation
DO i = 1,n
    kh = SQRT(w**2/g*h*kh*COSH(kh)/SINH(kh)) ! COTH(x) = COSH(x)/SINH(x)
END DO
khout = kh
END FUNCTION

END FUNCTION


 ! Find the unique positive integer whose square has the form
 ! 1_2_3_4_5_6_7_8_9_0,
 ! where each "_" is a single digit.
 !
 ! Project Euler: 206
 ! Answer: 1389019170

program main

        use euler

implicit none

        integer (int64) :: i, MIN_RES = 1020304050607080900_i64;

        i = floor(sqrt(dble(MIN_RES)))

        do while(.TRUE.)
                if(concealed_sqr(i*i)) then
                        goto 24;
                endif

                i = i + 1
        end do

24 &
        print *, i

contains

        pure function concealed_sqr(tmp)

                integer (int64), intent(in) :: tmp;
                integer (int64) :: a, i;
                logical :: concealed_sqr;

                concealed_sqr = (mod(tmp, 10) == 0)
                i = tmp / 100;

                a = 9;
                do while(i > 0 .AND. concealed_sqr)
                        concealed_sqr = (mod(i, 10) == a);
                        i = i / 100;
                        a = a - 1;
                end do

        end function concealed_sqr

end program main


module m
implicit none
public :: mean,avg
! older way to have same name for function with multiple ranks
! is an interface with module procedures
interface avg
   module procedure avg_0,avg_1,avg_2
end interface avg
contains
function mean(x) result(y)
real, intent(in) :: x(..) ! assumed rank argument
real             :: y
select rank (x)
   rank (0)     ; y = x ! scalar case
   rank (1)     ; y = sum(x)/max(1,size(x))
   rank (2)     ; y = sum(x)/max(1,size(x))
   rank default ; stop "mean not implemented for rank > 2"
end select
end function mean
!
function avg_0(x) result(y) ! rank 0 argument
real, intent(in) :: x
real             :: y
y = x
end function avg_0
!
function avg_1(x) result(y) ! rank 1 argument
real, intent(in) :: x(:)
real             :: y
y = sum(x)/max(1,size(x))
end function avg_1
!
function avg_2(x) result(y) ! rank 2 argument
real, intent(in) :: x(:,:)
real             :: y
y = sum(x)/max(1,size(x))
end function avg_2
end module m
!
program test_assumed_rank
use m, only: avg  ! interface with module procedures
use m, only: mean ! function with assumed rank argument
implicit none
integer, parameter :: n1 = 1000, n2 = 5
real :: x(n1,n2)
character (len=*), parameter :: fmt="(*(f6.3))"
call random_seed()
call random_number(x)
! demonstrate rank 0, 1, 2 cases
print "(*(a6))","avg","mean","check"
print fmt,avg(x(1,1)),mean(x(1,1)),x(1,1) ! scalar
print fmt,avg(x(:,1)),mean(x(:,1)),sum(x(:,1))/n1 ! 1D
print fmt,avg(x),mean(x),sum(x)/(n1*n2) ! 2D
end program test_assumed_rank
! works with gfortran and Intel Fortran
! sample output:
!    avg  mean check
!  0.662 0.662 0.662
!  0.507 0.507 0.507
!  0.506 0.506 0.506


! { dg-do compile }
!
subroutine test4
  integer, parameter :: wp = 4
  complex(wp), parameter :: i = (0._wp, 1._wp)
  complex(wp) :: c(12)
  integer :: m, N

  N = 12
  c = (/(exp(i*m),m=1,N)/)
  print *, c(1)
end

subroutine test8
  integer, parameter :: wp = 8
  complex(wp), parameter :: i = (0._wp, 1._wp)
  complex(wp) :: c(12)
  integer :: m, N

  N = 12
  c = (/(exp(i*m),m=1,N)/)
  print *, c(1)
end


!> @brief Module containing physical and mathematical constants to be used in KORC.
!! @details In this module we define the constant parameters to be used in KORC. Notice that the numerical precision of these quantities is '_rp', see korc_types.f90.
!! Any new constant needs to be compliant with the numerical precision used in KORC.
module korc_constants
  USE korc_types

  IMPLICIT NONE

  REAL(rp), PARAMETER :: C_PI = 4.0_rp*ATAN(1.0_rp) !< Definition of @f$\pi@f$
  REAL(rp), PARAMETER :: C_E = 1.602176E-19_rp !< Absolute value of electron charge in Coulombs (C).
  REAL(rp), PARAMETER :: C_ME = 9.109382E-31_rp !< Electron mass in kg
  REAL(rp), PARAMETER :: C_MP = 1.672621E-27_rp !< Proton mass in kg
  REAL(rp), PARAMETER :: C_U = 1.660538E-27_rp !< Atomic mass unit in kg
  REAL(rp), PARAMETER :: C_KB = 1.380650E-23_rp !< Boltzmann constant in Joules/Kelvin
  REAL(rp), PARAMETER :: C_C = 299792458.0_rp !< Light speed in m/s
  REAL(rp), PARAMETER :: C_MU = 4.0_rp*C_PI*1E-7_rp !< Vacuum permeability in N/A^2
  REAL(rp), PARAMETER :: C_E0 = 1.0_rp/(C_MU*C_C**2) !< Vacuum permittivity in C^2/(N*m^2)
  REAL(rp), PARAMETER :: C_Ke = 1.0_rp/(4.0_rp*C_PI*C_E0) !< Coulomb constant in N*m^2/C^2
  REAL(rp), PARAMETER :: C_RE = 	C_E**2/( 4.0_rp*C_PI*C_E0*C_ME*C_C**2 ) !< Classical electron radius
  REAL(rp), PARAMETER :: C_h = 6.6261E-34_rp !< Planck constant in Joules*s
  REAL(rp), PARAMETER :: C_a = 1._rp/137._rp !< Fine-structure constant

end module korc_constants


*> \brief \b SCHKGG
*
*  =========== DOCUMENTATION ===========
*
* Online html documentation available at
*            http://www.netlib.org/lapack/explore-html/
*
*  Definition:
*  ===========
*
*       SUBROUTINE SCHKGG( NSIZES, NN, NTYPES, DOTYPE, ISEED, THRESH,
*                          TSTDIF, THRSHN, NOUNIT, A, LDA, B, H, T, S1,
*                          S2, P1, P2, U, LDU, V, Q, Z, ALPHR1, ALPHI1,
*                          BETA1, ALPHR3, ALPHI3, BETA3, EVECTL, EVECTR,
*                          WORK, LWORK, LLWORK, RESULT, INFO )
*
*       .. Scalar Arguments ..
*       LOGICAL            TSTDIF
*       INTEGER            INFO, LDA, LDU, LWORK, NOUNIT, NSIZES, NTYPES
*       REAL               THRESH, THRSHN
*       ..
*       .. Array Arguments ..
*       LOGICAL            DOTYPE( * ), LLWORK( * )
*       INTEGER            ISEED( 4 ), NN( * )
*       REAL               A( LDA, * ), ALPHI1( * ), ALPHI3( * ),
*      $                   ALPHR1( * ), ALPHR3( * ), B( LDA, * ),
*      $                   BETA1( * ), BETA3( * ), EVECTL( LDU, * ),
*      $                   EVECTR( LDU, * ), H( LDA, * ), P1( LDA, * ),
*      $                   P2( LDA, * ), Q( LDU, * ), RESULT( 15 ),
*      $                   S1( LDA, * ), S2( LDA, * ), T( LDA, * ),
*      $                   U( LDU, * ), V( LDU, * ), WORK( * ),
*      $                   Z( LDU, * )
*       ..
*
*
*> \par Purpose:
*  =============
*>
*> \verbatim
*>
*> SCHKGG  checks the nonsymmetric generalized eigenvalue problem
*> routines.
*>                                T          T        T
*> SGGHRD factors A and B as U H V  and U T V , where   means
*> transpose, H is hessenberg, T is triangular and U and V are
*> orthogonal.
*>                                 T          T
*> SHGEQZ factors H and T as  Q S Z  and Q P Z , where P is upper
*> triangular, S is in generalized Schur form (block upper triangular,
*> with 1x1 and 2x2 blocks on the diagonal, the 2x2 blocks
*> corresponding to complex conjugate pairs of generalized
*> eigenvalues), and Q and Z are orthogonal.  It also computes the
*> generalized eigenvalues (alpha(1),beta(1)),...,(alpha(n),beta(n)),
*> where alpha(j)=S(j,j) and beta(j)=P(j,j) -- thus,
*> w(j) = alpha(j)/beta(j) is a root of the generalized eigenvalue
*> problem
*>
*>     det( A - w(j) B ) = 0
*>
*> and m(j) = beta(j)/alpha(j) is a root of the essentially equivalent
*> problem
*>
*>     det( m(j) A - B ) = 0
*>
*> STGEVC computes the matrix L of left eigenvectors and the matrix R
*> of right eigenvectors for the matrix pair ( S, P ).  In the
*> description below,  l and r are left and right eigenvectors
*> corresponding to the generalized eigenvalues (alpha,beta).
*>
*> When SCHKGG is called, a number of matrix "sizes" ("n's") and a
*> number of matrix "types" are specified.  For each size ("n")
*> and each type of matrix, one matrix will be generated and used
*> to test the nonsymmetric eigenroutines.  For each matrix, 15
*> tests will be performed.  The first twelve "test ratios" should be
*> small -- O(1).  They will be compared with the threshhold THRESH:
*>
*>                  T
*> (1)   | A - U H V  | / ( |A| n ulp )
*>
*>                  T
*> (2)   | B - U T V  | / ( |B| n ulp )
*>
*>               T
*> (3)   | I - UU  | / ( n ulp )
*>
*>               T
*> (4)   | I - VV  | / ( n ulp )
*>
*>                  T
*> (5)   | H - Q S Z  | / ( |H| n ulp )
*>
*>                  T
*> (6)   | T - Q P Z  | / ( |T| n ulp )
*>
*>               T
*> (7)   | I - QQ  | / ( n ulp )
*>
*>               T
*> (8)   | I - ZZ  | / ( n ulp )
*>
*> (9)   max over all left eigenvalue/-vector pairs (beta/alpha,l) of
*>
*>    | l**H * (beta S - alpha P) | / ( ulp max( |beta S|, |alpha P| ) )
*>
*> (10)  max over all left eigenvalue/-vector pairs (beta/alpha,l') of
*>                           T
*>   | l'**H * (beta H - alpha T) | / ( ulp max( |beta H|, |alpha T| ) )
*>
*>       where the eigenvectors l' are the result of passing Q to
*>       STGEVC and back transforming (HOWMNY='B').
*>
*> (11)  max over all right eigenvalue/-vector pairs (beta/alpha,r) of
*>
*>       | (beta S - alpha T) r | / ( ulp max( |beta S|, |alpha T| ) )
*>
*> (12)  max over all right eigenvalue/-vector pairs (beta/alpha,r') of
*>
*>       | (beta H - alpha T) r' | / ( ulp max( |beta H|, |alpha T| ) )
*>
*>       where the eigenvectors r' are the result of passing Z to
*>       STGEVC and back transforming (HOWMNY='B').
*>
*> The last three test ratios will usually be small, but there is no
*> mathematical requirement that they be so.  They are therefore
*> compared with THRESH only if TSTDIF is .TRUE.
*>
*> (13)  | S(Q,Z computed) - S(Q,Z not computed) | / ( |S| ulp )
*>
*> (14)  | P(Q,Z computed) - P(Q,Z not computed) | / ( |P| ulp )
*>
*> (15)  max( |alpha(Q,Z computed) - alpha(Q,Z not computed)|/|S| ,
*>            |beta(Q,Z computed) - beta(Q,Z not computed)|/|P| ) / ulp
*>
*> In addition, the normalization of L and R are checked, and compared
*> with the threshhold THRSHN.
*>
*> Test Matrices
*> ---- --------
*>
*> The sizes of the test matrices are specified by an array
*> NN(1:NSIZES); the value of each element NN(j) specifies one size.
*> The "types" are specified by a logical array DOTYPE( 1:NTYPES ); if
*> DOTYPE(j) is .TRUE., then matrix type "j" will be generated.
*> Currently, the list of possible types is:
*>
*> (1)  ( 0, 0 )         (a pair of zero matrices)
*>
*> (2)  ( I, 0 )         (an identity and a zero matrix)
*>
*> (3)  ( 0, I )         (an identity and a zero matrix)
*>
*> (4)  ( I, I )         (a pair of identity matrices)
*>
*>         t   t
*> (5)  ( J , J  )       (a pair of transposed Jordan blocks)
*>
*>                                     t                ( I   0  )
*> (6)  ( X, Y )         where  X = ( J   0  )  and Y = (      t )
*>                                  ( 0   I  )          ( 0   J  )
*>                       and I is a k x k identity and J a (k+1)x(k+1)
*>                       Jordan block; k=(N-1)/2
*>
*> (7)  ( D, I )         where D is diag( 0, 1,..., N-1 ) (a diagonal
*>                       matrix with those diagonal entries.)
*> (8)  ( I, D )
*>
*> (9)  ( big*D, small*I ) where "big" is near overflow and small=1/big
*>
*> (10) ( small*D, big*I )
*>
*> (11) ( big*I, small*D )
*>
*> (12) ( small*I, big*D )
*>
*> (13) ( big*D, big*I )
*>
*> (14) ( small*D, small*I )
*>
*> (15) ( D1, D2 )        where D1 is diag( 0, 0, 1, ..., N-3, 0 ) and
*>                        D2 is diag( 0, N-3, N-4,..., 1, 0, 0 )
*>           t   t
*> (16) U ( J , J ) V     where U and V are random orthogonal matrices.
*>
*> (17) U ( T1, T2 ) V    where T1 and T2 are upper triangular matrices
*>                        with random O(1) entries above the diagonal
*>                        and diagonal entries diag(T1) =
*>                        ( 0, 0, 1, ..., N-3, 0 ) and diag(T2) =
*>                        ( 0, N-3, N-4,..., 1, 0, 0 )
*>
*> (18) U ( T1, T2 ) V    diag(T1) = ( 0, 0, 1, 1, s, ..., s, 0 )
*>                        diag(T2) = ( 0, 1, 0, 1,..., 1, 0 )
*>                        s = machine precision.
*>
*> (19) U ( T1, T2 ) V    diag(T1)=( 0,0,1,1, 1-d, ..., 1-(N-5)*d=s, 0 )
*>                        diag(T2) = ( 0, 1, 0, 1, ..., 1, 0 )
*>
*>                                                        N-5
*> (20) U ( T1, T2 ) V    diag(T1)=( 0, 0, 1, 1, a, ..., a   =s, 0 )
*>                        diag(T2) = ( 0, 1, 0, 1, ..., 1, 0, 0 )
*>
*> (21) U ( T1, T2 ) V    diag(T1)=( 0, 0, 1, r1, r2, ..., r(N-4), 0 )
*>                        diag(T2) = ( 0, 1, 0, 1, ..., 1, 0, 0 )
*>                        where r1,..., r(N-4) are random.
*>
*> (22) U ( big*T1, small*T2 ) V    diag(T1) = ( 0, 0, 1, ..., N-3, 0 )
*>                                  diag(T2) = ( 0, 1, ..., 1, 0, 0 )
*>
*> (23) U ( small*T1, big*T2 ) V    diag(T1) = ( 0, 0, 1, ..., N-3, 0 )
*>                                  diag(T2) = ( 0, 1, ..., 1, 0, 0 )
*>
*> (24) U ( small*T1, small*T2 ) V  diag(T1) = ( 0, 0, 1, ..., N-3, 0 )
*>                                  diag(T2) = ( 0, 1, ..., 1, 0, 0 )
*>
*> (25) U ( big*T1, big*T2 ) V      diag(T1) = ( 0, 0, 1, ..., N-3, 0 )
*>                                  diag(T2) = ( 0, 1, ..., 1, 0, 0 )
*>
*> (26) U ( T1, T2 ) V     where T1 and T2 are random upper-triangular
*>                         matrices.
*> \endverbatim
*
*  Arguments:
*  ==========
*
*> \param[in] NSIZES
*> \verbatim
*>          NSIZES is INTEGER
*>          The number of sizes of matrices to use.  If it is zero,
*>          SCHKGG does nothing.  It must be at least zero.
*> \endverbatim
*>
*> \param[in] NN
*> \verbatim
*>          NN is INTEGER array, dimension (NSIZES)
*>          An array containing the sizes to be used for the matrices.
*>          Zero values will be skipped.  The values must be at least
*>          zero.
*> \endverbatim
*>
*> \param[in] NTYPES
*> \verbatim
*>          NTYPES is INTEGER
*>          The number of elements in DOTYPE.   If it is zero, SCHKGG
*>          does nothing.  It must be at least zero.  If it is MAXTYP+1
*>          and NSIZES is 1, then an additional type, MAXTYP+1 is
*>          defined, which is to use whatever matrix is in A.  This
*>          is only useful if DOTYPE(1:MAXTYP) is .FALSE. and
*>          DOTYPE(MAXTYP+1) is .TRUE. .
*> \endverbatim
*>
*> \param[in] DOTYPE
*> \verbatim
*>          DOTYPE is LOGICAL array, dimension (NTYPES)
*>          If DOTYPE(j) is .TRUE., then for each size in NN a
*>          matrix of that size and of type j will be generated.
*>          If NTYPES is smaller than the maximum number of types
*>          defined (PARAMETER MAXTYP), then types NTYPES+1 through
*>          MAXTYP will not be generated.  If NTYPES is larger
*>          than MAXTYP, DOTYPE(MAXTYP+1) through DOTYPE(NTYPES)
*>          will be ignored.
*> \endverbatim
*>
*> \param[in,out] ISEED
*> \verbatim
*>          ISEED is INTEGER array, dimension (4)
*>          On entry ISEED specifies the seed of the random number
*>          generator. The array elements should be between 0 and 4095;
*>          if not they will be reduced mod 4096.  Also, ISEED(4) must
*>          be odd.  The random number generator uses a linear
*>          congruential sequence limited to small integers, and so
*>          should produce machine independent random numbers. The
*>          values of ISEED are changed on exit, and can be used in the
*>          next call to SCHKGG to continue the same random number
*>          sequence.
*> \endverbatim
*>
*> \param[in] THRESH
*> \verbatim
*>          THRESH is REAL
*>          A test will count as "failed" if the "error", computed as
*>          described above, exceeds THRESH.  Note that the error is
*>          scaled to be O(1), so THRESH should be a reasonably small
*>          multiple of 1, e.g., 10 or 100.  In particular, it should
*>          not depend on the precision (single vs. double) or the size
*>          of the matrix.  It must be at least zero.
*> \endverbatim
*>
*> \param[in] TSTDIF
*> \verbatim
*>          TSTDIF is LOGICAL
*>          Specifies whether test ratios 13-15 will be computed and
*>          compared with THRESH.
*>          = .FALSE.: Only test ratios 1-12 will be computed and tested.
*>                     Ratios 13-15 will be set to zero.
*>          = .TRUE.:  All the test ratios 1-15 will be computed and
*>                     tested.
*> \endverbatim
*>
*> \param[in] THRSHN
*> \verbatim
*>          THRSHN is REAL
*>          Threshhold for reporting eigenvector normalization error.
*>          If the normalization of any eigenvector differs from 1 by
*>          more than THRSHN*ulp, then a special error message will be
*>          printed.  (This is handled separately from the other tests,
*>          since only a compiler or programming error should cause an
*>          error message, at least if THRSHN is at least 5--10.)
*> \endverbatim
*>
*> \param[in] NOUNIT
*> \verbatim
*>          NOUNIT is INTEGER
*>          The FORTRAN unit number for printing out error messages
*>          (e.g., if a routine returns IINFO not equal to 0.)
*> \endverbatim
*>
*> \param[in,out] A
*> \verbatim
*>          A is REAL array, dimension
*>                            (LDA, max(NN))
*>          Used to hold the original A matrix.  Used as input only
*>          if NTYPES=MAXTYP+1, DOTYPE(1:MAXTYP)=.FALSE., and
*>          DOTYPE(MAXTYP+1)=.TRUE.
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*>          LDA is INTEGER
*>          The leading dimension of A, B, H, T, S1, P1, S2, and P2.
*>          It must be at least 1 and at least max( NN ).
*> \endverbatim
*>
*> \param[in,out] B
*> \verbatim
*>          B is REAL array, dimension
*>                            (LDA, max(NN))
*>          Used to hold the original B matrix.  Used as input only
*>          if NTYPES=MAXTYP+1, DOTYPE(1:MAXTYP)=.FALSE., and
*>          DOTYPE(MAXTYP+1)=.TRUE.
*> \endverbatim
*>
*> \param[out] H
*> \verbatim
*>          H is REAL array, dimension (LDA, max(NN))
*>          The upper Hessenberg matrix computed from A by SGGHRD.
*> \endverbatim
*>
*> \param[out] T
*> \verbatim
*>          T is REAL array, dimension (LDA, max(NN))
*>          The upper triangular matrix computed from B by SGGHRD.
*> \endverbatim
*>
*> \param[out] S1
*> \verbatim
*>          S1 is REAL array, dimension (LDA, max(NN))
*>          The Schur (block upper triangular) matrix computed from H by
*>          SHGEQZ when Q and Z are also computed.
*> \endverbatim
*>
*> \param[out] S2
*> \verbatim
*>          S2 is REAL array, dimension (LDA, max(NN))
*>          The Schur (block upper triangular) matrix computed from H by
*>          SHGEQZ when Q and Z are not computed.
*> \endverbatim
*>
*> \param[out] P1
*> \verbatim
*>          P1 is REAL array, dimension (LDA, max(NN))
*>          The upper triangular matrix computed from T by SHGEQZ
*>          when Q and Z are also computed.
*> \endverbatim
*>
*> \param[out] P2
*> \verbatim
*>          P2 is REAL array, dimension (LDA, max(NN))
*>          The upper triangular matrix computed from T by SHGEQZ
*>          when Q and Z are not computed.
*> \endverbatim
*>
*> \param[out] U
*> \verbatim
*>          U is REAL array, dimension (LDU, max(NN))
*>          The (left) orthogonal matrix computed by SGGHRD.
*> \endverbatim
*>
*> \param[in] LDU
*> \verbatim
*>          LDU is INTEGER
*>          The leading dimension of U, V, Q, Z, EVECTL, and EVECTR.  It
*>          must be at least 1 and at least max( NN ).
*> \endverbatim
*>
*> \param[out] V
*> \verbatim
*>          V is REAL array, dimension (LDU, max(NN))
*>          The (right) orthogonal matrix computed by SGGHRD.
*> \endverbatim
*>
*> \param[out] Q
*> \verbatim
*>          Q is REAL array, dimension (LDU, max(NN))
*>          The (left) orthogonal matrix computed by SHGEQZ.
*> \endverbatim
*>
*> \param[out] Z
*> \verbatim
*>          Z is REAL array, dimension (LDU, max(NN))
*>          The (left) orthogonal matrix computed by SHGEQZ.
*> \endverbatim
*>
*> \param[out] ALPHR1
*> \verbatim
*>          ALPHR1 is REAL array, dimension (max(NN))
*> \endverbatim
*>
*> \param[out] ALPHI1
*> \verbatim
*>          ALPHI1 is REAL array, dimension (max(NN))
*> \endverbatim
*>
*> \param[out] BETA1
*> \verbatim
*>          BETA1 is REAL array, dimension (max(NN))
*>
*>          The generalized eigenvalues of (A,B) computed by SHGEQZ
*>          when Q, Z, and the full Schur matrices are computed.
*>          On exit, ( ALPHR1(k)+ALPHI1(k)*i ) / BETA1(k) is the k-th
*>          generalized eigenvalue of the matrices in A and B.
*> \endverbatim
*>
*> \param[out] ALPHR3
*> \verbatim
*>          ALPHR3 is REAL array, dimension (max(NN))
*> \endverbatim
*>
*> \param[out] ALPHI3
*> \verbatim
*>          ALPHI3 is REAL array, dimension (max(NN))
*> \endverbatim
*>
*> \param[out] BETA3
*> \verbatim
*>          BETA3 is REAL array, dimension (max(NN))
*> \endverbatim
*>
*> \param[out] EVECTL
*> \verbatim
*>          EVECTL is REAL array, dimension (LDU, max(NN))
*>          The (block lower triangular) left eigenvector matrix for
*>          the matrices in S1 and P1.  (See STGEVC for the format.)
*> \endverbatim
*>
*> \param[out] EVECTR
*> \verbatim
*>          EVECTR is REAL array, dimension (LDU, max(NN))
*>          The (block upper triangular) right eigenvector matrix for
*>          the matrices in S1 and P1.  (See STGEVC for the format.)
*> \endverbatim
*>
*> \param[out] WORK
*> \verbatim
*>          WORK is REAL array, dimension (LWORK)
*> \endverbatim
*>
*> \param[in] LWORK
*> \verbatim
*>          LWORK is INTEGER
*>          The number of entries in WORK.  This must be at least
*>          max( 2 * N**2, 6*N, 1 ), for all N=NN(j).
*> \endverbatim
*>
*> \param[out] LLWORK
*> \verbatim
*>          LLWORK is LOGICAL array, dimension (max(NN))
*> \endverbatim
*>
*> \param[out] RESULT
*> \verbatim
*>          RESULT is REAL array, dimension (15)
*>          The values computed by the tests described above.
*>          The values are currently limited to 1/ulp, to avoid
*>          overflow.
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*>          INFO is INTEGER
*>          = 0:  successful exit
*>          < 0:  if INFO = -i, the i-th argument had an illegal value
*>          > 0:  A routine returned an error code.  INFO is the
*>                absolute value of the INFO value returned.
*> \endverbatim
*
*  Authors:
*  ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup single_eig
*
*  =====================================================================
      SUBROUTINE SCHKGG( NSIZES, NN, NTYPES, DOTYPE, ISEED, THRESH,
     $                   TSTDIF, THRSHN, NOUNIT, A, LDA, B, H, T, S1,
     $                   S2, P1, P2, U, LDU, V, Q, Z, ALPHR1, ALPHI1,
     $                   BETA1, ALPHR3, ALPHI3, BETA3, EVECTL, EVECTR,
     $                   WORK, LWORK, LLWORK, RESULT, INFO )
*
*  -- LAPACK test routine (version 3.4.0) --
*  -- LAPACK is a software package provided by Univ. of Tennessee,    --
*  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*     November 2011
*
*     .. Scalar Arguments ..
      LOGICAL            TSTDIF
      INTEGER            INFO, LDA, LDU, LWORK, NOUNIT, NSIZES, NTYPES
      REAL               THRESH, THRSHN
*     ..
*     .. Array Arguments ..
      LOGICAL            DOTYPE( * ), LLWORK( * )
      INTEGER            ISEED( 4 ), NN( * )
      REAL               A( LDA, * ), ALPHI1( * ), ALPHI3( * ),
     $                   ALPHR1( * ), ALPHR3( * ), B( LDA, * ),
     $                   BETA1( * ), BETA3( * ), EVECTL( LDU, * ),
     $                   EVECTR( LDU, * ), H( LDA, * ), P1( LDA, * ),
     $                   P2( LDA, * ), Q( LDU, * ), RESULT( 15 ),
     $                   S1( LDA, * ), S2( LDA, * ), T( LDA, * ),
     $                   U( LDU, * ), V( LDU, * ), WORK( * ),
     $                   Z( LDU, * )
*     ..
*
*  =====================================================================
*
*     .. Parameters ..
      REAL               ZERO, ONE
      PARAMETER          ( ZERO = 0.0, ONE = 1.0 )
      INTEGER            MAXTYP
      PARAMETER          ( MAXTYP = 26 )
*     ..
*     .. Local Scalars ..
      LOGICAL            BADNN
      INTEGER            I1, IADD, IINFO, IN, J, JC, JR, JSIZE, JTYPE,
     $                   LWKOPT, MTYPES, N, N1, NERRS, NMATS, NMAX,
     $                   NTEST, NTESTT
      REAL               ANORM, BNORM, SAFMAX, SAFMIN, TEMP1, TEMP2,
     $                   ULP, ULPINV
*     ..
*     .. Local Arrays ..
      INTEGER            IASIGN( MAXTYP ), IBSIGN( MAXTYP ),
     $                   IOLDSD( 4 ), KADD( 6 ), KAMAGN( MAXTYP ),
     $                   KATYPE( MAXTYP ), KAZERO( MAXTYP ),
     $                   KBMAGN( MAXTYP ), KBTYPE( MAXTYP ),
     $                   KBZERO( MAXTYP ), KCLASS( MAXTYP ),
     $                   KTRIAN( MAXTYP ), KZ1( 6 ), KZ2( 6 )
      REAL               DUMMA( 4 ), RMAGN( 0: 3 )
*     ..
*     .. External Functions ..
      REAL               SLAMCH, SLANGE, SLARND
      EXTERNAL           SLAMCH, SLANGE, SLARND
*     ..
*     .. External Subroutines ..
      EXTERNAL           SGEQR2, SGET51, SGET52, SGGHRD, SHGEQZ, SLABAD,
     $                   SLACPY, SLARFG, SLASET, SLASUM, SLATM4, SORM2R,
     $                   STGEVC, XERBLA
*     ..
*     .. Intrinsic Functions ..
      INTRINSIC          ABS, MAX, MIN, REAL, SIGN
*     ..
*     .. Data statements ..
      DATA               KCLASS / 15*1, 10*2, 1*3 /
      DATA               KZ1 / 0, 1, 2, 1, 3, 3 /
      DATA               KZ2 / 0, 0, 1, 2, 1, 1 /
      DATA               KADD / 0, 0, 0, 0, 3, 2 /
      DATA               KATYPE / 0, 1, 0, 1, 2, 3, 4, 1, 4, 4, 1, 1, 4,
     $                   4, 4, 2, 4, 5, 8, 7, 9, 4*4, 0 /
      DATA               KBTYPE / 0, 0, 1, 1, 2, -3, 1, 4, 1, 1, 4, 4,
     $                   1, 1, -4, 2, -4, 8*8, 0 /
      DATA               KAZERO / 6*1, 2, 1, 2*2, 2*1, 2*2, 3, 1, 3,
     $                   4*5, 4*3, 1 /
      DATA               KBZERO / 6*1, 1, 2, 2*1, 2*2, 2*1, 4, 1, 4,
     $                   4*6, 4*4, 1 /
      DATA               KAMAGN / 8*1, 2, 3, 2, 3, 2, 3, 7*1, 2, 3, 3,
     $                   2, 1 /
      DATA               KBMAGN / 8*1, 3, 2, 3, 2, 2, 3, 7*1, 3, 2, 3,
     $                   2, 1 /
      DATA               KTRIAN / 16*0, 10*1 /
      DATA               IASIGN / 6*0, 2, 0, 2*2, 2*0, 3*2, 0, 2, 3*0,
     $                   5*2, 0 /
      DATA               IBSIGN / 7*0, 2, 2*0, 2*2, 2*0, 2, 0, 2, 9*0 /
*     ..
*     .. Executable Statements ..
*
*     Check for errors
*
      INFO = 0
*
      BADNN = .FALSE.
      NMAX = 1
      DO 10 J = 1, NSIZES
         NMAX = MAX( NMAX, NN( J ) )
         IF( NN( J ).LT.0 )
     $      BADNN = .TRUE.
   10 CONTINUE
*
*     Maximum blocksize and shift -- we assume that blocksize and number
*     of shifts are monotone increasing functions of N.
*
      LWKOPT = MAX( 6*NMAX, 2*NMAX*NMAX, 1 )
*
*     Check for errors
*
      IF( NSIZES.LT.0 ) THEN
         INFO = -1
      ELSE IF( BADNN ) THEN
         INFO = -2
      ELSE IF( NTYPES.LT.0 ) THEN
         INFO = -3
      ELSE IF( THRESH.LT.ZERO ) THEN
         INFO = -6
      ELSE IF( LDA.LE.1 .OR. LDA.LT.NMAX ) THEN
         INFO = -10
      ELSE IF( LDU.LE.1 .OR. LDU.LT.NMAX ) THEN
         INFO = -19
      ELSE IF( LWKOPT.GT.LWORK ) THEN
         INFO = -30
      END IF
*
      IF( INFO.NE.0 ) THEN
         CALL XERBLA( 'SCHKGG', -INFO )
         RETURN
      END IF
*
*     Quick return if possible
*
      IF( NSIZES.EQ.0 .OR. NTYPES.EQ.0 )
     $   RETURN
*
      SAFMIN = SLAMCH( 'Safe minimum' )
      ULP = SLAMCH( 'Epsilon' )*SLAMCH( 'Base' )
      SAFMIN = SAFMIN / ULP
      SAFMAX = ONE / SAFMIN
      CALL SLABAD( SAFMIN, SAFMAX )
      ULPINV = ONE / ULP
*
*     The values RMAGN(2:3) depend on N, see below.
*
      RMAGN( 0 ) = ZERO
      RMAGN( 1 ) = ONE
*
*     Loop over sizes, types
*
      NTESTT = 0
      NERRS = 0
      NMATS = 0
*
      DO 240 JSIZE = 1, NSIZES
         N = NN( JSIZE )
         N1 = MAX( 1, N )
         RMAGN( 2 ) = SAFMAX*ULP / REAL( N1 )
         RMAGN( 3 ) = SAFMIN*ULPINV*N1
*
         IF( NSIZES.NE.1 ) THEN
            MTYPES = MIN( MAXTYP, NTYPES )
         ELSE
            MTYPES = MIN( MAXTYP+1, NTYPES )
         END IF
*
         DO 230 JTYPE = 1, MTYPES
            IF( .NOT.DOTYPE( JTYPE ) )
     $         GO TO 230
            NMATS = NMATS + 1
            NTEST = 0
*
*           Save ISEED in case of an error.
*
            DO 20 J = 1, 4
               IOLDSD( J ) = ISEED( J )
   20       CONTINUE
*
*           Initialize RESULT
*
            DO 30 J = 1, 15
               RESULT( J ) = ZERO
   30       CONTINUE
*
*           Compute A and B
*
*           Description of control parameters:
*
*           KCLASS: =1 means w/o rotation, =2 means w/ rotation,
*                   =3 means random.
*           KATYPE: the "type" to be passed to SLATM4 for computing A.
*           KAZERO: the pattern of zeros on the diagonal for A:
*                   =1: ( xxx ), =2: (0, xxx ) =3: ( 0, 0, xxx, 0 ),
*                   =4: ( 0, xxx, 0, 0 ), =5: ( 0, 0, 1, xxx, 0 ),
*                   =6: ( 0, 1, 0, xxx, 0 ).  (xxx means a string of
*                   non-zero entries.)
*           KAMAGN: the magnitude of the matrix: =0: zero, =1: O(1),
*                   =2: large, =3: small.
*           IASIGN: 1 if the diagonal elements of A are to be
*                   multiplied by a random magnitude 1 number, =2 if
*                   randomly chosen diagonal blocks are to be rotated
*                   to form 2x2 blocks.
*           KBTYPE, KBZERO, KBMAGN, IBSIGN: the same, but for B.
*           KTRIAN: =0: don't fill in the upper triangle, =1: do.
*           KZ1, KZ2, KADD: used to implement KAZERO and KBZERO.
*           RMAGN: used to implement KAMAGN and KBMAGN.
*
            IF( MTYPES.GT.MAXTYP )
     $         GO TO 110
            IINFO = 0
            IF( KCLASS( JTYPE ).LT.3 ) THEN
*
*              Generate A (w/o rotation)
*
               IF( ABS( KATYPE( JTYPE ) ).EQ.3 ) THEN
                  IN = 2*( ( N-1 ) / 2 ) + 1
                  IF( IN.NE.N )
     $               CALL SLASET( 'Full', N, N, ZERO, ZERO, A, LDA )
               ELSE
                  IN = N
               END IF
               CALL SLATM4( KATYPE( JTYPE ), IN, KZ1( KAZERO( JTYPE ) ),
     $                      KZ2( KAZERO( JTYPE ) ), IASIGN( JTYPE ),
     $                      RMAGN( KAMAGN( JTYPE ) ), ULP,
     $                      RMAGN( KTRIAN( JTYPE )*KAMAGN( JTYPE ) ), 2,
     $                      ISEED, A, LDA )
               IADD = KADD( KAZERO( JTYPE ) )
               IF( IADD.GT.0 .AND. IADD.LE.N )
     $            A( IADD, IADD ) = RMAGN( KAMAGN( JTYPE ) )
*
*              Generate B (w/o rotation)
*
               IF( ABS( KBTYPE( JTYPE ) ).EQ.3 ) THEN
                  IN = 2*( ( N-1 ) / 2 ) + 1
                  IF( IN.NE.N )
     $               CALL SLASET( 'Full', N, N, ZERO, ZERO, B, LDA )
               ELSE
                  IN = N
               END IF
               CALL SLATM4( KBTYPE( JTYPE ), IN, KZ1( KBZERO( JTYPE ) ),
     $                      KZ2( KBZERO( JTYPE ) ), IBSIGN( JTYPE ),
     $                      RMAGN( KBMAGN( JTYPE ) ), ONE,
     $                      RMAGN( KTRIAN( JTYPE )*KBMAGN( JTYPE ) ), 2,
     $                      ISEED, B, LDA )
               IADD = KADD( KBZERO( JTYPE ) )
               IF( IADD.NE.0 .AND. IADD.LE.N )
     $            B( IADD, IADD ) = RMAGN( KBMAGN( JTYPE ) )
*
               IF( KCLASS( JTYPE ).EQ.2 .AND. N.GT.0 ) THEN
*
*                 Include rotations
*
*                 Generate U, V as Householder transformations times
*                 a diagonal matrix.
*
                  DO 50 JC = 1, N - 1
                     DO 40 JR = JC, N
                        U( JR, JC ) = SLARND( 3, ISEED )
                        V( JR, JC ) = SLARND( 3, ISEED )
   40                CONTINUE
                     CALL SLARFG( N+1-JC, U( JC, JC ), U( JC+1, JC ), 1,
     $                            WORK( JC ) )
                     WORK( 2*N+JC ) = SIGN( ONE, U( JC, JC ) )
                     U( JC, JC ) = ONE
                     CALL SLARFG( N+1-JC, V( JC, JC ), V( JC+1, JC ), 1,
     $                            WORK( N+JC ) )
                     WORK( 3*N+JC ) = SIGN( ONE, V( JC, JC ) )
                     V( JC, JC ) = ONE
   50             CONTINUE
                  U( N, N ) = ONE
                  WORK( N ) = ZERO
                  WORK( 3*N ) = SIGN( ONE, SLARND( 2, ISEED ) )
                  V( N, N ) = ONE
                  WORK( 2*N ) = ZERO
                  WORK( 4*N ) = SIGN( ONE, SLARND( 2, ISEED ) )
*
*                 Apply the diagonal matrices
*
                  DO 70 JC = 1, N
                     DO 60 JR = 1, N
                        A( JR, JC ) = WORK( 2*N+JR )*WORK( 3*N+JC )*
     $                                A( JR, JC )
                        B( JR, JC ) = WORK( 2*N+JR )*WORK( 3*N+JC )*
     $                                B( JR, JC )
   60                CONTINUE
   70             CONTINUE
                  CALL SORM2R( 'L', 'N', N, N, N-1, U, LDU, WORK, A,
     $                         LDA, WORK( 2*N+1 ), IINFO )
                  IF( IINFO.NE.0 )
     $               GO TO 100
                  CALL SORM2R( 'R', 'T', N, N, N-1, V, LDU, WORK( N+1 ),
     $                         A, LDA, WORK( 2*N+1 ), IINFO )
                  IF( IINFO.NE.0 )
     $               GO TO 100
                  CALL SORM2R( 'L', 'N', N, N, N-1, U, LDU, WORK, B,
     $                         LDA, WORK( 2*N+1 ), IINFO )
                  IF( IINFO.NE.0 )
     $               GO TO 100
                  CALL SORM2R( 'R', 'T', N, N, N-1, V, LDU, WORK( N+1 ),
     $                         B, LDA, WORK( 2*N+1 ), IINFO )
                  IF( IINFO.NE.0 )
     $               GO TO 100
               END IF
            ELSE
*
*              Random matrices
*
               DO 90 JC = 1, N
                  DO 80 JR = 1, N
                     A( JR, JC ) = RMAGN( KAMAGN( JTYPE ) )*
     $                             SLARND( 2, ISEED )
                     B( JR, JC ) = RMAGN( KBMAGN( JTYPE ) )*
     $                             SLARND( 2, ISEED )
   80             CONTINUE
   90          CONTINUE
            END IF
*
            ANORM = SLANGE( '1', N, N, A, LDA, WORK )
            BNORM = SLANGE( '1', N, N, B, LDA, WORK )
*
  100       CONTINUE
*
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'Generator', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               RETURN
            END IF
*
  110       CONTINUE
*
*           Call SGEQR2, SORM2R, and SGGHRD to compute H, T, U, and V
*
            CALL SLACPY( ' ', N, N, A, LDA, H, LDA )
            CALL SLACPY( ' ', N, N, B, LDA, T, LDA )
            NTEST = 1
            RESULT( 1 ) = ULPINV
*
            CALL SGEQR2( N, N, T, LDA, WORK, WORK( N+1 ), IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'SGEQR2', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            CALL SORM2R( 'L', 'T', N, N, N, T, LDA, WORK, H, LDA,
     $                   WORK( N+1 ), IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'SORM2R', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            CALL SLASET( 'Full', N, N, ZERO, ONE, U, LDU )
            CALL SORM2R( 'R', 'N', N, N, N, T, LDA, WORK, U, LDU,
     $                   WORK( N+1 ), IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'SORM2R', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            CALL SGGHRD( 'V', 'I', N, 1, N, H, LDA, T, LDA, U, LDU, V,
     $                   LDU, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'SGGHRD', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
            NTEST = 4
*
*           Do tests 1--4
*
            CALL SGET51( 1, N, A, LDA, H, LDA, U, LDU, V, LDU, WORK,
     $                   RESULT( 1 ) )
            CALL SGET51( 1, N, B, LDA, T, LDA, U, LDU, V, LDU, WORK,
     $                   RESULT( 2 ) )
            CALL SGET51( 3, N, B, LDA, T, LDA, U, LDU, U, LDU, WORK,
     $                   RESULT( 3 ) )
            CALL SGET51( 3, N, B, LDA, T, LDA, V, LDU, V, LDU, WORK,
     $                   RESULT( 4 ) )
*
*           Call SHGEQZ to compute S1, P1, S2, P2, Q, and Z, do tests.
*
*           Compute T1 and UZ
*
*           Eigenvalues only
*
            CALL SLACPY( ' ', N, N, H, LDA, S2, LDA )
            CALL SLACPY( ' ', N, N, T, LDA, P2, LDA )
            NTEST = 5
            RESULT( 5 ) = ULPINV
*
            CALL SHGEQZ( 'E', 'N', 'N', N, 1, N, S2, LDA, P2, LDA,
     $                   ALPHR3, ALPHI3, BETA3, Q, LDU, Z, LDU, WORK,
     $                   LWORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'SHGEQZ(E)', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
*           Eigenvalues and Full Schur Form
*
            CALL SLACPY( ' ', N, N, H, LDA, S2, LDA )
            CALL SLACPY( ' ', N, N, T, LDA, P2, LDA )
*
            CALL SHGEQZ( 'S', 'N', 'N', N, 1, N, S2, LDA, P2, LDA,
     $                   ALPHR1, ALPHI1, BETA1, Q, LDU, Z, LDU, WORK,
     $                   LWORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'SHGEQZ(S)', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
*           Eigenvalues, Schur Form, and Schur Vectors
*
            CALL SLACPY( ' ', N, N, H, LDA, S1, LDA )
            CALL SLACPY( ' ', N, N, T, LDA, P1, LDA )
*
            CALL SHGEQZ( 'S', 'I', 'I', N, 1, N, S1, LDA, P1, LDA,
     $                   ALPHR1, ALPHI1, BETA1, Q, LDU, Z, LDU, WORK,
     $                   LWORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'SHGEQZ(V)', IINFO, N, JTYPE,
     $            IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            NTEST = 8
*
*           Do Tests 5--8
*
            CALL SGET51( 1, N, H, LDA, S1, LDA, Q, LDU, Z, LDU, WORK,
     $                   RESULT( 5 ) )
            CALL SGET51( 1, N, T, LDA, P1, LDA, Q, LDU, Z, LDU, WORK,
     $                   RESULT( 6 ) )
            CALL SGET51( 3, N, T, LDA, P1, LDA, Q, LDU, Q, LDU, WORK,
     $                   RESULT( 7 ) )
            CALL SGET51( 3, N, T, LDA, P1, LDA, Z, LDU, Z, LDU, WORK,
     $                   RESULT( 8 ) )
*
*           Compute the Left and Right Eigenvectors of (S1,P1)
*
*           9: Compute the left eigenvector Matrix without
*              back transforming:
*
            NTEST = 9
            RESULT( 9 ) = ULPINV
*
*           To test "SELECT" option, compute half of the eigenvectors
*           in one call, and half in another
*
            I1 = N / 2
            DO 120 J = 1, I1
               LLWORK( J ) = .TRUE.
  120       CONTINUE
            DO 130 J = I1 + 1, N
               LLWORK( J ) = .FALSE.
  130       CONTINUE
*
            CALL STGEVC( 'L', 'S', LLWORK, N, S1, LDA, P1, LDA, EVECTL,
     $                   LDU, DUMMA, LDU, N, IN, WORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'STGEVC(L,S1)', IINFO, N,
     $            JTYPE, IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            I1 = IN
            DO 140 J = 1, I1
               LLWORK( J ) = .FALSE.
  140       CONTINUE
            DO 150 J = I1 + 1, N
               LLWORK( J ) = .TRUE.
  150       CONTINUE
*
            CALL STGEVC( 'L', 'S', LLWORK, N, S1, LDA, P1, LDA,
     $                   EVECTL( 1, I1+1 ), LDU, DUMMA, LDU, N, IN,
     $                   WORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'STGEVC(L,S2)', IINFO, N,
     $            JTYPE, IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            CALL SGET52( .TRUE., N, S1, LDA, P1, LDA, EVECTL, LDU,
     $                   ALPHR1, ALPHI1, BETA1, WORK, DUMMA( 1 ) )
            RESULT( 9 ) = DUMMA( 1 )
            IF( DUMMA( 2 ).GT.THRSHN ) THEN
               WRITE( NOUNIT, FMT = 9998 )'Left', 'STGEVC(HOWMNY=S)',
     $            DUMMA( 2 ), N, JTYPE, IOLDSD
            END IF
*
*           10: Compute the left eigenvector Matrix with
*               back transforming:
*
            NTEST = 10
            RESULT( 10 ) = ULPINV
            CALL SLACPY( 'F', N, N, Q, LDU, EVECTL, LDU )
            CALL STGEVC( 'L', 'B', LLWORK, N, S1, LDA, P1, LDA, EVECTL,
     $                   LDU, DUMMA, LDU, N, IN, WORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'STGEVC(L,B)', IINFO, N,
     $            JTYPE, IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            CALL SGET52( .TRUE., N, H, LDA, T, LDA, EVECTL, LDU, ALPHR1,
     $                   ALPHI1, BETA1, WORK, DUMMA( 1 ) )
            RESULT( 10 ) = DUMMA( 1 )
            IF( DUMMA( 2 ).GT.THRSHN ) THEN
               WRITE( NOUNIT, FMT = 9998 )'Left', 'STGEVC(HOWMNY=B)',
     $            DUMMA( 2 ), N, JTYPE, IOLDSD
            END IF
*
*           11: Compute the right eigenvector Matrix without
*               back transforming:
*
            NTEST = 11
            RESULT( 11 ) = ULPINV
*
*           To test "SELECT" option, compute half of the eigenvectors
*           in one call, and half in another
*
            I1 = N / 2
            DO 160 J = 1, I1
               LLWORK( J ) = .TRUE.
  160       CONTINUE
            DO 170 J = I1 + 1, N
               LLWORK( J ) = .FALSE.
  170       CONTINUE
*
            CALL STGEVC( 'R', 'S', LLWORK, N, S1, LDA, P1, LDA, DUMMA,
     $                   LDU, EVECTR, LDU, N, IN, WORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'STGEVC(R,S1)', IINFO, N,
     $            JTYPE, IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            I1 = IN
            DO 180 J = 1, I1
               LLWORK( J ) = .FALSE.
  180       CONTINUE
            DO 190 J = I1 + 1, N
               LLWORK( J ) = .TRUE.
  190       CONTINUE
*
            CALL STGEVC( 'R', 'S', LLWORK, N, S1, LDA, P1, LDA, DUMMA,
     $                   LDU, EVECTR( 1, I1+1 ), LDU, N, IN, WORK,
     $                   IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'STGEVC(R,S2)', IINFO, N,
     $            JTYPE, IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            CALL SGET52( .FALSE., N, S1, LDA, P1, LDA, EVECTR, LDU,
     $                   ALPHR1, ALPHI1, BETA1, WORK, DUMMA( 1 ) )
            RESULT( 11 ) = DUMMA( 1 )
            IF( DUMMA( 2 ).GT.THRESH ) THEN
               WRITE( NOUNIT, FMT = 9998 )'Right', 'STGEVC(HOWMNY=S)',
     $            DUMMA( 2 ), N, JTYPE, IOLDSD
            END IF
*
*           12: Compute the right eigenvector Matrix with
*               back transforming:
*
            NTEST = 12
            RESULT( 12 ) = ULPINV
            CALL SLACPY( 'F', N, N, Z, LDU, EVECTR, LDU )
            CALL STGEVC( 'R', 'B', LLWORK, N, S1, LDA, P1, LDA, DUMMA,
     $                   LDU, EVECTR, LDU, N, IN, WORK, IINFO )
            IF( IINFO.NE.0 ) THEN
               WRITE( NOUNIT, FMT = 9999 )'STGEVC(R,B)', IINFO, N,
     $            JTYPE, IOLDSD
               INFO = ABS( IINFO )
               GO TO 210
            END IF
*
            CALL SGET52( .FALSE., N, H, LDA, T, LDA, EVECTR, LDU,
     $                   ALPHR1, ALPHI1, BETA1, WORK, DUMMA( 1 ) )
            RESULT( 12 ) = DUMMA( 1 )
            IF( DUMMA( 2 ).GT.THRESH ) THEN
               WRITE( NOUNIT, FMT = 9998 )'Right', 'STGEVC(HOWMNY=B)',
     $            DUMMA( 2 ), N, JTYPE, IOLDSD
            END IF
*
*           Tests 13--15 are done only on request
*
            IF( TSTDIF ) THEN
*
*              Do Tests 13--14
*
               CALL SGET51( 2, N, S1, LDA, S2, LDA, Q, LDU, Z, LDU,
     $                      WORK, RESULT( 13 ) )
               CALL SGET51( 2, N, P1, LDA, P2, LDA, Q, LDU, Z, LDU,
     $                      WORK, RESULT( 14 ) )
*
*              Do Test 15
*
               TEMP1 = ZERO
               TEMP2 = ZERO
               DO 200 J = 1, N
                  TEMP1 = MAX( TEMP1, ABS( ALPHR1( J )-ALPHR3( J ) )+
     $                    ABS( ALPHI1( J )-ALPHI3( J ) ) )
                  TEMP2 = MAX( TEMP2, ABS( BETA1( J )-BETA3( J ) ) )
  200          CONTINUE
*
               TEMP1 = TEMP1 / MAX( SAFMIN, ULP*MAX( TEMP1, ANORM ) )
               TEMP2 = TEMP2 / MAX( SAFMIN, ULP*MAX( TEMP2, BNORM ) )
               RESULT( 15 ) = MAX( TEMP1, TEMP2 )
               NTEST = 15
            ELSE
               RESULT( 13 ) = ZERO
               RESULT( 14 ) = ZERO
               RESULT( 15 ) = ZERO
               NTEST = 12
            END IF
*
*           End of Loop -- Check for RESULT(j) > THRESH
*
  210       CONTINUE
*
            NTESTT = NTESTT + NTEST
*
*           Print out tests which fail.
*
            DO 220 JR = 1, NTEST
               IF( RESULT( JR ).GE.THRESH ) THEN
*
*                 If this is the first test to fail,
*                 print a header to the data file.
*
                  IF( NERRS.EQ.0 ) THEN
                     WRITE( NOUNIT, FMT = 9997 )'SGG'
*
*                    Matrix types
*
                     WRITE( NOUNIT, FMT = 9996 )
                     WRITE( NOUNIT, FMT = 9995 )
                     WRITE( NOUNIT, FMT = 9994 )'Orthogonal'
*
*                    Tests performed
*
                     WRITE( NOUNIT, FMT = 9993 )'orthogonal', '''',
     $                  'transpose', ( '''', J = 1, 10 )
*
                  END IF
                  NERRS = NERRS + 1
                  IF( RESULT( JR ).LT.10000.0 ) THEN
                     WRITE( NOUNIT, FMT = 9992 )N, JTYPE, IOLDSD, JR,
     $                  RESULT( JR )
                  ELSE
                     WRITE( NOUNIT, FMT = 9991 )N, JTYPE, IOLDSD, JR,
     $                  RESULT( JR )
                  END IF
               END IF
  220       CONTINUE
*
  230    CONTINUE
  240 CONTINUE
*
*     Summary
*
      CALL SLASUM( 'SGG', NOUNIT, NERRS, NTESTT )
      RETURN
*
 9999 FORMAT( ' SCHKGG: ', A, ' returned INFO=', I6, '.', / 9X, 'N=',
     $      I6, ', JTYPE=', I6, ', ISEED=(', 3( I5, ',' ), I5, ')' )
*
 9998 FORMAT( ' SCHKGG: ', A, ' Eigenvectors from ', A, ' incorrectly ',
     $      'normalized.', / ' Bits of error=', 0P, G10.3, ',', 9X,
     $      'N=', I6, ', JTYPE=', I6, ', ISEED=(', 3( I5, ',' ), I5,
     $      ')' )
*
 9997 FORMAT( / 1X, A3, ' -- Real Generalized eigenvalue problem' )
*
 9996 FORMAT( ' Matrix types (see SCHKGG for details): ' )
*
 9995 FORMAT( ' Special Matrices:', 23X,
     $      '(J''=transposed Jordan block)',
     $      / '   1=(0,0)  2=(I,0)  3=(0,I)  4=(I,I)  5=(J'',J'')  ',
     $      '6=(diag(J'',I), diag(I,J''))', / ' Diagonal Matrices:  ( ',
     $      'D=diag(0,1,2,...) )', / '   7=(D,I)   9=(large*D, small*I',
     $      ')  11=(large*I, small*D)  13=(large*D, large*I)', /
     $      '   8=(I,D)  10=(small*D, large*I)  12=(small*I, large*D) ',
     $      ' 14=(small*D, small*I)', / '  15=(D, reversed D)' )
 9994 FORMAT( ' Matrices Rotated by Random ', A, ' Matrices U, V:',
     $      / '  16=Transposed Jordan Blocks             19=geometric ',
     $      'alpha, beta=0,1', / '  17=arithm. alpha&beta             ',
     $      '      20=arithmetic alpha, beta=0,1', / '  18=clustered ',
     $      'alpha, beta=0,1            21=random alpha, beta=0,1',
     $      / ' Large & Small Matrices:', / '  22=(large, small)   ',
     $      '23=(small,large)    24=(small,small)    25=(large,large)',
     $      / '  26=random O(1) matrices.' )
*
 9993 FORMAT( / ' Tests performed:   (H is Hessenberg, S is Schur, B, ',
     $      'T, P are triangular,', / 20X, 'U, V, Q, and Z are ', A,
     $      ', l and r are the', / 20X,
     $      'appropriate left and right eigenvectors, resp., a is',
     $      / 20X, 'alpha, b is beta, and ', A, ' means ', A, '.)',
     $      / ' 1 = | A - U H V', A,
     $      ' | / ( |A| n ulp )      2 = | B - U T V', A,
     $      ' | / ( |B| n ulp )', / ' 3 = | I - UU', A,
     $      ' | / ( n ulp )             4 = | I - VV', A,
     $      ' | / ( n ulp )', / ' 5 = | H - Q S Z', A,
     $      ' | / ( |H| n ulp )', 6X, '6 = | T - Q P Z', A,
     $      ' | / ( |T| n ulp )', / ' 7 = | I - QQ', A,
     $      ' | / ( n ulp )             8 = | I - ZZ', A,
     $      ' | / ( n ulp )', / ' 9 = max | ( b S - a P )', A,
     $      ' l | / const.  10 = max | ( b H - a T )', A,
     $      ' l | / const.', /
     $      ' 11= max | ( b S - a P ) r | / const.   12 = max | ( b H',
     $      ' - a T ) r | / const.', / 1X )
*
 9992 FORMAT( ' Matrix order=', I5, ', type=', I2, ', seed=',
     $      4( I4, ',' ), ' result ', I2, ' is', 0P, F8.2 )
 9991 FORMAT( ' Matrix order=', I5, ', type=', I2, ', seed=',
     $      4( I4, ',' ), ' result ', I2, ' is', 1P, E10.3 )
*
*     End of SCHKGG
*
      END


C File: derived-types-02.f
C Illustrates more complex derived types involving fields that
C are aggregates (in this case, 1-D arrays)
C
C This code is adapted from
C https://courses.physics.illinois.edu/phys466/sp2013/comp_info/derived.html
C
C The generated output is:
C  1   4.000   1.000   1.500   2.000
C  2   5.000   1.500   2.000   2.500
C  3   6.000   2.000   2.500   3.000

      program main
      implicit none

      type mytype
          integer:: i
          real, dimension(3) :: a    !  <<< derived type element that is an array
      end type mytype

      integer i, j

      type (mytype) var
      type (mytype), dimension(3) :: x    ! <<< x: array of derived type values

      var%i = 3

      do i = 1, var%i
          var%a(i) = var%i + i

          do j = 1, var%i
              x(i)%a(j) = (i+j)/2.0
          end do
      end do

 10   format(I3, 4(3X, F5.3))

      do i = 1, var%i
          write(*,10) i, var%a(i), x(i)%a(1), x(i)%a(2), x(i)%a(3)
      end do

      stop
      end program main


SUBROUTINE running_avg(x, avg, std_dev, nvals, reset)
IMPLICIT NONE

REAL, INTENT(IN) :: x
REAL, INTENT(OUT) :: avg, std_dev
INTEGER, INTENT(OUT) :: nvals
LOGICAL, INTENT(IN) :: reset
INTEGER, SAVE :: n
REAL, SAVE :: sum_x, sum_x2

calc_sums: IF(reset) THEN
  n       = 0
  sum_x   = 0.
  sum_x2  = 0.
  avg     = 0.
  std_dev = 0.
  nvals   = 0
ELSE
  n      = n + 1
  sum_x  = sum_x + x
  sum_x2 = sum_x2 + x**2

  avg = sum_x / REAL(n)

  IF (n >= 2) THEN
    std_dev = SQRT((REAL(n) * sum_x2 - sum_x**2) &
            / (REAL(n) * REAL(n-1)))
  ELSE
    std_dev = 0.
  END IF

  nvals = n
END IF calc_sums
END SUBROUTINE running_avg

PROGRAM test_running_avg
IMPLICIT NONE
INTEGER :: istat, nvals
REAL :: avg, std_dev, x
CHARACTER(len=80) :: msg
CHARACTER(len=20) :: file_name

CALL running_avg(0., avg, std_dev, nvals, .TRUE.)
WRITE(*, *) 'Enter the file name to read data from:'
READ(*, '(A20)') file_name
OPEN(UNIT=21, FILE=file_name, STATUS='OLD', ACTION='READ', &
     IOSTAT=istat, IOMSG=msg)

openok: IF (istat == 0) THEN
  calc: DO
    READ(21, *, IOSTAT=istat) x
    IF (istat /= 0) EXIT
    CALL running_avg(x, avg, std_dev, nvals, .FALSE.)
    WRITE(*, 1020) 'VALUE = ',x,' Avg = ',avg, &
                   '  Std_Dev = ', std_dev, &
                   '  Nvals = ', nvals
    1020 FORMAT (3(A,F10.4),A,I6)
  END DO calc
ELSE openok
  WRITE(*, 1030) msg
  1030 FORMAT ('File open failed: ', A)
END IF openok
END PROGRAM test_running_avg