    PROGRAM g02eafe

!      G02EAF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g02eaf, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6, vnlen = 3
!      .. Local Scalars ..
       INTEGER                         :: i, ifail, k, ldmodl, ldx, lwt, m, n, &
                                          nmod
       CHARACTER (1)                   :: mean, weight
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: rss(:), wk(:), wt(:), x(:,:), y(:)
       INTEGER, ALLOCATABLE            :: isx(:), mrank(:), nterms(:)
       CHARACTER (vnlen), ALLOCATABLE  :: modl(:,:), vname(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          count, max
!      .. Executable Statements ..
       WRITE (nout,*) 'G02EAF Example Program Results'
       WRITE (nout,*)

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

!      Read in the problem size
       READ (nin,*) n, m, mean, weight

       IF (weight=='W' .OR. weight=='w') THEN
          lwt = n
       ELSE
          lwt = 0
       END IF
       ldx = n
       ALLOCATE (x(ldx,m),vname(m),isx(m),y(n),wt(lwt))

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

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

!      Read in first VNLEN characters of the variable names
       READ (nin,*) vname(1:m)

!      Calculate the number of free variables
       k = count(isx(1:m)==1)

       ldmodl = max(m,2**k)
       ALLOCATE (modl(ldmodl,m),rss(ldmodl),nterms(ldmodl),mrank(ldmodl), &
          wk(n*(m+1)))

!      Calculate residual sums of squares for all possible models
       ifail = 0
       CALL g02eaf(mean,weight,n,m,x,ldx,vname,isx,y,wt,nmod,modl,ldmodl,rss, &
          nterms,mrank,wk,ifail)

!      Display results
       WRITE (nout,*) 'Number of     RSS    RANK  MODL'
       WRITE (nout,*) 'parameters'
       DO i = 1, nmod
          WRITE (nout,99999) nterms(i), rss(i), mrank(i), modl(i,1:nterms(i))
       END DO

99999  FORMAT (1X,I8,F11.4,I4,3X,5(1X,A))
    END PROGRAM g02eafe
