//------------------------------------------------------------------------
//                             Library CBM I/O
//
// Author: Mattias Hansson
// Copyright (c) : 2005 Mattias Hansson
// License: GNU LGPL 2
// Language: 65CM v0.4+
// Dependencies: (all libs might be included, selectively)
// Target: CBM computers.
//
// Purpose: To shorten lib names to normal usage length
//------------------------------------------------------------------------

#IFNDEF __LIB_CBMIO
#DEFINE __LIB_CBMIO = 1


GOTO lib_cbmio_skip

FUNC lib_cbmio_print ( {WORD strptr} )
  //On c64 we "borrow" the undocumented "print zero-terminated string" routine
  #IFDEF MACHINE_C64
  ASM
    lda |strptr|
    ldy |strptr|+1
    jsr $ab1e ; strout kernal routine
  ENDASM
  #IFEND
  #IFNDEF MACHINE_C64
    BYTE ch
    ch = PEEK strptr
    WHILE ch
      GOSUB $ffd2 PASSING ch AS ACC
      strptr++
      ch = PEEK strptr
    WEND
  #IFEND
FEND

FUNC lib_cbmio_printlf ( {WORD strptr} )

  CALL lib_cbmio_print ( strptr )
  CALL lib_cbmio_print ( @lib_cbmio_tl_linefeed )

FEND

FUNC lib_cbmio_lf

  CALL lib_cbmio_print ( @lib_cbmio_tl_linefeed )

FEND

FUNC lib_cbmio_home

  CALL lib_cbmio_print ( @lib_cbmio_tl_home )

FEND


FUNC lib_cbmio_cls

  CALL lib_cbmio_print ( @lib_cbmio_tl_cls )

FEND

ASM
lib_cbmio_tl_home
  !8 19, 0
lib_cbmio_tl_cls
  !8 147, 0
lib_cbmio_tl_linefeed
  !8 13, 0
lib_cbmio_text_nullstr
  !8 0
ENDASM


FUNC lib_cbmio_hexoutb ( {BYTE value} )
  ASM
    ;ldy #0
    ;lda (lib_cbmio_ho_varaddress),y
    lda |value|
    and #$0f
    tax
    lda lib_cbmio_ho_hexdigits,x
    sta lib_cbmio_ho_hextxt+1
    ;lda (lib_cbmio_ho_varaddress),y
    lda |value|
    lsr
    lsr
    lsr
    lsr
    tax
    lda lib_cbmio_ho_hexdigits,x
    sta lib_cbmio_ho_hextxt
  ENDASM
  CALL lib_cbmio_print ( @lib_cbmio_ho_hextxt )

FEND

FUNC lib_cbmio_hexoutw ( {WORD value} )
  BYTE high
  BYTE low
  
  // Extract high byte (shift right 8 bits)
  high = value >> 8
  
  // Extract low byte (direct assignment takes low byte)
  low = value
  
  // Print high byte then low byte (big-endian order)
  CALL lib_cbmio_hexoutb ( high )
  CALL lib_cbmio_hexoutb ( low )
FEND

FUNC lib_cbmio_input ( {WORD strptr} )
  BYTE ch

  ch = 0
  WHILE ch <> 13
    ASM
      jsr $ffcf
      sta |ch|
    ENDASM
    POKE strptr , ch
    strptr++
  WEND
  strptr-- //replace ending #13 with #0
  POKE strptr , 0
FEND

ASM

lib_cbmio_ho_hextxt
  !8 0,0,0

lib_cbmio_ho_hexdigits
  !pet "0123456789abcdef"
ENDASM


LABEL lib_cbmio_skip
#IFEND
