#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "fields.h"
#include "sllist.h"

/* This program prints the median score of a group of students. The
   name of the file that contains the student data  should be the
   first command line argument. Each line in the file is of the form:

 	first_name last_name score

   The students are ordered in descending order. The program reads
   each student's data and appends the student to a list. When all
   the students have been read, the program iterates to the middle
   of the list and prints the median student's name and score.
*/

typedef struct {
  char *fname;   // student's first name
  char *lname;   // student's last name
  int score;     // student's score
} Student;

main(int argc, char *argv[]) {
  IS inputFile; 
  Sllist *studentList = new_sllist();
  int studentCount = 0;
  Student *newStudent;
  Sllist_Node *student;
  int i;

  inputFile = new_inputstruct(argv[1]);
  if (inputFile == NULL) {
    perror(argv[1]);
    exit(1);
  }

  while (get_line(inputFile) != EOF) {
    if (inputFile->NF != 3) { 
      fprintf(stderr, "line %d: wrong number of fields (%d)\n",
		inputFile->line, inputFile->NF);
      fprintf(stderr, "line %d:    input must be of the form 'firstname lastname score'\n", inputFile->line);
      fprintf(stderr, "line %d:    the first name and last name may be only one field each\n", inputFile->line);
      continue;
    }
    newStudent = (Student *)malloc(sizeof(Student));
    newStudent->fname = strdup(inputFile->fields[0]);
    newStudent->lname = strdup(inputFile->fields[1]);
    if (sscanf(inputFile->fields[2], "%i", &newStudent->score) != 1) {
	fprintf(stderr, "line %d: score (%s) must be an integer\n",
		inputFile->line, inputFile->fields[2]);
	continue;
    }
    sll_append(studentList, newStudent);
    studentCount++;
  }

  if (studentCount == 0) {
     fprintf(stderr, "%s had no valid data so no median could be computed\n",
	argv[1]);
     exit(1);
  }

  // traverse to the middle of the list and print the median student's
  // name and score
  for (i = 0, student = sll_first(studentList); i < studentCount / 2; 
	i++, student = sll_next(student)) ;
  newStudent = (Student *)sll_val(student);
  printf("%s %s: %d\n", newStudent->fname, newStudent->lname, 
			newStudent->score);
}

