;int2asc was printint
;Willard Goosey
;;1/7/2012

;$Id: int2asc.asm,v 1.1 2012/01/22 06:12:02 goosey Exp goosey $

;derived from _8080/Z80 Assembly Language_
;Alan Miller, 1981

;int2asc buffer get 16-bit int as decimal in 5 ASCII chars
;Entry Conditions: BC=int
;                  HL-> 6 byte buf
;Exit  Conditions: HL-> 6 byte buf with number, null terminated
;		   all registers preserved
int2asc:
	push psw
	push b
	push d
	push h
	call int2a
	pop h
	pop d
	pop b
	pop psw
	ret


;int2a   buffer gets 16-bit integer to decimal in 5 ASCII chars 
;Entry Conditions:  BC=int
;		    HL->6 byte buf
;Exit  Conditions:  A,BC,DE destroyed
;		    HL=HL+length of number
;                   bufer holds decimals of number null terminated

int2a:
	shld bufp	;bufp->buf
	call cbuf	;clear buf
	lxi h,0
	dad b		;HL=BC
	mvi b,0		;leading 0 flag
	lxi d,-10000	;2's compl
	call subtr	;10 thou
	lxi d,-1000
	call subtr	;thous
	lxi d,-100
	call subtr	;hundreds
	lxi d, -10
	call subtr	;tens
	mov a,l
	adi '0'
	jmp schar 


;subtract power of ten and count
subtr	mvi c,'0'-1	;ascii count
subtr2	inr c
	dad d		;add negative number
	jc subtr2	;keep going

	;one 2 many, add one back
	mov a,d		;complement DE
	cma		
	mov d,a
	mov a,e
	cma
	mov e,a
	inx d		;and

	dad d		;add back
	mov a,c		;get count

	;check for zero
	cpi '1'		;less than 1?
	jnc nzero	;no
	mov a,b		;check zero flag
	ora a		;set?
	mov a,c		;restore
	rz		;skip leading 0
	jmp schar
	
	; set flag for non-zero characters
nzero	mvi b,0ffh	;set 0 flag
	jmp schar	;print it

;schar: save char in a to buffer pointed to by bufp
schar	push h
	lhld bufp	;HL->buf
	mov m,a		;*HL=a
	inx h		;HL++
	shld bufp	;save bufp
	pop h
	ret

cbuf	mvi a,0		;A=0
cbuf1	mvi m,0		;*HL=0
	inr a		;A++
	cpi 6		;zeroed out six bytes?
	jc cbuf1	;loop if not
	ret		;done
	
;data section

bufp	dw 0
