/**
	\file hiresAsm.s
	
*/
#include <vs1005h.h>
#include <vstypes.h>
#include "miscAsm.h"


#ifdef ASM

/*
void LimitSlew(register __i0 s_int16 *data, register __i2 *mem, register __d0 u_int16 limit, register s_int16 __a0 stereoSamples) {
*/

/*
	Uses 8 clocks / unmodified sample, 13-14 clocks / modified sample

	-> typical performance penalty for 48 kHz stereo = 0.8 MIPS
	-> worst case performance penalty for 8 kHz stereo = 0.2 MIPS
	   (unless samples are provided one at a time, in which case
	   both performance penalties become significantly higher)
	
*/
#if 1
	.sect code,LimitSlew
	.export _LimitSlew
_LimitSlew:
	add a0,ones,a0;	ldx (i6)+1,null
	stx a1,(I6)+1;	sty d1,(I6)
	stx le,(I6)+1;	sty ls,(I6)
	stx c1,(I6)+1;	sty lc,(I6)
	stx b0,(I6)+1;	sty b1,(I6)


	jns $9
	asr d0,d1;	ldx (i2),a1;	sty c0,(I6)	// d1 = limitPer2, a1 = *mem

	loop a0,$1-1
	ldx (i0)+2,b0	// b0 = *data

	asr b0,b1;	ldx (i0)-2,b0	// b1 = *data>>1
	sub a1,b1,c0	    		// c0 = diff = *mem-(*data>>1)
	abs c0,c1			// c1 = abs(diff)
	sub c1,d1,c1
	nop
	jns $2
	add c0,null,c0	// if (diff < 0)

	nop
	jnc $3
	add a1,a1,c0

	j $4
	add c0,d0,c0
$3:
	sub c0,d0,c0
$4:
	asr c0,b1;	stx c0,(i0)

$2:
	add b1,null,a1; ldx (i0)+4,null	// *mem = *data++>>1;
	
$1:
	
$9:
	stx a1,(i2);	ldy (I6)-1,c0	// *mem = a1
	ldx (I6)-1,b0;	ldy (I6),b1
	ldx (I6)-1,c1;	ldy (I6),lc
	ldx (I6)-1,le;	ldy (I6),ls
	jr
	ldx (I6)-1,a1;	ldy (I6),d1
#endif

/*
void Sat16Buffer(register __i0 s_int16 *data, register __d0 u_int16 limit, register __a0 s_int16 n);
*/
/*
	Uses 3 clocks / sample
*/
#if 1
	.sect code,Sat16Buffer
	.export _Sat16Buffer
_Sat16Buffer:
	add a0,ones,a0; ldx (i6)+1,null
	stx a1,(I6)+1;	sty d1,(I6)
	stx le,(I6)+1;	sty ls,(I6)
	stx lc,(I6)

	jns $9
	add d0,d0,d1;	ldx (i0)+1,a1

	ldc MR_INT|MR_SAT,mr0

	loop a0,$9-1
	add a1,d0,a1
	
	sub a1,d1,a0;	ldx (i0)-1,a1
	add a0,d0,a0
	add a1,d0,a1;	stx a0,(i0)+2

$9:
	ldc MR_INT,mr0

	ldx (I6)-1,lc
	ldx (I6)-1,le;	ldy (I6),ls
	jr
	ldx (I6)-1,a1;	ldy (I6),d1
#endif


#endif

	.end



#if 0
	/********* EVERYTHING FROM NOW ON IS PURELY DECORATIONAL!!! **********/

/*
	void Generic(void) - 2018 edition
*/
	.sect code,Generic
	.export _Generic
_Generic:
	ldx (i6)+1,null
	stx i0,(I6)+1;	sty i1,(I6)
	stx i2,(I6)+1;	sty i3,(I6)
	stx le,(I6)+1;	sty ls,(I6)
	stx lr0,(I6)+1;	sty lc,(I6)
	stx a0,(I6)+1;	sty a1,(I6)
	stx b0,(I6)+1;	sty b1,(I6)
	stx c0,(I6)+1;	sty c1,(I6)
	stx d0,(I6)+1;	sty d1,(I6)
	stx i4,(I6)

	ldx (I6)-1,i4
	ldx (I6)-1,d0;	ldy (I6),d1
	ldx (I6)-1,c0;	ldy (I6),c1
	ldx (I6)-1,b0;	ldy (I6),b1
	ldx (I6)-1,a0;	ldy (I6),a1
	ldx (I6)-1,lr0;	ldy (I6),lc
	ldx (I6)-1,le;	ldy (I6),ls
	ldx (I6)-1,i2;	ldy (I6),i3
	jr
	ldx (I6)-1,i0;	ldy (I6),i1
#endif
