    PROGRAM g11bbfe

!      G11BBF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g11bbf, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: percnt
       INTEGER                         :: i, ifail, j, k, ldf, liwk, lwk, lwt, &
                                          maxt, n, ncells, ncol, ndim, nfac,   &
                                          nrow
       CHARACTER (1)                   :: typ, weight
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: table(:), wk(:), wt(:), y(:)
       INTEGER, ALLOCATABLE            :: icount(:), idim(:), ifac(:,:),       &
                                          isf(:), iwk(:), lfac(:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G11BBF Example Program Results'
       WRITE (nout,*)

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

!      Read in the problem size
       READ (nin,*) typ, weight, n, nfac, percnt

       IF (weight=='W' .OR. weight=='w') THEN
          lwt = n
       ELSE
          lwt = 0
       END IF
       liwk = 2*nfac + n
       lwk = 2*n
       ldf = n
       ALLOCATE (isf(nfac),lfac(nfac),ifac(ldf,nfac),idim(nfac),iwk(liwk), &
          y(n),wt(lwt),wk(lwk))

!      Read in data
       IF (lwt>0) THEN
          READ (nin,*) (ifac(i,1:nfac),y(i),wt(i),i=1,n)
       ELSE
          READ (nin,*) (ifac(i,1:nfac),y(i),i=1,n)
       END IF
       READ (nin,*) lfac(1:nfac)
       READ (nin,*) isf(1:nfac)

!      Calculate the size of TABLE
       maxt = 1
       DO i = 1, nfac
          IF (isf(i)>0) THEN
             maxt = maxt*lfac(i)
          END IF
       END DO

       ALLOCATE (table(maxt),icount(maxt))

!      Compute classification table
       ifail = 0
       CALL g11bbf(typ,weight,n,nfac,isf,lfac,ifac,ldf,percnt,y,wt,table,maxt, &
          ncells,ndim,idim,icount,iwk,wk,ifail)

!      Display results
       WRITE (nout,99999) ' TABLE for ', percnt, 'th percentile'
       WRITE (nout,*)
       ncol = idim(ndim)
       nrow = ncells/ncol
       k = 1
       DO i = 1, nrow
          WRITE (nout,99998) (table(j),'(',icount(j),')',j=k,k+ncol-1)
          k = k + ncol
       END DO

99999  FORMAT (A,F4.0,A)
99998  FORMAT (1X,6(F8.2,A,I2,A))
    END PROGRAM g11bbfe
