#include "digirule1.h"

///////////////////////////////////////////////////////////////////////////////
// public functions

void all_leds_set( uint8 n )
{
	switch( n )
	{
		case 0:
			A_LED    = 0;
			B_LED    = 0;

			NOT_LED  = 0;
			OR_LED   = 0;
			AND_LED  = 0;
			XOR_LED  = 0;
			NOR_LED  = 0;
			NAND_LED = 0;
			XNOR_LED = 0;

			X_LED    = 0;

			SJTD_LED = 0;
			CLK_LED  = 0;
			RK_LED   = 0;

			SR_LED   = 0;
			JK_LED   = 0;
			T_LED    = 0;
			D_LED    = 0;

			Q_LED    = 0;
			QNOT_LED = 0;

			CTR8_LED = 0;
			CTR4_LED = 0;
			CTR2_LED = 0;
			CTR1_LED = 0;
			break;
			
		case 1:
			A_LED    = 1;
			B_LED    = 1;

			NOT_LED  = 1;
			OR_LED   = 1;
			AND_LED  = 1;
			XOR_LED  = 1;
			NOR_LED  = 1;
			NAND_LED = 1;
			XNOR_LED = 1;

			X_LED    = 1;

			SJTD_LED = 1;
			CLK_LED  = 1;
			RK_LED   = 1;

			SR_LED   = 1;
			JK_LED   = 1;
			T_LED    = 1;
			D_LED    = 1;

			Q_LED    = 1;
			QNOT_LED = 1;

			CTR8_LED = 1;
			CTR4_LED = 1;
			CTR2_LED = 1;
			CTR1_LED = 1;
			break;
			
		case 2:
			A_LED    ^= 1;
			B_LED    ^= 1;

			NOT_LED  ^= 1;
			OR_LED   ^= 1;
			AND_LED  ^= 1;
			XOR_LED  ^= 1;
			NOR_LED  ^= 1;
			NAND_LED ^= 1;
			XNOR_LED ^= 1;

			X_LED    ^= 1;

			SJTD_LED ^= 1;
			CLK_LED  ^= 1;
			RK_LED   ^= 1;

			SR_LED   ^= 1;
			JK_LED   ^= 1;
			T_LED    ^= 1;
			D_LED    ^= 1;

			Q_LED    ^= 1;
			QNOT_LED ^= 1;

			CTR8_LED ^= 1;
			CTR4_LED ^= 1;
			CTR2_LED ^= 1;
			CTR1_LED ^= 1;
			break;
	}
}

uint8 ctr_leds_get( void )
{
	union8_t temp;
	
	temp.byte = 0;
	temp.bit3 = CTR8_LED;
	temp.bit2 = CTR4_LED;
	temp.bit1 = CTR2_LED;
	temp.bit0 = CTR1_LED;
	
	return temp.byte;
}

uint8 ctr_leds_set( uint8 n )
{
	union8_t temp;
	
	temp.byte = n;
	CTR8_LED = temp.bit3;
	CTR4_LED = temp.bit2;
	CTR2_LED = temp.bit1;
	CTR1_LED = temp.bit0;
	
	return n;	// for convenience
}

// returns a pseudo-random number in the range 1..255
uint8 prng( void )
{
	static union16_t lfsr;
	uint8 n;
	
	// seed on first use (the LFSR will be zero after reset, but always non-zero after first use)
	if( lfsr.word == 0 )
		lfsr.low_byte = (ticks != 0) ? ticks : 1;
	
	n = lfsr.low_byte;
	lfsr.bit8 = lfsr.bit0 ^ lfsr.bit2 ^ lfsr.bit3 ^ lfsr.bit4;		// polynomial is x8 + x6 + x5 + x4 + 1
	lfsr.word >>= 1;
	
	return n;
}
