    PROGRAM g02ddfe

!      G02DDF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g02ddf, g02def, nag_wp
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: rss, tol
       INTEGER                         :: i, idf, ifail, ip, irank, ldq, lwt,  &
                                          m, n
       LOGICAL                         :: svd
       CHARACTER (1)                   :: weight
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: b(:), cov(:), p(:), q(:,:), se(:),   &
                                          wk(:), wt(:), x(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G02DDF Example Program Results'
       WRITE (nout,*)

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

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

       IF (weight=='W' .OR. weight=='w') THEN
          lwt = n
       ELSE
          lwt = 0
       END IF
       ldq = n
       ALLOCATE (b(m),cov(m*(m+1)/2),p(m*(m+2)),q(ldq,m+1),se(m),wk(m*m+5*m), &
          wt(n),x(n,m))

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

!      Use suggested value for tolerance
       tol = 0.000001E0_nag_wp

!      Fit general linear regression model, adding each variable in turn
       ip = 0
       DO i = 1, m
          ifail = -1
          CALL g02def(weight,n,ip,q,ldq,p,wt,x(1,i),rss,tol,ifail)
          IF (ifail==0) THEN
             ip = ip + 1
          ELSE IF (ifail==3) THEN
             WRITE (nout,99996) ' * Variable ', ip, &
                ' is linear combination of previous columns'
             WRITE (nout,99996) '   so it has not been added'
          ELSE
             GO TO 20
          END IF
       END DO

!      Get G02DDF to calculate RSS
       rss = 0.0E0_nag_wp

!      Calculate parameter estimates, RSS etc
       ifail = 0
       CALL g02ddf(n,ip,q,ldq,rss,idf,b,se,cov,svd,irank,p,tol,wk,ifail)

!      Display results
       IF (svd) THEN
          WRITE (nout,*) 'Model not of full rank'
          WRITE (nout,*)
       END IF
       WRITE (nout,99999) 'Residual sum of squares = ', rss
       WRITE (nout,99998) 'Degrees of freedom = ', idf
       WRITE (nout,*)
       WRITE (nout,*) 'Variable   Parameter estimate   Standard error'
       WRITE (nout,*)
       WRITE (nout,99997) (i,b(i),se(i),i=1,ip)

20     CONTINUE

99999  FORMAT (1X,A,E12.4)
99998  FORMAT (1X,A,I4)
99997  FORMAT (1X,I6,2E20.4)
99996  FORMAT (1X,A,I0,A)
    END PROGRAM g02ddfe
