C--------------------------------------------------------------------------
        subroutine ftgkey(iunit,keynam,value,comm,status)

C       Read value and comment of a header keyword from the keyword buffer

C       iunit   i  Fortran I/O unit number
C       keynam  c  name of keyword to be read
C       OUTPUT PARAMETERS:
C       value   c  output value of the keyword, if any
C       comm    c  output comment string, if any, of the keyword
C       status  i  returned error status (0=ok)
C
C       written by Wm Pence, HEASARC/GSFC, June, 1991

        character*(*) keynam
        integer iunit,status,i,j,ibuff,maxkey
        character*(*) value,comm
        character kname*8
        character*80 keybuf

C       COMMON BLOCK DEFINITIONS:--------------------------------------------
        integer nb,ne
        parameter (nb = 12)
        parameter (ne = 128)
        integer bufnum,bufpnt,reclen,recnum,bytnum
        integer chdu,maxhdu,hdstrt,hdend,nxthdr,dtstrt
        logical wrmode,modify
        real compid
        common/ft0001/bufnum(199),bufpnt(nb),reclen(199),recnum(nb),
     &  bytnum(nb),wrmode(nb),modify(nb),chdu(nb),maxhdu(nb),
     &  hdstrt(nb,ne),hdend(nb),nxthdr(nb),dtstrt(nb),compid
C       END OF COMMON BLOCK DEFINITIONS-----------------------------------

C       get the number of the data buffer used for this unit
        ibuff=bufnum(iunit)

C       make sure keyword name is in uppercase
        kname=keynam
        call ftupch(kname)

C       Start by searching for keyword from current pointer position to the end.
C       Calculate the maximum number of keywords to be searched:
        maxkey=(hdend(ibuff)-nxthdr(ibuff))/80
        if (maxkey .gt. 0)then
C               position I/O pointer to the next header keyword
                call ftmbyt(iunit,nxthdr(ibuff),.false.,status)
                if (status .gt. 0)go to 100
        end if
        do 20 j=1,2
            do 10 i=1,maxkey
                call ftgcbf(iunit,1,80,keybuf,status)
                if (status .gt. 0)go to 100
                if (keybuf(1:8) .eq. kname)go to 50
10          continue

C           didn't find keyword yet, so now search from top down to starting pt.
C           move I/O pointer to beginning of header
            call ftmbyt(iunit,hdstrt(ibuff,chdu(ibuff)),.false.,status)
            if (status .gt. 0)go to 100

C           calculate the maximum number of keywords to be searched
            maxkey=(nxthdr(ibuff)-hdstrt(ibuff,chdu(ibuff)))/80
20      continue                        

C       keyword was not found
        status=202
        go to 100

C       parse the record to find value and comment strings
50      call ftpsvc(keybuf,value,comm,status)
        if (status .gt. 0)go to 100

C       update header pointer position (set equal to the current position)
        nxthdr(ibuff)=(recnum(ibuff)-1)*reclen(iunit)+bytnum(ibuff)

100     continue
        end
