FUNCTION random_t(m) RESULT(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! FUNCTION GENERATES A RANDOM VARIATE FROM A
! T DISTRIBUTION USING KINDERMAN AND MONAHAN'S RATIO METHOD.
! M = DEGREES OF FREEDOM OF DISTRIBUTION
! (1 <= 1NTEGER)
INTEGER, INTENT(IN) :: m
REAL :: fn_val
! Local variables
REAL, SAVE :: s, c, a, f, g
REAL :: r, x, v
REAL, PARAMETER :: three = 3.0, four = 4.0, quart = 0.25, &
five = 5.0, sixteen = 16.0
INTEGER :: mm = 0
IF (m < 1) THEN
WRITE(*, *) 'IMPERMISSIBLE DEGREES OF FREEDOM'
STOP
END IF
IF (m /= mm) THEN ! Initialization, if necessary
s = m
c = -quart*(s + one)
a = four/(one + one/s)**c
f = sixteen/a
IF (m > 1) THEN
g = s - one
g = ((s + one)/g)**c*SQRT((s+s)/g)
ELSE
g = one
END IF
mm = m
END IF
DO
CALL RANDOM_NUMBER(r)
IF (r <= zero) CYCLE
CALL RANDOM_NUMBER(v)
x = (two*v - one)*g/r
v = x*x
IF (v > five - a*r) THEN
IF (m >= 1 .AND. r*(v + three) > f) CYCLE
IF (r > (one + v/s)**c) CYCLE
END IF
EXIT
END DO
fn_val = x
RETURN
END FUNCTION random_t