module GetImage_m

! Get a "card image" from a column-binary "deck."

  implicit NONE

  integer, public, save :: UNIT = 10 ! I/O unit to use

  character(len=156), private, save :: Buf
  integer, private, save :: CurPos = 999

contains

  subroutine OpenImages ( File, IOSTAT, REC1, COL1 )
    use ReadCB_m, only: OpenCB, ReadCB
    character(len=*), intent(in) :: File
    integer, intent(out), optional :: IOSTAT
    integer, intent(in), optional :: REC1, COL1 ! Start here, default 1, 1
    integer :: MyStat ! Status to ignore in case of REC1
    call openCB ( File, Unit, IOSTAT, REC1 )
    if ( present(rec1) ) then
      call readCB ( unit, buf, myStat )
      if ( myStat /= 0 .and. myStat /= -3 ) then
        if ( present(iostat) ) then
          iostat = myStat
          return
        end if
        stop
      end if
      curpos = 0
    else
      curpos = 999
    end if
    if ( present(col1) ) curpos = col1 - 1
  end subroutine OpenImages

  subroutine GetImage ( Image, Flag, Insert )
    character(len=80), intent(out) :: Image
    integer, intent(out) :: Flag ! 0 = EOF, >0 = image length
    character, intent(in), optional :: Insert ! Insertion character, default ' '
    integer :: CH         ! A character from the buffer
    character :: MyInsert
    integer :: GC, RC, SC ! Group counter, Removed Counter, Significant Counter
    integer :: IG, IR, IS ! Indexes running to GC, RC, SC respectively

    myInsert = ''
    if ( present(insert) ) myInsert = insert

    ! Get the group count
    call get ( gc )
!print '(a,i0)', 'CURPOS = ', curpos
!print '(16o3.2)', ( ichar(buf(ig:ig)), ig = 1, 156 )
!print '(16(1x,a1))', ( char(ichar(buf(ig:ig))+32), ig = 1, 156 )
!print '(a,i0)', 'Group Count = ', gc
    flag = gc
    if ( flag == 0 ) return ! EOF
    flag = 0

    ! Unscramble GC groups
    do ig = 1, gc
      ! Get the removed character count and insert RC inserts
      call get ( rc )
!print '(a,i0)', 'Removed count = ', rc
      do ir = 1, rc
        flag = flag + 1
        image(flag:flag) = myInsert
      end do
      ! Get the significant character count and copy SC characters
      call get ( sc )
!print '(a,i0)', 'Significant character count = ', sc
      do is = 1, sc
        flag = flag + 1
        call get ( ch )
        image(flag:flag) = achar(ch+32)
!print '(a,o2,a,a)', 'Character = ', ch, ' = ', image(flag:flag)
      end do
!stop
    end do
  contains
    ! Get the next character.  Get a new buffer if necessary.
    subroutine Get ( ch )
      use ReadCB_m, only: ReadCB
      integer, intent(out) :: CH
      if ( curpos >= len(buf) ) then
        call readcb ( unit, buf )
        curpos = 0
      end if
      curpos = curpos + 1
      ch = ichar(buf(curpos:curpos))
    end subroutine Get

  end subroutine GetImage

  subroutine CloseImages ( IOSTAT )
    use ReadCB_m, only: CloseCB
    integer, intent(out), optional :: IOSTAT
    call CloseCB ( IOSTAT )
    curpos = 999
  end subroutine CloseImages

end module GetImage_m
