
	opt	o+,ow-
	bra	_START
; A small utility to run from the CLI. You enter HEX <word> and the
;decimal value is printed. The word MUST be 4 digits so don't forget
;leading zeros.

;eg 1>hex 10AF  at the command line would yield the result:4367

WBC	equ	1

	incdir	"source_2:includes/"
	include	"header.asm"

MAIN	MOVEA.L	COMMAND,A0
	CMPI.B	#'?',(A0)
	BEQ	USAGE
	BSR	FORMWORD
	CMPI.B	#$FF,D0
	BEQ	ERR
	MOVE.W	D1,D0
	BSR	ASCIIdec
	DOSPRINT	STDOUT,#STRSTART
BYE	RTS
	
ERR	DOSPRINT	STDOUT,#ERRORTEXT

USAGE	DOSPRINT	STDOUT,#USETEXT
	BEQ	BYE

; A subroutine to convert a word to a decimal number for printing
; ENTRY     d0=word to be converted.
; CORRUPTED a0,d0,d1
; ASCII string ready for printing starts at STRSTART

ASCIIdec	lea	STRSTART,a0	get addr of ASCII string
	moveq	#' ',d1	d1=ASCII code of space
clrloop	move.b	d1,(a0)+	1st char=space
	move.b	d1,(a0)+	2nd char=space
	move.b	d1,(a0)+	3rd char=space
	move.b	d1,(a0)+	4th char=space
	move.b	#'0',(a0)+	5th char=a zero (routine quits
;			if called with d0=0
DIVLOOP	tst.w	d0	test if d0=0
	beq.s	FIN	if it does then exit
	divu	#$0A,d0	divide num by 10
	move.l	d0,d1	copy result
	swap	d1	move remainder int MSW
	addi.w	#'0',d1	convert to ASCII digit
	move.b	d1,-(a0)	store this digit
	and.l	#$FFFF,d0	mask off remainder
	bra.s	DIVLOOP	loop back for next digit
	
FIN	rts		finished so exit

STRSTART	DC.B	'PPPPP'
	DC.B	10,0
		


; A subroutine that converts a hex string into a word stored in d1
; ENTRY	A0-->ASCII string
; EXIT	D1=data
; CORRUPTED	d0,d1,d2,a0

FORMWORD	MOVEQ	#0,D0	d0=0
	MOVE.L	D0,D1	d1=0
	MOVEQ	#3,D2	d2=3 our char counter
NEXTCHAR	MOVE.B	(A0)+,D0	get char
	BSR	GETNIBBLE	convert to nibble
	CMPI.B	#$FF,D0	check for error
	BEQ	ERROR	if so then leave
	OR.B	D0,D1	copy nibble into d1
	ASL.L	#4,D1	shift to make room for next
	DBRA	D2,NEXTCHAR	loop back if mored chars expected
	ASR.L	#4,D1	correct data word
ERROR	RTS		finished so return

GETNIBBLE	SUBI.B	#'0',D0	offset for digit
	CMPI.B	#9,D0	check if >9
	BLS	OK	if not weve finished
	SUBI.B	#7,D0	offset for char a
	CMPI.B	#15,D0	check its a hex digit	
	BLS	OK	if not user error
	MOVE.L	#$FF,D0	set d0 to show error
OK	RTS		finished so return

USETEXT	DC.B	10,'Usage: hex <word>'
	DC.B	10,'Where <word> means 4 hex digits'
	DC.B	10,10,'nb. All hex digits MUST be upper case!',10,0
	EVEN
ERRORTEXT	DC.B	10,'WARNING ! suspect data error.',10,0
	EVEN

