// This may look like C code, but it is really -*- Asm -*-
/*
 *  smoke16/src16/_sdiv.s - Signed divide function.
 *  $Revision: 1.1 $
 *  Copyright 1997, 2000, Benjamin Sittler
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#define SIGFPE 8 /* signal to raise on divide by zero */

	.text
	.align 1

	// _sdiv -- divides the signed short in x (%a0) by the signed
	// short in y (%a1), placing the result in %a0. Currently, it
	// uses _udiv to do the dirty work.

	// the remainder is left in %a1

	// short _sdiv(short x, short y)
	// x:		dividend (%a0)
	// y:		divisor (%a1)
	// returns:	quotient (%a0), remainder (%a1)
	.global __sdiv
__sdiv:	push %t0 // negative result flag
	push %t1 // copy of dividend, for remainder sign
	mov %0, %t0
	mov %a0, %t1
	// check for negative x
	cmp %a0, %0
	bge sdiv0
	sub %0, %a0, %a0
	sub %0, %a1, %a1
sdiv0:	// check for negative y
	cmp %a1, %0
	bge sdiv1
	sub %0, %a1, %a1
	add 1, %t0
sdiv1:	// we have _udiv do the dirty work
	push %ra
	call __udiv
	pop %ra
	// apply the quotient sign
	cmp %t0, %0
	be sdiv2
	sub %0, %a0, %a0
sdiv2:	// apply the remainder sign
	cmp %t1, %0
	bge sdivN
	sub %0, %a1, %a1
sdivN:	// done!
	pop %t1
	pop %t0
	ret
