; print a number to the screen.
; based on Ullrich von Bassewitz's itoa.s from the cc65 lib src.
; it's modified to:
; - only support base 10.
; - only support unsigned int.
; - print the result directly to the fnchat screen, or
; - store the result directly in numbuf.

 .importzp sreg
 .import _scr_putc_active, _scr_current, _scr_active, _numbuf
 .export _scr_cur_printnum, _scr_act_printnum, _num_to_numbuf

 ; sreg+2 bit 7 is a flag that means "print" if set, or "store in numbuf:
 ; if clear. also, the bottom bits of sreg+2 are the buffer position, when
 ; bit 7 is clear.

_num_to_numbuf:
 ldy #0
 sty sreg+2
 beq printnum

_scr_cur_printnum:
 ldy _scr_current
 sty _scr_active

_scr_act_printnum:
 ldy #$80
 sty sreg+2

printnum:
 sta sreg
 stx sreg+1

 lda #0
 pha ; sentinel

divloop:
 ldy #$10 ; 16-bit remainder
 lda #0

shift:
 asl sreg
 rol sreg+1
 rol a
 cmp #$0a ; radix
 bcc nosub
 sbc #$0a
 inc sreg

nosub:
 dey
 bne shift

 ora #$30 ; make it an ASCII digit
 pha ; save digit on stack

 ; are we done yet?
 lda sreg
 ora sreg+1
 bne divloop ; nope!

 ; get the results from the stack and print.
digitloop:
 pla
 beq done ; found sentinel? we're done.
 ldy sreg+2
 bpl store
 jsr _scr_putc_active
 jmp digitloop

store:
 sta _numbuf,y
 iny
 lda #0
 sta _numbuf,y
 sty sreg+2
 beq digitloop ; branch always

done:
 rts
