module Page_m

  ! Type and scanner for ALD page heading

  ! P for page
  ! Book number
  ! Drawing number
  ! Logic number
  ! Frame/Channel number
  ! MFI
  ! Title in quotes
  ! Feature in quotes

  ! # bk drawing# logic#     FR_CH MFI  "title"                  "feature"
  ! P  7 761264   B9.40.12.1 00xc  M0   "Error stop read gating" "TAU 9"

  implicit None

  private

  public :: Draw_Head, Page_T, Parse_Page

  type :: Page_T
    integer :: Book
    integer :: Drawing
    character(10) :: Logic
    character(4) :: FR_CH = ''
    character(4) :: MFI = ''
    character(60) :: Title
    character(6) :: Feature
  end type Page_T

contains

  subroutine Parse_Page ( Line, N_Lines, Head )

  ! # bk drawing# logic#     FR_CH MFI  "title"                  "feature"
  ! P  7 761264   B9.40.12.1 00xc  M0   "Error stop read gating" "TAU 9"

    use Scan_m, only: Scan

    character(*), intent(inout) :: Line
    integer, intent(in) :: N_Lines
    type(page_t), intent(out) :: Head

    integer :: IOSTAT
    character(255) :: Token

    call scanTest ( 'book', *9 )
    read ( token, *, iostat=iostat ) head%book
    if ( iostat /= 0 ) then
      print *, 'Book number in heading not numeric at line', n_lines
      go to 9
    end if
    call scanTest ( 'drawing', *9 )
    read ( token, *, iostat=iostat ) head%drawing
    if ( iostat /= 0 ) then
      print *, 'Drawing number in heading not numeric at line', n_lines
      go to 9
    end if
    call scanTest ( 'logic', *9 )
    head%logic = token
    call scanTest ( 'FR_CH', *9 )
    head%FR_CH = token
    call scanTest ( 'MFI', *9 )
    head%MFI = token
    call scanTest ( 'Title', *9 )
    head%title = token(2:)
    call scanTest ( 'Feature', *9 )
    head%feature = token(2:)
  9 return
  contains

    subroutine ScanTest ( what, * )
      ! Scan for a token and test whether there is one
      character(len=*), intent(in) :: What
      call scan ( line, token )
      if ( token == '' ) then
        print *, 'Missing ', trim(adjustl(what)), &
          & ' for page heading at line', n_lines
        return 1
      end if
    end subroutine ScanTest

  end subroutine Parse_Page

  subroutine Draw_Head ( Head, Line )
    type(page_t), intent(in) :: Head
    character(len=*), intent(out) :: Line
    write ( line(1:7), '(i7.7)' ) head%drawing
    line(41:) = head%title
    line(92:) = head%feature
    line(107:) = head%logic
  end subroutine Draw_Head

end module Page_m
