; Altirra BASIC - Utility module
; Copyright (C) 2014 Avery Lee, All Rights Reserved.
;
; Copying and distribution of this file, with or without modification,
; are permitted in any medium without royalty provided the copyright
; notice and this notice are preserved.  This file is offered as-is,
; without any warranty.

;==========================================================================
; Unsigned 16x16 -> 16 multiply.
;
; Inputs:
;	Multiplicand: FR0+1, FR0
;	Multiplier:   FR1+1, FR1
;
; Output:
;	16-bit result in [FR0+1, FR0+0]
;	C = 0 if OK
;	C = 1 if overflow
;
; Altered:
;	A, X, FR0+2, FR0+3
;
umul16x16_stafr1:
		sta		fr1
.proc	umul16x16
		;##TRACE "umul16x16(%u,%u)" dw(fr0) dw(fr1)
		mva		fr0 fr0+2
		lda		#0
		sta		fr0+0
		ldx		#16
bitloop:
		;shift result left
		asl		fr0+0
		rol
		bcs		overflow
		
		;stash result hi
		tay
		
		;shift multiplicand left
		asl		fr0+2
		rol		fr0+1
		bcc		no_add
		
		;add multiplier to result
		clc
		lda		fr0
		adc		fr1
		sta		fr0
		tya
		adc		fr1+1
		bcs		overflow
no_add:
		dex
		bne		bitloop
		sta		fr0+1
overflow:
		;##TRACE "umul16x16 result %u" dw(fr0)
		rts
		
.endp

;==========================================================================
; Unsigned 16-bit x #6 multiply.
;
; Inputs:
;	Multiplicand: FR0+1, FR0
;
; Output:
;	16-bit result in [FR0+1, FR0]
;	C = 0 if OK
;	C = 1 if overflow
;
.proc umul16_6
		lda		fr0
		ldy		fr0+1
		asl
		rol		fr0+1
		bcs		xit
		adc		fr0
		sta		fr0
		tya
		adc		fr0+1
		bcs		xit
		asl		fr0
		rol
		sta		fr0+1
xit:
		rts
.endp
