; CopyChunky(dst:a0:PTR TO chunky,dx:d0:LONG,dy:d1:LONG,
;            src:a1:PTR TO chunky,sx:d2:LONG,sy:d3:LONG,
;            w:d4:LONG,h:d5:LONG)

	machine	mc68020

	xdef	_CopyChunky
_CopyChunky
	movem.l	d2-d7/a2-a3,-(a7)

; DESTINATION BOUNDS
	tst.l	d0		; left bound
	bge.s	.leftdone
	move.l	d0,d7			; store left negative offset
	neg.l	d7
	cmp.l	d4,d7
	bge.s	.finish			; out of bounds
	moveq	#0,d0			; left position
	add.l	d7,d2
	sub.l	d7,d4			; new width
.leftdone
	tst.l	d1		; top bound
	bge.s	.topdone
	move.l	d1,d7			; store top negative offset
	neg.l	d7
	cmp.l	d5,d7
	bge.s	.finish			; out of bounds
	moveq	#0,d1			; top position
	add.l	d7,d3
	sub.l	d7,d5			; new height
.topdone
	cmp.l	(a0),d0		; right bound
	bgt.s	.finish
	move.l	(a0),d7			; store maximal width
	sub.l	d0,d7			; change width
	cmp.l	d4,d7			; check if we can fit
	bgt.s	.rightdone		; we can fit
	move.l	d7,d4			; new width, we can't fit
.rightdone
	cmp.l	(4,a0),d1		; bottom bound
	bgt.s	.finish
	move.l	(4,a0),d7			; store maximal width
	sub.l	d1,d7			; change width
	cmp.l	d5,d7			; check if we can fit
	bgt.s	.bottomdone		; we can fit
	move.l	d7,d5			; new width, we can't fit
.bottomdone

	move.l	(a0),d6		; get dest width to d6
	muls.l	d1,d6
	add.l	d6,d0		; now we have start position in dest buffer
	move.l	(8,a0),a2
	add.l	d0,a2

	move.l	(a1),d6
	muls.l	d3,d6
	add.l	d6,d2
	move.l	(8,a1),a3
	add.l	d2,a3		; and start position in source buffer

	move.l	(a0),d2		; get the d2 and d3 values
	sub.l	d4,d2
	move.l	(a1),d3
	sub.l	d4,d3

	subq.l	#1,d4
	subq.l	#1,d5
	move.l	d4,d6		; store width
.loopy	move.l	d6,d4		; restore width
.loopx	move.b	(a3)+,(a2)+	; copy pixel
	dbra.s	d4,.loopx
	adda.l	d2,a2
	adda.l	d3,a3
	dbra.s	d5,.loopy
.finish	movem.l	(a7)+,d2-d7/a2-a3
	rts
