    PROGRAM g11cafe

!      G11CAF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g11caf, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: dev, tol
       INTEGER                         :: cm, i, ifail, ip, iprint, ldz, lwk,  &
                                          m, maxit, n, n0, ns
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: b(:), cov(:), sc(:), se(:), wk(:),   &
                                          z(:,:)
       INTEGER, ALLOCATABLE            :: cnt(:), ic(:), isi(:), isz(:),       &
                                          nca(:), nct(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          count, maxval, sum
!      .. Executable Statements ..
       WRITE (nout,*) 'G11CAF Example Program Results'
       WRITE (nout,*)

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

!      Read in problem size and control parameters
       READ (nin,*) n, m, ns, maxit, iprint, tol

       ldz = n
       ALLOCATE (z(ldz,m),isz(m),ic(n),isi(n),nca(ns),nct(ns),cnt(ns))

!      Read in data
       READ (nin,*) (isi(i),ic(i),z(i,1:m),i=1,n)

!      Read in variable inclusion flags
       READ (nin,*) isz(1:m)

!      Calculate IP
       ip = count(isz(1:m)>0)

!      Calculate number of observations in the model and maximum number of
!      observations in any stratum
       cnt(1:ns) = 0
       DO i = 1, n
          IF (isi(i)>0 .AND. isi(i)<=ns) THEN
             cnt(isi(i)) = cnt(isi(i)) + 1
          END IF
       END DO
       cm = maxval(cnt(1:ns))
       n0 = sum(cnt(1:ns))

       lwk = ip*n0 + (cm+1)*(ip+1)*(ip+2)/2 + cm
       ALLOCATE (b(ip),se(ip),sc(ip),cov(ip*(ip+1)/2),wk(lwk))

!      Read in initial estimate for B
       READ (nin,*) b(1:ip)

!      Calculate parameter estimates
       ifail = 0
       CALL g11caf(n,m,ns,z,ldz,isz,ip,ic,isi,dev,b,se,sc,cov,nca,nct,tol, &
          maxit,iprint,wk,lwk,ifail)

!      Display results
       WRITE (nout,99999) ' Deviance = ', dev
       WRITE (nout,*)
       WRITE (nout,*) ' Strata     No. Cases   No. Controls'
       WRITE (nout,*)
       WRITE (nout,99998) (i,nca(i),nct(i),i=1,ns)
       WRITE (nout,*)
       WRITE (nout,*) ' Parameter      Estimate', '       Standard Error'
       WRITE (nout,*)
       WRITE (nout,99997) (i,b(i),se(i),i=1,ip)

99999  FORMAT (A,E13.4)
99998  FORMAT (3X,I3,10X,I2,10X,I2)
99997  FORMAT (I6,10X,F8.4,10X,F8.4)
    END PROGRAM g11cafe
