    PROGRAM g08cgfe

!      G08CGF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g01aef, g08cgf, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: chisq, p, xmax, xmin
       INTEGER                         :: iclass, ifail, n, nclass, ndf, npar, &
                                          npest
       CHARACTER (1)                   :: dist
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: cb(:), chisqi(:), eval(:), prob(:),  &
                                          x(:)
       REAL (KIND=nag_wp)              :: par(2)
       INTEGER, ALLOCATABLE            :: ifreq(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G08CGF Example Program Results'
       WRITE (nout,*)

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

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

!      Read in class information
       READ (nin,*) nclass, iclass

       ALLOCATE (x(n),cb(nclass),ifreq(nclass),prob(nclass),eval(nclass), &
          chisqi(nclass))

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

!      Read in the class boundaries, if supplied
       IF (iclass==1) THEN
          READ (nin,*) cb(1:(nclass-1))
       END IF

!      Read in information on the distribution to test against
       READ (nin,*) dist, npest

       SELECT CASE (dist)
       CASE ('A','a')
          npar = 0
       CASE ('E','e','C','c')
          npar = 1
       CASE DEFAULT
          npar = 2
       END SELECT

!      Read in the distribution parameters or probabilities
       IF (npar==0) THEN
          READ (nin,*) prob(1:nclass)
       ELSE
          READ (nin,*) par(1:npar)
       END IF

!      Produce frequency table for data
       ifail = 0
       CALL g01aef(n,nclass,x,iclass,cb,ifreq,xmin,xmax,ifail)

!      Perform chi-squared test
       ifail = -1
       CALL g08cgf(nclass,ifreq,cb,dist,par,npest,prob,chisq,p,ndf,eval, &
          chisqi,ifail)
       IF (ifail/=0) THEN
          IF (ifail<=9) THEN
             GO TO 20
          END IF
       END IF

!      Display results
       WRITE (nout,99999) 'Chi-squared test statistic   = ', chisq
       WRITE (nout,99998) 'Degrees of freedom.          = ', ndf
       WRITE (nout,99999) 'Significance level           = ', p
       WRITE (nout,*)
       WRITE (nout,*) 'The contributions to the test statistic are :-'
       WRITE (nout,99997) chisqi(1:nclass)

20     CONTINUE

99999  FORMAT (1X,A,F10.4)
99998  FORMAT (1X,A,I5)
99997  FORMAT (1X,F10.4)
    END PROGRAM g08cgfe
