@ apLib decruncher for ARM
@
@ Based on the M68000 version by MML 2010
@ Size optimized (164 bytes) by Franck "hitchhikr" Charlet. 
@
@ ARM version by Mic 2010 (288 bytes)

	.section .text
	.align 2
	.arm
	
	.global		aplib_decrunch


@ r0 = packed data, r1 = dest
aplib_decrunch:
	stmfd	sp!,{r5-r12,lr}
	mov	r6,#1
copy_byte:
	ldrb	r12,[r0],#1
	strb	r12,[r1],#1
next_sequence_init:
	mov	r7,#0
next_sequence:
	bl	get_bit
	bcc	copy_byte
	bl	get_bit
	bcc	code_pair
	bl	get_bit
	mov	r10,#0
	bcc	short_match
	mov	r11,#4
get_offset:
	bl	get_bit
	adc	r10,r10,r10
	subs	r11,r11,#1
	bne	get_offset			
	cmp	r10,#0	
	beq	write_byte	
	sub	r12,r1,r10
	ldrb	r10,[r12]        
write_byte:
	strb	r10,[r1],#1
	b	next_sequence_init
code_pair:
	bl	decode_gamma
	subs	r10,r2,#2
	bne	normal_code_pair
	tst	r7,r7
	bne	normal_code_pair
	mov	r10,r8	
	bl	decode_gamma
	b	copy_code_pair
normal_code_pair:
	add	r10,r10,r7
	sub	r10,r10,#1	
	ldrb	r11,[r0],#1
	orr	r10,r11,r10,lsl#8
	bl	decode_gamma
	cmp	r10,#32000
	addcs	r2,r2,#1
	cmp	r10,#1280
	addcs	r2,r2,#1
	bcs	continue_short_match
	cmp	r10,#128
	addcc	r2,r2,#2
	b	continue_short_match	
get_bit:	
	subs	r6,r6,#1
	moveq	r6,#8
	ldreqb	r3,[r0],#1
	moveq	r3,r3,lsl#24
	movs	r3,r3,lsl#1
	mov	pc,lr
decode_gamma:
	stmfd	sp!,{lr}
	mov	r2,#1
get_more_gamma:
	bl	get_bit
	adc	r2,r2,r2
	bl	get_bit
	bcs	get_more_gamma
	ldmfd	sp!,{pc}
short_match:  
	ldrb	r10,[r0],#1
	tst	r10,#1
	movne	r2,#3
	moveq	r2,#2
	movs	r10,r10,lsr#1
	ldmeqfd	sp!,{r5-r12,lr}
	bxeq	lr
continue_short_match:
	mov	r8,r10
copy_code_pair:
	sub	r12,r1,r10
loop_do_copy:		
	ldrb	r5,[r12],#1
	strb	r5,[r1],#1
	subs	r2,r2,#1
	bne	loop_do_copy	
	mov	r7,#1	
        b   	next_sequence   
	


	



