#include <stdlib.h>
#include "\digilent\digilab\digilab\digilab.h"


#define WORD_SIZE			32
#define SMALL_WORD_SIZE		4	// 
#define SMALL_ADDER_SIZE	5	// Always small_word_size+1 for carry
#define CARRY_SIZE			1		
#define MAX_SMALL_RESULT	8	// This is always 2^(small_word_size -1)

int SMALL_WORD_SIZE adder(int SMALL_WORD_SIZE x, int SMALL_WORD_SIZE y, int CARRY_SIZE *c)
{
	int SMALL_ADDER_SIZE mycarry, tmpx, tmpy, sum;

	tmpx = 0@x;
	tmpy = 0@y;
	mycarry = 0@(*c);
	sum = tmpx + tmpy + mycarry;
	*c = sum[4]; // The carry is in the 5th bit.
	return sum<-SMALL_WORD_SIZE;
}

int WORD_SIZE bigadder(int WORD_SIZE x, int WORD_SIZE y, int CARRY_SIZE *c)
{
	int WORD_SIZE result;
	int SMALL_WORD_SIZE small_result;
	int WORD_SIZE tmpx, tmpy, tmp_result;
	unsigned 6 i;

	// Initially carry is 0
	*c = 0;


	// Result is 0
	result = 0;

	// Copy to temporary variables so as not to alter the call variables

	tmpx = x;
	tmpy = y;
			
	
	for(i=0; i<WORD_SIZE/SMALL_WORD_SIZE; i++)
	{
		small_result = adder(tmpx<-SMALL_WORD_SIZE, tmpy<-SMALL_WORD_SIZE, c);
		
		tmp_result = 0@(small_result<-SMALL_WORD_SIZE);
		tmp_result = tmp_result << (i * SMALL_WORD_SIZE);
		result = result | tmp_result;

		// Hack off the LS 4 bits and start again

		tmpx = 0@(tmpx \\ SMALL_WORD_SIZE);
		tmpy = 0@(tmpy \\ SMALL_WORD_SIZE);
	} 

	return result;
}

void main(void)
{
	int 32 x, y, result;
	int 1 c;
	x = 18372;
	y = 84382;

	DLabLEDDriver();
	result = bigadder(x, y, &c);
	DLabSetLEDs((unsigned) result<-8);
}