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

#include "readCharacter.h"

int 
readCharacter(cmd_args args)
{
  unsigned int lines=0;
  unsigned int characters = 0;
  unsigned int words = 0;

  char ch;
  char tmp = ' '; /* temp buffer, MUST BE INITIALIZED TO ' ' OR ANY ASCII CHARACTER <= 32, OTHERWISE AN EMPTY FILE WILL BE INTERPRETED AS 1 WORD LONG */


  while((ch = fgetc(args.fp)))
    {
      if (ch == EOF)
	{
	  if (tmp != ' ' && tmp != '\n')
	    {
	      words++;
	      /* printf("_WORDS++_"); */
	    }
	  break;
	}

      /*printf("%c", ch); //prints the text verbatim */

      characters++;

      if (ch == '\n')
	{
	  lines++;
	  /* printf("_LINES++_");  */
	}

      if (ch == ' ' && (tmp > 32))
	{
	  words++;
	  /* printf("_WORDS++_"); */
	}
      else if (ch == '\n' && (tmp > 32))
	{
	  words++;
	  /* printf("_WORDS++_");    */
	}

      tmp = ch; /* tmp receives the most recent 'ch' value  before  'ch' is updated*/
    }


  /* Prints the appropriate information */
  if (args.fp != stdin || args.filename[0] == '-')
    {
      fprintf(stdout, "%s: ", args.filename);
    }
  
  if (args.char_opt == 1)
    {
      fprintf(stdout,"%i\n", characters);
    }
  else if (args.line_opt == 1)
    {
      fprintf(stdout, "%i\n", lines);
    }
  else
    {
      fprintf(stdout, "%i\n", words);
    }
  
  return 0;
}
