/*
 * From "Optimizing Code Speed for the MaverickCrunch Coprocessor
 * http://www.cirrus.com/en/pubs/appNote/AN253-1.pdf
 *
 * Example 2: a Biquad IIR filter
 */

extern double fcoef[5];
extern double bdq1k[4];
extern double data[];
extern long nn;

void
iir_biquad_difference()
{
	double inp;
	double accumulator;
	long i;

	for (i=0; i<(long)nn; i++)
	{
		inp = data[i];
		accumulator = 0;
		accumulator -= fcoef[0]*bdq1k[0];
		accumulator -= fcoef[0]*bdq1k[1];
		accumulator += fcoef[2]*inp;
		accumulator += fcoef[3]*bdq1k[2];
		accumulator += fcoef[4]*bdq1k[3];

		// Update y[n] states (output history for feedback lines)
		bdq1k[1] = bdq1k[0];
		bdq1k[0] = accumulator;

		// Store the output
		data[i] = accumulator;

		// Update x[n] states (input history for delay lines)
		bdq1k[3] = bdq1k[2];
		bdq1k[2] = inp;
	}
}

/*
 * According to the example, two possible outputs are:

// Floating-point Biquad IIR
// (Basic: Non-optimized)
main_loop
    cfldrd temp2, [fcoef]
    cfldrd bqd1k_s0, [bdq1k]
    cfmuld acc, temp2, bqd1k_s0
    cfnegd acc, acc
    cfldrd temp2, [fcoef, 8]
    cfldrd bqd1k_s1, [bdq1k, 8]
    cfmuld temp, temp2, bqd1k_s1
    cfsubd acc, acc, temp
    cfldrd temp2, [fcoef, 16]
    cfldrd temp4, [data]
    cfmuld temp, temp2, temp4
    cfaddd acc, acc, temp
    cfldrd temp2, [fcoef, 24]
    cfldrd bqd1k_s2, [bdq1k, 16]
    cfmuld temp, temp2, bqd1k_s2
    cfaddd acc, acc, temp
    cfldrd temp2, [fcoef, 32]
    cfldrd bqd1k_s3, [bdq1k, 24]
    cfmuld temp, temp2, bqd1k_s3
    cfaddd acc, acc, temp
    cfstrd acc, [data], 8
    cfstrd acc, [bdq1k]
    cfstrd bqd1k_s0, [bdq1k, 8]
    cfstrd temp4, [bdq1k, 16]
    cfstrd bqd1k_s2, [bdq1k, 24]
    subs nn, nn, 1
    bgt main_loop

// Floating-point Biquad IIR
// (Optimized)
    cfldrd bqd1k_s0, [bdq1k]
    cfldrd bqd1k_s1, [bdq1k, 8]
    cfldrd bqd1k_s2, [bdq1k, 16]
    cfldrd bqd1k_s3, [bdq1k, 24]
    cfldrd outp, [fcoef]
    cfldrd temp1, [fcoef, 8]
    cfldrd temp2, [fcoef, 16]
    cfldrd temp3, [fcoef, 24]
    cfldrd temp4, [fcoef, 32]
    cfnegd outp, outp
    cfnegd temp1, temp1
main_loop:
				;Insns between set and use
    cfldrd inp, [data]			;4
;2 x stall bqd1k_s0
    cfmuld acc, outp, bqd1k_s0		;2
    cfmuld temp, temp1, bqd1k_s1	;1
    cfcpyd bqd1k_s1, bqd1k_s0		;oxo
;4 x stall temp
    cfaddd acc, acc, temp		;1
    cfmuld temp, temp2, inp		;0
;11 x stall temp
    cfaddd acc, acc, temp		;1
    cfmuld temp, temp3, bqd1k_s2	;0
;11 x stall temp
    cfaddd acc, acc, temp		;3
    cfmuld temp, temp4, bqd1k_s3	;2
    cfcpyd bqd1k_s3, bqd1k_s2		;oxo
    cfcpyd bqd1k_s2, inp		;oxo
;3 x stall temp
    cfaddd acc, acc, temp		;0
    cfcpyd bqd1k_s0, acc		;3
    subs nn, nn, 1
    bgt main_loop

    ldr temp1, =bqd1k_dCrstates
    cfstrd bqd1k_s0, [temp1]
    cfstrd bqd1k_s1, [temp1, 8]
    cfstrd bqd1k_s2, [temp1, 16]
    cfstrd bqd1k_s3, [temp1, 24]
*/

