/* charcount.c
 * A simple c program for counting characters in a specified file.
 * Compilation: gcc -o charcount charcount.c
 * Usage: charcount filename
 * where filename contains "the actual paper"
 * that will go between the lines "BODY" and "ENDBODY".
 * The output of charcount should be put between "PAPER:" and "BODY".
 */

#include <stdio.h>

main(argc, argv)
int argc;
char *argv[];
{
  int c;
  long sum, lowercase_count, uppercase_count, digit_count, count[256];
  FILE *fp, *fopen();

  if (argc != 2) {
    fprintf(stderr, "Usage: %s filename\n",argv[0]);
    exit(1);
  }
  lowercase_count = 0;
  uppercase_count = 0;
  digit_count = 0;
  sum = 0;
  for (c = 0; c <= 255; c++) count[c] = 0;
  while (--argc > 0) {
    if ((fp = fopen(argv[argc],"r")) != NULL) {
      while ((c = getc(fp)) != EOF) {
        if (islower(c)) lowercase_count++;
        else if (isupper(c)) uppercase_count++;
        else if (isdigit(c)) digit_count++;
        else count[c]++;
        sum++;
      }
      printf("The body of this paper,\n");
      printf("from the line following \"BODY\" ");
      printf("to the line preceding \"ENDBODY\",\n");
      printf("contains a total of %ld characters.\n", sum);
      printf("In the  table below, this count is broken down by ASCII code;\n");
      printf("following one white space after the code is the corresponding character\n");
      printf("(intended for trouble shooting, in case things got garbled).\n\n");
      printf("%7ld lowercase letters\n", lowercase_count);
      printf("%7ld uppercase letters\n", uppercase_count);
      printf("%7ld digits\n", digit_count);
      for (c = 0; c <= 127; c++) {
        if (count[c] > 0)
          printf("%7ld ASCII characters %3ld %c\n", count[c], c, (char)c);
      }
      for (c = 128; c <= 255; c++) {
        if (count[c] > 0)
          printf("%7ld       characters %3ld %c\n", count[c], c, (char)c);
      }
      fclose(fp);
    }
    else {
      fprintf(stderr, "%s: can't open %s\n",argv[0], argv[argc]);  
      exit(1);
    }
    exit(0);
  }
}

