# CopyChunky(dst:r3:PTR TO chunky,r4:d0:LONG,dy:r5:LONG,
#            src:r6:PTR TO chunky,sx:r7:LONG,sy:r8:LONG,
#            w:r9:LONG,h:r10:LONG)

	.global	_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
	lwz	r11,0(r3)		# get dest width to r30
#	muls.l	d1,d6
	mullw	r11,r11,r5
#	add.l	d6,d0		# now we have start position in dest buffer
	add	r4,r11,r11	# now we have start position in dest buffer
#	move.l	(8,a0),a2
	lwz	r12,8(r3)
#	add.l	d0,a2
	add	r13,r13,r4

#	move.l	(a1),d6
	lwz	r11,0(r6)
#	muls.l	d3,d6
	mullw	r11,r11,r8
#	add.l	d6,d2
	add	r7,r7,r11
	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
