    PROGRAM g11safe

!      G11SAF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : g11saf, nag_wp, x04abf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: iset = 1, nin = 5, nout = 6
!      .. Local Scalars ..
       REAL (KIND=nag_wp)              :: cgetol, chi, rlogl, siglev
       INTEGER                         :: i, idf, ifail, ip, ip2, iprint,      &
                                          ishow, ldcm, ldexpp, ldx, lw, maxit, &
                                          n, nadv, niter, ns
       LOGICAL                         :: chisqr, gprob
!      .. Local Arrays ..
       REAL (KIND=nag_wp), ALLOCATABLE :: a(:), alpha(:), c(:), cm(:,:),       &
                                          exf(:), expp(:,:), g(:), obs(:,:),   &
                                          pigam(:), w(:), xl(:), y(:)
       INTEGER, ALLOCATABLE            :: iob(:), irl(:)
       LOGICAL, ALLOCATABLE            :: x(:,:)
!      .. Executable Statements ..
       WRITE (nout,*) 'G11SAF Example Program Results'
       WRITE (nout,*)
       FLUSH (nout)

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

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

!      Read in control parameters
       READ (nin,*) gprob, iprint, cgetol, maxit, chisqr, ishow

!      Set the advisory channel to NOUT for monitoring information
       IF (iprint>0 .OR. ishow/=0) THEN
          nadv = nout
          CALL x04abf(iset,nadv)
       END IF

       ip2 = 2*ip
       ldx = ns
       ldcm = ip2
       ldexpp = ip
       lw = 4*ip*(ip+16)
       ALLOCATE (x(ldx,ip),irl(ns),a(ip),c(ip),alpha(ip),pigam(ip), &
          cm(ldcm,ip2),g(ip2),expp(ldexpp,ip),obs(ldexpp,ip),exf(ns),y(ns), &
          xl(ns),iob(ns),w(lw))

!      Read in data
       READ (nin,*) (irl(i),x(i,1:ip),i=1,ns)

!      Read in intial values
       READ (nin,*) a(1:ip)
       READ (nin,*) c(1:ip)

!      Fit a latent variable model
       ifail = 0
       CALL g11saf(ip,n,gprob,ns,x,ldx,irl,a,c,iprint,cgetol,maxit,chisqr, &
          ishow,niter,alpha,pigam,cm,ldcm,g,expp,ldexpp,obs,exf,y,xl,iob, &
          rlogl,chi,idf,siglev,w,lw,ifail)

    END PROGRAM g11safe
