program errtab
  implicit none
  character(200):: input
  character(200):: linebuf
  character(32):: symbol
  character(64):: message
  integer:: tabsiz, iostat, i
  read(*, '(A)') input
  open(10, file=input, action='READ', status='OLD')
  !
  ! === part 1: error message table ===
  !
  ! COUNT NUMBER OF LINE, DEFINE ERROR CODE CONSTANTS
  !
  tabsiz = 0
  do
    read(unit=10, fmt='(A)', iostat=iostat) linebuf
    if (iostat /= 0) exit
    call parse(linebuf, symbol, message, iostat)
    if (iostat /= 0) cycle
    tabsiz = tabsiz + 1
    write(*, '(6X,A,A,A,I5)') 'INTEGER, PARAMETER:: ', symbol, ' = ', tabsiz
  enddo
  write(*, '(6X,A,I5,A)') 'CHARACTER(48):: ERRMSG(', TABSIZ, ')'
  !
  ! TABLE OF ERROR MESSAGE BY ERROR CODE
  !
  rewind(10)
  do
    read(unit=10, fmt='(A)', iostat=iostat) linebuf
    if (iostat /= 0) exit
    call parse(linebuf, symbol, message, iostat)
    if (iostat /= 0) cycle
    write(*, '(6X,A,A,A)') 'DATA ERRMSG(', symbol, ') &'
    write(*, '(5X,A,A,A)') '& /"', trim(message), '"/'
  enddo
  close(10)
contains

  subroutine parse(line, symbol, message, stat)
    character(*), intent(in):: line
    character(*), intent(out):: symbol, message
    integer, intent(out):: stat
    integer:: colon, quot
    stat = -1
    colon = index(line, ':')
    if (colon <= 1 .or. colon >= (len(line)-1)) return
    symbol = adjustl(line(1:colon-1))
    message = adjustl(line(colon+1: ))
    do
      quot = index(message, '"')
      if (quot == 0) exit
      if (quot == len(message)) then
        message(quot:quot) = ' '
      else
        if (quot <= (len(message) - 2)) message(quot+2: ) = message(quot+1: )
        message(quot+1:quot+1) = '"'
      endif
    enddo
    stat = 0
  end subroutine

end program
