;------------------------------------------------------------------------------
;hl=src de=dst
lz4decrunch:
	ld			bc,7
	add			hl,bc
	ld			c,(hl)
	inc			hl
	ld			b,(hl)						;剄剈剛剉剗 則剅刾 剄刾剒剟刾 剏剎 剎刾剆剙剕剙剅剓刾 - 剛刾剎剗剈剛
	inc			hl
	inc			hl
	inc			hl							;剘刾剦刾剕剙 剝剋刾剟剭剣 則刾剘剘剭剣 剝剙 剝剗剈剫剈剘剏剳 #0B

	ld			a,l
	add			a,c
	ld			(.endL+1),a
	ld			a,h
	adc			a,b
	ld			(.endH+1),a					;凨剙剘剈剦剘剭剒 刾則剛剈剝 剝剋刾剟剭剣 則刾剘剘剭剣

.loop:
	ld			a,(hl)
	inc			hl
	ld			(.litteral+1),a
	and			#F0
	jr			z,.copy						;凟剝剕剏 則剕剏剘刾 剛刾剅剘刾 0, 剝剓剙剚剏剛剙剅刾剟剮 剠剋剈 剚剈剛剈則刾剘剘剭剈 則刾剘剘剭剈
	rrca
	rrca
	rrca
	rrca
	ld			b,0
	ld			c,a
	cp			#0F
	call		z,.getlength			;凟剝剕剏 則剕剏剘刾 #0F, 剟剙 剚剙剕剠剦剏剟剮 則剙剚剙剕剘剏剟剈剕剮剘剠剱 則剕剏剘剠

	ldir								;凱剈剛剈則刾剦刾 剘刾剦剏剘刾剈剟剝剳 剝剙 剝剕剈則剠剱剫剈剒 剏剘剢剙剛剗刾剤剏剏 剙 則剕剏剘剈

.copy:
	ld			a,l						;則剙剝剟剏剆剕剏 剕剏 剝剋刾剟剭剈 則刾剘剘剭剈 剓剙剘剈剦剘剙剆剙 刾則剛剈剝刾
.endL:
	sub			#FF
	ld			a,h
.endH:
	sbc			a,#FF
	ret			nc						;刕剢剢剈剓剟剏剅剘刾剳 剚剛剙剅剈剛剓刾 zf=1

	ld			c,(hl)
	inc			hl
	ld			b,(hl)					;bc=2byte 刋剟剈剘剏剈 剎剘刾剦剈剘剏剳 剝剗剈剫剈剘剏剳
	inc			hl

.litteral:
	ld			a,0						;litteral 剚剈剛剈剚剏剝刾剟剮 剎則剈剝剮
	and			#0F
	add			a,#04					;cf=0

	push		hl
	ld			h,d
	ld			l,e
	sbc			hl,bc					;hl=de-bc 処剝剚剙剕剮剎剠剒剟剈 則刾剘剘剭剈, 剓剙剟剙剛剭剈 剠剋剈 剄剭剕剏 剛刾剝剨剏剛剈剘剭, 剅 剓刾剦剈剝剟剅剈 剏剝剟剙剦剘剏剓刾 剚剈剛剈則刾剦剏

	ld			b,0
	ld			c,a
	cp			#0F+#04
	ex			(sp),hl
	call		z,.getlength
	ex			(sp),hl

	ldir								;凨剙剚剏剛剙剅刾剟剮 剚剈剛剈剘剙剝 剠剋剈 剛刾剎剅剈剛剘剠剟剭剣 則刾剘剘剭剣
	pop			hl
	jp			.loop

.getlength:								;凱剙剕剠剦剏剟剮 則剕剏剘剠 剄刾剒剟刾 剚剈剛剈剅剙則刾 (剄剙剕剮剨剈) bc=剟剈剓剠剫刾剳 剝剠剗剗刾 剚剈剛剈剅剙則刾
	ld			a,(hl)
	inc			hl
	cp			#FF						;#FF 剠則剅刾剏剅刾剈剟剝剳 剓刾剓 剎剘刾剓, 剎刾 剓剙剟剙剛剭剗 剝剕剈則剠剈剟 剏剘剢剙剛剗刾剤剏剳 剙 則剕剏剘剈
	jr			nz,.addlen
	inc			b
	dec			bc						;bc += 255
	jr			.getlength
.addlen:
	add			a,c
	ld			c,a
	adc			a,b
	sub			c
	ld			b,a						;bc=則剕剏剘刾 剚剈剛剈則刾剅刾剈剗剙剆剙 剄刾剒剟刾
	ret

;------------------------------------------------------------------------------
;in: hl=剘刾剦刾剕剮剘剭剒 刾則剛剈剝 bc=則剕剏剘刾
;out: bcde=剛剈剎剠剕剮剟刾剟
crc32:
	push		hl
	push		bc

	ld			de,#FFFF				; 0xFFFFFFFF ? 剘刾剦刾剕剮剘剙剈 剎剘刾剦剈剘剏剈 CRC32, 剏剝剚剙剕剮剎剠剈剗剙剆剙 剅 ZIP
	ld			h,d
	ld			l,e
	ld			c,#20					;剝剙剓剛刾剫剈剘剏剈

	exx
	pop			hl
	dec			hl
	inc			h
	inc			l
	ld			b,l
	ld			c,h
	pop			hl
.loop1:
	ld			a,(hl)
	inc			hl
	exx

	xor			e
	ld			b,8
.loop2:
	srl			h
	rr			l
	rr			d
	rra
	jp			nc,.skip
	ld			e,a
	ld			a,h
	xor			#ED
	ld			h,a
	ld			a,l
	xor			#B8
	ld			l,a
	ld			a,d
	xor			#83
	ld			d,a
	ld			a,e
;	xor			#20
	xor			c
.skip:
	djnz		.loop2
	ld			e,a

	exx
	djnz		.loop1
	dec			c
	jp			nz,.loop1
	exx

	ld			a,h						;CRC32, 剏剝剚剙剕剮剎剠剈剗剭剒 剅 ZIP, 剚剛剏剘剏剗刾剈剟 xor 剝 0xFFFFFFFF 剅 剓剙剘剤剈
	cpl
	ld			b,a
	ld			a,l
	cpl
	ld			c,a

	ld			a,d
	cpl
	ld			d,a
	ld			a,e
	cpl
	ld			e,a
	ret
