	TITLE homework 3 -- Multiplication two ways

	.model small
	.stack 100h

	.data

prompt1 db	"Enter multiplicand:  $"

	.code
	.startup

	;prompt for first input
	mov	ah, 09h
	mov	dx, offset prompt1
	int 21h

	call	readint

	; put the rest of your program here!!!

	.exit

	;The Irvine I/O procedures follow

	.code
readint proc
	push	bx
	push	cx
	push	dx
	push	si
	mov	dx, offset inputarea	;input the string
	mov	ah, 0ah
	int	21h
	mov	si, offset inputarea+2
	mov	cx, 0				;scan for leading spaces
	mov	cl, inputarea+1		;get number of chars entered
	or	cx,cx				;any chars entered?
	jnz	L1				;yes: continue
	mov	ax, 0				;no: set value to zero
	jmp	L7				;exit procedure

L1:	mov	al, [si]			;get a character from buffer
	cmp	al, ' '			;space character found?
	jnz	l2				;no: check for a sign
	inc	si				;yes: point to next char
	loop	l1
	jcxz	l7				;quit if all spaces

L2:	mov	sign,1			;assume number is positive
	cmp	al, '-'			;minus sign found?
	jnz	L3				;no, look for plus sign
	mov	sign, -1			;yes: sign is negative
	inc	si				;point to next char
	jmp	L4

L3:	cmp	al, '+'			;plus sign found?
	jnz	L4				;no: must be a digit
	inc	si				;yes: skip over the sign

L4:	mov	ax, 0				;clear accumulator
	mov	bx, 10			;BX is the divisor

L5:	mov	dl, [si]			;get character from buffer
	cmp	dl, '0'			;character < '0'?
	jl	L7				;yes: resolve sign and exit
	cmp	dl, '9'			;character < '9'?
	jg	L7				;yes: resolve sign and exit
	and	dx, 000fh			;no: convert to binary
	push	dx				;save the digit
	mul	bx				;DX:AX = AX * BX
	pop	dx				;restore the digit
	jc	L6				;quit if result too large
	add	ax, dx			;add new digit to AX
	jc	L6				;quite if result too large
	inc	si				;point to next digit
	jmp	L5				;get another digit

	;overflow must have occured
L6:	mov	dx, offset overflow_msg
	mov	ah, 9
	int 	21h
	mov	ax, 0				;set result to zero

L7:	mul	sign				;AX = AX * sign
	pop	si
	pop	dx
	pop	cx
	pop	bx
	ret
readint endp

	.data	
sign	dw	?
inputarea db	10, 0, 10 dup(' ') ; up to 9 digits
overflow_msg db	' <integer overflow> $'

	.code
wrint	proc
	push	ax				;save registers
	push	bx
	push	cx
	push 	dx
	push	di
	mov	cx, 0				;set digit counter to zero
	mov	di,offset buffer_A + 6 	;point past the end of buffer

	;Divide AX, convert remainder to ASCII

	mov	bx, 10			;divisor = 10
A1:	mov	dx, 0				;clear dividend to zero
	div	bx				;divide AX by 10
	or	dl, 30h			;convert remainder to ASCII
	dec	di				;reverse through the buffer
	mov	[di], dl			;store ASCII digit
	inc	cx				;increment count
	or	ax, ax			;quotient = zero?
	jnz	A1				;no, divide again

	;Display the buffer, using CX as a counter.
A2:	mov	ah, 2				;function: display character
	mov	dl, [di]			;get digit from buffer
	int	21h				;call DOS
	inc	di				;point to next digit
	loop	A2

	pop	di				;restore registers
	pop	dx
	pop	cx
	pop	bx
	pop	ax
	ret
wrint endp

	.data
buffer_A db	6 dup(' ')

	end