C----------------------------------------------------------------------
        subroutine ftchdu(iunit,status)

C       Close Header Data Unit
C       If we have write access to the file, then close the current HDU by:
C                      -padding remaining space in the header with blanks
C                      -writing the END keyword in the CHU
C                      -flushing the current buffer to disk

C       iunit   i  fortran unit number
C       status  i  output error status
C
C       written by Wm Pence, HEASARC/GSFC, June, 1991

        integer iunit,status

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-----------------------------------

        integer ibuff,nblank,i,endpos
        character*80 rec

        if (status .gt. 0)return

        ibuff=bufnum(iunit)

C       check if there was an attempt to modify a readonly access file
        if (.not. wrmode(ibuff) .and. modify(ibuff))then
                status=112
                return

C       see if we have write access to this file
        else if (wrmode(ibuff))then

C               calculate the number of blank keyword slots in the header
                endpos=hdend(ibuff)
                nblank=(dtstrt(ibuff)-endpos)/80
C               move the i/o pointer to the end of the header keywords
                call ftmbyt(iunit,endpos,.true.,status)
C               fill all the slots with blanks
                rec=' '
                do 10 i=1,nblank
                        call ftpcbf(iunit,1,80,rec,status)
10              continue

C               The END keyword must either be placed 
C               immediately after the last keyword that was written 
C               (as indicated by the HDEND parameter), or must be in the
C               first 80 bytes of the FITS record immediately preceeding
C               the data unit, whichever is further in the file.
C               The latter will occur if the user reserved room for more
C               header keywords which have not (yet) been filled.

                endpos=max(endpos,dtstrt(ibuff)-2880)
C               move pointer to this position
                call ftmbyt(iunit,endpos,.true.,status)

                rec='END'
C               append the 80 characters to the output buffer:
                call ftpcbf(iunit,1,80,rec,status)

C               now flush the current buffer to disk (by writing 0 bytes)
                call ftpbyt(iunit,0,i,status)
        end if
        end
