// Mike Gellman
// 7/23/02
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// This function adds two one bit digits with a carry.
void addDigit(int iDig1, int iDig2, char &cRes, int &iCarryOver)
{
	// Compute the initial sum.
	int iSum = iDig1 + iDig2 + iCarryOver;

	// Split initial sum into sum and carry components.
	cRes = (char)('0'+(iSum%2));
        iCarryOver = iSum/2;
}

// Adds two eight bit 2s complement integers and returns the answer in a
// character array.
char * add(char caNum1[], char caNum2[])
{
	int i;
	char * cpSum = new char[100];
	int iCarryOver=0;
	cpSum[8]='\0';
	char caTempNum1[100];
	char caTempNum2[100];
	strcpy(caTempNum1,caNum1);
	strcpy(caTempNum2,caNum2);

	// Add the digits normally, from least significant bit on...
	for (i=7;i>=0;i--)
	{
		addDigit(atoi(caTempNum1+i),atoi(caTempNum2+i),cpSum[i],iCarryOver);
		caTempNum1[i] = '\0';
		caTempNum2[i] = '\0';
	}

	// Checking for the overflow case. Only occurs if the sign bits of
	// the two numbers are the same, but the answer sign bit has
	// flipped.
	if ( ( caNum1[0] == caNum2[0] ) && ( cpSum[0] != caNum1[0] ) )
	{
		sprintf(cpSum,"OVERFLOW");
	}

	return(cpSum);

}




void main (int argc, char *argv[])
{
	char caLine[100], caNum1[100], caNum2[100];
	char *cpNum3=NULL;
	int i;

	// Open the input file.
	FILE *fp=fopen("addition.in","r");
	if (fp) 
	{
		// Loop until all input lines have been read in.
		while ( fgets(caLine,100,fp) )
		{
			// Copy both numbers into the appropriate arrays.
			for (i=0;i<8;i++ )
				caNum1[i] = caLine[i];
				
			for ( i=9;i<=16;i++)
				caNum2[i-9] = caLine[i];
				
			caNum1[8] = '\0';
			caNum2[8] = '\0';

			// Add the values.
			cpNum3 = add(caNum1,caNum2);

			// Print out the result.
			printf("%s + %s = %s\n",caNum1,caNum2,cpNum3);
		}
	}
}
