#include "digirule1.h"

///////////////////////////////////////////////////////////////////////////////
// private data

static uint8 a_reg, b_reg;

static void eval( void );

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

void mode_logic_init( void )
{
	all_leds_set( 0 );
	OR_LED = 1;
	a_reg = b_reg = 0;
}

void mode_logic_process( void )
{
	if( button.down.pressed )
		ctr_leds_set( ctr_leds_get() - 1 );
	
	else if( button.up.pressed )
		ctr_leds_set( ctr_leds_get() + 1 );
	
	else if( button.a.pressed )
	{
		A_LED = 1;
		a_reg = ctr_leds_get();
		eval();
	}
	else if( button.a.released )
		A_LED = 0;
		
	else if( button.b.pressed )
	{
		B_LED = 1;
		b_reg = ctr_leds_get();
		eval();
	}
	else if( button.b.released )
		B_LED = 0;
	
	else if( button.gate_select.pressed )
	{
		if( OR_LED )		// select next function
		{
			OR_LED = 0;
			AND_LED = 1;
		}
		else if( AND_LED )
		{
			AND_LED = 0;
			XOR_LED = 1;
		}
		else if( XOR_LED )
		{
			XOR_LED = 0;
			NOR_LED = 1;
		}
		else if( NOR_LED )
		{
			NOR_LED = 0;
			NAND_LED = 1;
		}
		else if( NAND_LED )
		{
			NAND_LED = 0;
			XNOR_LED = 1;
		}
		else if( XNOR_LED )
		{
			XNOR_LED = 0;
			OR_LED = 1;
		}

		eval();
	}
}

///////////////////////////////////////////////////////////////////////////////
// private functions

static void eval( void )
{
	union8_t temp;
	
	if( OR_LED )
		temp.byte = a_reg | b_reg;
	
	else if( AND_LED )
		temp.byte = a_reg & b_reg;
				
	else if( XOR_LED )
		temp.byte = a_reg ^ b_reg;
				
	else if( NOR_LED )
		temp.byte = ~(a_reg | b_reg);
	
	else if( NAND_LED )
		temp.byte = ~(a_reg & b_reg);
				
	else if( XNOR_LED )
		temp.byte = ~(a_reg ^ b_reg);
	
	SR_LED = temp.bit3;
	JK_LED = temp.bit2;
	T_LED  = temp.bit1;
	D_LED  = temp.bit0;
}
