/* calc_fletcher
      This function takes a string as input and calculates
      the Fletcher sum checkbits and appends them to the
      end of the string
*/
      
calc_fletcher(str)
   char *str;
{
   int i, sum1, sum2, check1, check2;
   char *temp;

   sum1 = sum2 = 0;
   
   for ( i = 0; *str != '\0'; str++) {
      sum1 = ( sum1 + *str ) % 255;
      sum2 = ( sum1 + sum2 ) % 255;
   }
   
   check1 = 255 - (( sum1 + sum2 ) % 255 );
   check2 = 255 - (( sum1 + check1 ) % 255 );

   temp[0] = check1;
   temp[1] = check2;
   temp[2] = '\0';  /* end of string marker */

   strcat(str,temp);
}

/* check_fletcher
     This function checks to see that the Fletcher sum on the
     entire message is 0.  The check bytes added in the 
     function calc_fletcher make the whole checksum out to 0.
*/

check_fletcher(str)
   char *str;
{
   int i, sum1, sum2;
 
   sum1 = sum2 = 0;

   for ( i = 0; *str != '\0'; str++) {
      sum1 = ( sum1 + *str ) % 255;
      sum2 = ( sum1 + sum2 ) % 255;
      i++;
   }
  
   if ( ( sum1 + sum2 ) == 0 ) 
     return (0);
   else 
     return (-1);
}
   
main ()
{
   char *string1;
   int results;

   string1 = "This is a test of Fletcher's Checksum";
 
   calc_fletch(string1);
 
   results = check_fletch(string1);
 
   if (results == 0)
      printf("Checksum is OK\n");
   else 
      printf("Checksum is bad\n");
    
}

