/* readData.c   P. Conrad 10/24/05 */
/* read water polo data into an array */


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

#define MAXLINE 1024 /* maximum characters on one line */

#define FILENAME "data.txt"


/* function prototype is the first line of a function, with a semicolon 
   after it. */

int computeTotalGoalsScored(  int count, int goalsPerPlayer[]   );
int readFileIntoArray( int *goalsPerPlayer ); /* return number of lines read */

int main(void)
{
  int i; /* for the for loop */


  int totalGoalsScored;
  int count;

  /* declare array */

  int goalsPerPlayer[10]; /* goals scored by each player recently */

  /* return the number of lines read */

  count = readFileIntoArray(goalsPerPlayer);

  /* When all done with the file, print a summary of results */
  
  printf("I read %d lines from the file\n", count);


  for (i=0; i<count; i++)
    printf("goals for player %d were %d \n", i, goalsPerPlayer[i]);
  
  /* find the total number of goals scored by all players */
  
  totalGoalsScored =  computeTotalGoalsScored( count, goalsPerPlayer  );

  printf("total goals scored = %d\n",totalGoalsScored);  


  /* find how many goals the best player(s) scored */


  /* find the player(s) who scored the most goals */

  /* find the average number of goals scored by all players */

  return 0;
}




int computeTotalGoalsScored(  int count, int goalsPerPlayer[]   )
{
  int totalGoalsScored = 0;
  int i;
  
  /* step through array totalling up the goals scored */

  for (i=0; i < count ; i++)
    totalGoalsScored += goalsPerPlayer[i] ;
  
  return totalGoalsScored;
    
}






int readFileIntoArray( int *goalsPerPlayer    )
{
  
  FILE *infile;
  char buffer[MAXLINE];
  char *result; /* return value from fgets */
  int count; /* the number of lines read from the file */

  /* open the input file */
  
  
  infile = fopen(FILENAME,"r");
  
  if (infile == NULL)
    {
      perror("opening " FILENAME); /* no comma! */
      
      fprintf(stderr,"Could not open " FILENAME "\n");
      exit(1);
    }
  
  /* actually read data from the file */
  
  count = 0;
  
  /*  fgets reads one line from the file */
  
  
  result = fgets(buffer, MAXLINE, infile);
  while (result != NULL)
    {
      /* process the line from the file */
      
      goalsPerPlayer[count] = atoi(buffer); /* converts ASCII to integer */
      count ++; /* always increment count AFTER storing in the array */
      
      /* get the next line */
      result = fgets(buffer, MAXLINE, infile);
    }
  
  
  return count;
}




