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

/*********************************************
 ** PROTOTYPES & CLASS DEFINITIONS
 *********************************************/
struct Student
{
  int *hw;
  string name;
};
void sort(Student *A, int N, int x);
bool before(Student a, Student b, int x);
int maxindex(Student *A, int N, int x);
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];
  }

  // Get assignment number
  cout << "Enter HW# to sort on: ";
  int x;
  cin >> x;

  // SORT!
  sort(stu,Ns,x);

  // Write out student records
  for(int k = 0; k < Ns; k++)
    cout << stu[k].name << " got a "
	 << stu[k].hw[x] << " on HW #" << x << 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, int x)
{
  if (a.hw[x] < b.hw[x])
    return true;
  else
    return false;
}

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

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

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