# copies chunky data from source to destination with clipping

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

	.text
	.global	_CopyChunky
_CopyChunky:
	mr.	r11,r4	# clip left
	blt	.ok1
	li	r4,0
	sub	r7,r7,r11
.ok1:
	mr.	r11,r5	# clip top
	blt	.ok2
	li	r5,0
	sub	r8,r8,r11
.ok2:
	lwz	r0,0(r3)	# clip right
	sub.	r11,r0,r4
	blt	.finish		# whole source is behind right side of the dest
	add.	r11,r4,r9
	blt	.finish		# whole source is behind left side of the dest
	sub.	r11,r0,r11
	bgt	.ok3
	add	r9,r9,r11
.ok3:
	lwz	r0,4(r3)	# clip bottom
	sub.	r11,r0,r5
	blt	.finish		# whole source is below the dest
	add.	r11,r5,r10
	blt	.finish		# whole source is above the dest
	sub.	r11,r0,r11
	bgt	.ok4
	add	r10,r10,r11
.ok4:
	lwz	r0,0(r3)
	mullw	r5,r5,r0
	add	r5,r5,r4	# offset of the first pixel in the dest
	lwz	r3,8(r3)
	add	r3,r3,r5	# jump to the offset
	sub	r4,r0,r9	# rest width of the dest

	lwz	r0,0(r6)
	mullw	r8,r8,r0
	add	r8,r8,r7	# offset of the first pixel in the source
	lwz	r6,8(r6)
	add	r6,r6,r8	# jump to the offset
	sub	r7,r0,r10	# rest width of the source

	mr	r11,r9	# store width
.loopy:
	mr	r9,r11	# restore width
	subi	r3,r3,1
	subi	r6,r6,1
.loopx:
	lbzu	r0,1(r6)
	stbu	r0,1(r3)
	subic.	r9,r9,1
	bgt	.loopx

	add	r3,r3,r4	# add the rest
	add	r6,r6,r7

	subic.	r10,r10,1
	bgt	.loopy

.finish:	blr
