    PROGRAM g08ebfe

!      G08EBF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g08ebf, nag_wp, x04eaf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: chi, df, ex, prob
       INTEGER                         :: i, ifail, lag, ldc, lwrk, msize, n,  &
                                          nsamp, pn
       LOGICAL                         :: bapp
       CHARACTER (1)                   :: cl
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: wrk(:), x(:)
       INTEGER, ALLOCATABLE            :: ncount(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G08EBF Example Program Results'
       WRITE (nout,*)
       FLUSH (nout)

!      Skip main heading in data file
       READ (nin,*)

!      Read in number of samples
       READ (nin,*) nsamp, msize, lag

       ldc = msize
       lwrk = 2*lag
       ALLOCATE (ncount(ldc,msize),wrk(lwrk),x(1))

       IF (nsamp==1) THEN
          cl = 'S'
       ELSE
          cl = 'F'
       END IF

       pn = 0
       bapp = .FALSE.
       DO i = 1, nsamp
!         Skip run heading in data file
          READ (nin,*)

!         Read in sample size
          READ (nin,*) n

          IF (n>pn) THEN
!            Reallocate X if required
             DEALLOCATE (x)
             ALLOCATE (x(n))
             pn = n
          END IF

!         Read in the sample
          READ (nin,*) x(1:n)

!         Process the sample
          ifail = -1
          CALL g08ebf(cl,n,x,msize,lag,ncount,ldc,ex,chi,df,prob,wrk,ifail)
          IF (ifail==8) THEN
             bapp = .TRUE.
          ELSE IF (ifail/=0) THEN
             GO TO 20
          END IF

!         Adjust CL for intermediate calls
          IF (i<nsamp-1) THEN
             cl = 'I'
          ELSE
             cl = 'L'
          END IF

       END DO

!      Display results
       ifail = 0
       CALL x04eaf('General',' ',msize,msize,ncount,ldc,'Count matrix',ifail)
       WRITE (nout,*)
       WRITE (nout,99999) 'Expected value = ', ex
       WRITE (nout,99998) 'CHISQ          = ', chi
       WRITE (nout,99999) 'DF             = ', df
       WRITE (nout,99998) 'Probability    = ', prob
       IF (bapp) THEN
          WRITE (nout,*) ' ** Note : EX <= 5.0, the chi square &
             &approximation may not be very good.'
       END IF

20     CONTINUE

99999  FORMAT (1X,A,F8.2)
99998  FORMAT (1X,A,F10.4)
    END PROGRAM g08ebfe
