/*********************************************
This program reads in student/grade data from
namedgrades.txt, gets a name from the user and
prints out his homework average.
**********************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*********************************************
 ** PROTOTYPES & STRUCT DEFINITIONS
 *********************************************/
struct student {
  int* hw;
  char name[128];
};

int find(char* name, struct student* arr, int size);
double average(int* arr, int size);

/*********************************************
 ** MAIN FUNCTION
 *********************************************/
int main() {
  // Open file and read header info
  int numstu, numhw;
  FILE* fin = fopen("namedgrades.txt", "r");
  fscanf(fin, " %i students %i homeworks", &numstu, &numhw);

  // Create array of numstu students with numhw grades each
  struct student* stu = calloc(numstu, sizeof(struct student));
  for(int i = 0; i < numstu; i++) {
    stu[i].hw = calloc(numhw, sizeof(int));
  }

  // Read and store student names and grades
  for(int i = 0; i < numstu; i++) {
    fscanf(fin, " %s", stu[i].name);
    for(int j = 0; j < numhw; j++) {
      fscanf(fin, " %i", &stu[i].hw[j]);
    }
  }

  // Get name from user
  char name[128];
  printf("Enter name: ");
  fflush(stdout);
  scanf(" %s", name);

  // Find student with given name & print their average
  int k = find(name, stu, numstu);
  if (k == numstu) {
    printf("%s is not in the class!\n", name);
  } else {
    printf("Average is: %g\n", average(stu[k].hw, numhw));
  }

  // clean up
  fclose(fin);
  for (int i=0; i < numstu; ++i) {
    free(stu[i].hw);
  }
  free(stu);

  return 0;
}

/*********************************************
 ** FUNCTION DEFINITIONS
 *********************************************/
// Returns index of array element whose name
// data member matches given name.
int find(char* name, struct student* arr, int size) {
  int k = 0;
  while(k < size && strcmp(name, arr[k].name) != 0) {
    k++;
  }
  return k;
}

// Returns the average of the size ints in array arr
double average(int* arr, int size) {
  double sum = 0;
  for(int i = 0; i < size; i++) {
    sum = sum + arr[i];
  }
  return sum / size;
}