      PROGRAM READWRITEPAL

      implicit none

      integer*4 gr_id, ri_id, file_id, pal_id, status
      integer*4 ri_idx
      character palette_data(256*3)
      integer i
      integer*4 MFGR_INTERLACE_PIXEL
      integer*4 DFACC_RDWR
      integer*4 DFNT_UINT8
      parameter(DFACC_RDWR = 3, MFGR_INTERLACE_PIXEL = 0, 
     +DFNT_UINT8 = 21)
      integer hopen, hclose, mgstart, mgselct, mgwrlut, mgn2ndx
      integer mggltid, mgrdlut, mgendac, mgend

C     Create and open the file.
      file_id = hopen('gr1.hdf', DFACC_RDWR, 0)
      write(*,*) 'hopen status: ', file_id

C     Initiate the GR interface.
      gr_id = mgstart(file_id)
      write(*,*) 'mgstart status: ', gr_id

C     Select the image named Image_1
      ri_idx = mgn2ndx (gr_id, 'Image_1')
      write(*,*) 'mgn2ndx status: ',ri_idx
      ri_id = mgselct (gr_id, ri_idx)
      write(*,*) 'mgselct status: ',ri_id

C     Initialize the palette to greyscale.
      do 10 i = 1, 256
        palette_data((i - 1) * 3 + 1) = char(i - 1)
        palette_data((i - 1) * 3 + 2) = char(i - 1)
        palette_data((i - 1) * 3 + 3) = char(i - 1)
10    continue

C     Get the identifier for the palette.
      pal_id = mggltid(ri_id, 0)
      write(*,*) 'mggltid status: ',pal_id

C     Write the palette to the HDF file.
      status = mgwrlut(pal_id, 3, DFNT_UINT8, MFGR_INTERLACE_PIXEL,
     +                 256, palette_data)
      write(*,*) 'mgwrlut status: ',status

C     Terminate access to the image.
      status = mgendac(ri_id)
      write(*,*) 'mgendac status: ',status

C     Terminate access to the GR interface.
      status = mgend(gr_id)
      write(*,*) 'mgend status: ',status

C     Close the file.
      status = hclose(file_id)
      write (*,*) 'hclose status: ', status

      return
      end

