/*********************************************
This program reads in student/grade data from
namedgrades.txt, and prints out student names
and HW#4 scores in order from lowest to highest
score on HW#4.
**********************************************/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

/*********************************************
 ** PROTOTYPES & STRUCT DEFINITIONS
 *********************************************/
struct Student
{
  int *hw;
  string name;
};
void sort(Student *A, int N);
bool before(Student a, Student b);
int maxindex(Student *A, int N);
void swap(Student &a, Student &b);


/*********************************************
 ** MAIN FUNCTION
 *********************************************/
int main()
{
  // Open file and read header info
  int Ns, Nh;
  string junk;
  ifstream IN("namedgrades.txt");
  IN >> Ns >> junk >> Nh >> junk;

  // Create array of Ns students with Nh grades each
  Student *stu = new Student[Ns];
  for(int j = 0; j < Ns; j++)
    stu[j].hw = new int[Nh];

  // Read & store student names & grades
  for(int i = 0; i < Ns; i++)
  {  
    IN >> stu[i].name;
    for(int j = 0; j < Nh; j++)
      IN >> stu[i].hw[j];
  }

  // SORT!
  sort(stu,Ns);

  // Write out student records
  for(int k = 0; k < Ns; k++)
    cout << stu[k].name << " got a "
	 << stu[k].hw[4] << " on HW #4" << endl;

  return 0;
}

/*********************************************
 ** FUNCTION DEFINITIONS
 *********************************************/
// Determines whether student a comes before b
// when ordered by increasing score on HW #4.
bool before(Student a, Student b)
{
  if (a.hw[4] < b.hw[4])
    return true;
  else
    return false;
}

// THE USUAL SORTING STUFF!!
void sort(Student *A, int N)
{
  for(int length = N; length > 1; length--)
    swap(A[maxindex(A,length)],A[length-1]);
}

int maxindex(Student *A, int N)
{
  int imax = 0, i;
  for(i = 1; i < N; i++)
    if (before(A[imax],A[i]))
      imax = i;
  return imax;
}

void swap(Student &a, Student &b)
{
  Student temp = a;
  a = b;
  b = temp;
}