/* add the letters in a file to those in another file */

#include <stdio.h>
#include <stdlib.h>

#define MaxLength 100000

int main(int argc, char *argv[])
{
   int	  letter1, letter2, out, lnthA, lnthB, i;
   int    h, inA[MaxLength], inB[MaxLength];
   FILE	*if1, *if2, *ofp;
   
   if (argc != 4) {
      printf("\n%s%s%s\n\n", "Usage: ", argv[0], " infile1 infile2 outfile");
      exit(1);
   }
   
   /*
   
   Open the files --- TODO: put error handling here
   
   */
   
   if1 = fopen(argv[1], "r");
   
   if2 = fopen(argv[2], "r");
   
   ofp = fopen(argv[3], "w");
   
   i = 0;
   out = 0;
   lnthA = 0;
   lnthB = 0;
   
   
   /*
   
   Load the files into arrays --- TODO: ???
   
   */
   
  for (h = 0; (letter1 = getc(if1)) != EOF; h++)
  {
  
    if ((letter1 == ' ') || (letter1 == '\t'))
    {
      letter1 = '\n';
    }

         
    if ((letter1 != '\n') && (h <= (MaxLength - 1)))
    {
      inA[i] = letter1;
      i = i + 1;
    }
    
  }
  
  lnthA = i;
  i = 0;
 
   for (h = 0; (letter2 = getc(if2)) != EOF; h++)
  {
  
    if ((letter2 == ' ') || (letter2 == '\t'))
    {
      letter2 = '\n';
    }

         
    if ((letter2 != '\n') && (h <= (MaxLength - 1)))
    {
      inB[i] = letter2;
      i = i + 1;
    }
    
  }
 
  lnthB = i;
  i = 0;
  
  
   /*
   Which is longer? Determines when to stop adding them together.
   TODO: there has got to be a better way to do all of this
   */

  if (lnthA > lnthB) {
      h = lnthB;
   }
   
  if (lnthB > lnthA) {
      h = lnthA;
   }
   
  if (lnthB == lnthA) {
      h = lnthA;
   }


   /*
   Now we add them together.
   TODO: there has got to be a better way?
   	 Also, maybe allow for different sorts of addition bounderies?
   */

 
  for (i = 0; i <= h; i++)
   	if ((inA[i] >= '!' &&  inA[i] <= '~') && 
	    (inB[i] >= '!' && inB[i] <= '~'))
	
	{  
	   out = inA[i] + inB[i];
	
	   
	   if (out > '~') {
	     out = (out - 94);
	   }
	   
	   if (out > '~') {
	     out = (out - 94);
	   }
	   
	   if (((i % 70) == 0) && (i != 0)){
	   fprintf(ofp, "\n");
	   }
	   
 	   fprintf(ofp, "%c", out);
	}
	

   fclose(if1);
   fclose(if2);
   fclose(ofp);
   return 0;

}

