      SUBROUTINE PDS_WRTRMF(NAME,RMF,NINCH,NOUTCH,MAXNZERO)
C
C------------------------------------------------------------------------
C
C.IDENTIFICATION: Subroutine  PDS_WRTRMF
C.SOURCE FILE:    pds_wrtrmf.f
C.LIBRARY:        PDSLIB
C.AUTHOR:         D. Dal Fiume and E. Palazzi - TeSRE Bologna
C.VERSIONS:       1.0 - 01 Aug 96 - First version
C                 1.1 - 23 May 97 - Updated energy grid
C.PURPOSE:        creates a FITS-OGIP file ".rmf" type and stores the 
C                 detector redistribution matrix. 
C.SYNTAX:         CALL PDS_WRTRMF(NAME,RMF,NINCH,NOUTCH,MAXNZERO)
C.PARAMETERS:     NAME      = the name of the output file
C                 RMF       = the PDS response matrix
C                 NINCH     = the number of points in the input energy
C                             grid
C                 NOUTCH    = the number of output channels
C.RESTRICTIONS:   none
C.NOTES:          none
C.FILES:          none
C.REFERENCES:     OGIP memo CAL/GEN/92-002 (Legacy, 2, 51 (1992))
C
C------------------------------------------------------------------------
C
C
C
      INCLUDE      'pdsmat.inc'
C
C     EXTERNAL     PDSMAT_INIT
C
      INTEGER      MAXNZERO, IUNIT, IROW, I, J, NINCH, NOUTCH
      INTEGER      STATUS, IERR
C
      REAL         RMF(NINCH,NOUTCH), ROW(NGRID), ELO, EUP
C
      CHARACTER    NAME*(*), DUMMY*10, GRIDTYPE*10
C
      LOGICAL      NONUNIFORM
C
C     Opening the FITS file.
C
      CALL PDS_OPNRMF (NAME,NINCH,NOUTCH,MAXNZERO,IUNIT)
C
C     What kind of energy grid?
C
      CALL GET_GLOBAL_DEFAULT('PDSGRID','NONUNIFORM',GRIDTYPE)
      IF(GRIDTYPE(1:10).EQ.'NONUNIFORM')THEN
        NONUNIFORM=.TRUE.
        ELSE
        NONUNIFORM=.FALSE.
      ENDIF
C
C     Writing the matrix extension.
C
      DO 1 I=1,NINCH
        DO 2 J=1,NOUTCH
          ROW(J)=RMF(I,J)
   2    CONTINUE
        IROW=I
        IF(NONUNIFORM.AND.I.EQ.PDSMAT_NEDGE)THEN
          ELO=PDSMAT_EGRID(I)-PDSMAT_ESTEP/2.
          EUP=PDSMAT_EGRID(I)
        ELSEIF(NONUNIFORM.AND.I.EQ.PDSMAT_NEDGE+1)THEN
          ELO=PDSMAT_EGRID(I)
          EUP=PDSMAT_EGRID(I)+PDSMAT_ESTEP/2.
        ELSE
          ELO=PDSMAT_EGRID(I)-PDSMAT_ESTEP/2.
          EUP=PDSMAT_EGRID(I)+PDSMAT_ESTEP/2.
        ENDIF
        CALL PDS_WRTRMFMAT(IUNIT,NOUTCH,IROW,ELO,EUP,ROW)
   1  CONTINUE
C
C     Writing the EBOUND extension, containing the output channels.
C
      CALL PDS_WRTRMFEBO(IUNIT,NOUTCH)
      CALL FTCLOS(IUNIT,STATUS)
      IF(IERR.NE.0) THEN
        WRITE(DUMMY,'(I05)')STATUS
        CALL X_ECHO_ERROR('PDS_WRTRMF: FTCLOS err =  '//DUMMY)
        CALL Z_EXIT(1)
      ENDIF
      RETURN
      END
