    PROGRAM m01edfe

!      M01EDF Example Program Text

!      Mark 23 Release. NAG Copyright 2011.

!      .. Use Statements ..
       USE nag_library, ONLY : m01daf, m01edf, nag_wp, x04daf
!      .. Implicit None Statement ..
       IMPLICIT NONE
!      .. Parameters ..
       INTEGER, PARAMETER              :: nin = 5, nout = 6
!      .. Local Scalars ..
       INTEGER                         :: i, ifail, j, k, m1, m2, n
       CHARACTER (30)                  :: string
!      .. Local Arrays ..
       COMPLEX (KIND=nag_wp), ALLOCATABLE :: cm(:,:)
       REAL (KIND=nag_wp), ALLOCATABLE :: cmod(:)
       INTEGER, ALLOCATABLE            :: irank(:)
!      .. Intrinsic Functions ..
       INTRINSIC                          abs
!      .. Executable Statements ..
       WRITE (nout,*) 'M01EDF Example Program Results'
       FLUSH (nout)

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

       READ (nin,*) m2, n, k

       IF (k<1 .OR. k>n) THEN
          GO TO 20
       END IF

       ALLOCATE (cm(m2,n),cmod(m2),irank(m2))

       m1 = 1

       DO i = m1, m2
          READ (nin,*) (cm(i,j),j=1,n)
       END DO

!      Calculate the moduli of the elements in the K-th column.

       DO i = m1, m2
          cmod(i) = abs(cm(i,k))
       END DO

!      Rearrange the rows so that the elements in the K-th column
!      are in ascending order of modulus.

       ifail = 0
       CALL m01daf(cmod,m1,m2,'Ascending',irank,ifail)

!      Rearrange each column into the order specified by IRANK.

       DO j = 1, n

          ifail = 0
          CALL m01edf(cm(m1,j),m1,m2,irank,ifail)

       END DO

!      Print the results.

       WRITE (nout,*)
       WRITE (string,99999) 'Matrix sorted on column', k
       FLUSH (nout)

       ifail = 0
       CALL x04daf('General',' ',m2-m1+1,n,cm(m1,1),m2,string,ifail)

20     CONTINUE

99999  FORMAT (1X,A,I3)
    END PROGRAM m01edfe
