program reftab
  implicit none
  integer, pointer:: reftable(:)
  integer, parameter:: MSGWORDS = 20
  nullify(reftable)
  call mainloop
  deallocate(reftable)
contains

  subroutine init
    use n3hashraw, only: htinit_pre, htinit
    integer:: nalloc
    call htinit_pre(klen=1, vlen=MSGWORDS, nalloc=nalloc)
    allocate(reftable(nalloc))
    call htinit(reftable, klen=1, vlen=MSGWORDS)
  end subroutine

  subroutine enlarge_table
    use n3hashraw, only: IDX_KLEN, IDX_VLEN, IDX_ALL_ENTS, htwords, htcopy
    integer, pointer:: otab(:)
    integer:: nent_new, nalloc
    otab => reftable(:)
    nent_new = otab(IDX_ALL_ENTS) * 2
    nalloc = htwords(otab(IDX_KLEN), otab(IDX_VLEN), nent_new)
    allocate(reftable(nalloc))
    call htcopy(otab, reftable, nent_new)
    deallocate(otab)
  end subroutine

  subroutine fileloop(filename)
    use n3bits, only: atoipack
    use n3hashraw, only: htprobe, htput
    character(*), intent(in):: filename
    character(256):: line
    character(20):: numbuf
    integer:: linebuf(MSGWORDS)
    integer:: iostat
    integer:: colon
    integer:: iref(1)
    open(unit=10, file=filename, action="READ", status="old", iostat=iostat)
    if (iostat /= 0) return
    do
      read(unit=10, fmt='(A)', iostat=iostat) line
      if (iostat /= 0) exit
      colon = index(line, ': ')
      if (colon == 0) cycle
      numbuf = line(1: colon-1)
      read(numbuf, fmt='(I20)') iref(1)
      call atoipack(line(colon+2: ), linebuf, MSGWORDS)
      call htprobe(reftable, iref, iostat)
      if (iostat /= 0) call enlarge_table
      call htput(reftable, iref, linebuf, iostat)
      if (iostat /= 0) stop '*** htput failure'
    enddo
    close(unit=10)
  end subroutine

  subroutine mainloop
    use n3hashraw, only: htdump
    character(512):: filename
    integer:: iostat
    call init
    do
      read(unit=*, fmt='(A)', iostat=iostat) filename
      if (iostat /= 0) exit
      write(unit=0, fmt='(A)', iostat=iostat) &
        & 'reading ' // trim(filename) // ' ...'
      call fileloop(filename)
    enddo
    call htdump(reftable)
  end subroutine

end program
