// student.cpp -- Implementation of the student class


#include <fstream>
using namespace std;

#include "student.h"


// Constructor for Student: just default values
Student::Student(): mid(0), final(0), hmwks(0), lname(""), fname("") {}

// Constructor for Student: specific initialization for the fields
Student::Student(const char flname[], const char ffname[], int fmid, 
				 int ffinal, int fhmwks)
{
  mid = fmid;
  final = ffinal;
  hmwks = fhmwks;
  lname = flname;
  fname = ffname;
}

// Accessor to the lname field of a student
string Student::get_lname() const
{
  return lname;
}


// Compute grade of a student
double Student::grade() const
{
  return (0.4*final+0.4*hmwks+0.2*mid);
}


// The functions below are help functions for Student.
// They are neither member functions nor friends of the class. Thus
// they have no access to the private members of the Student class.

// Reads a file filein of students into array a with at most n records
// and returns the number of records actually read (-1 if there is no
// such file). It allocates the space for each student.
int readStudentFile(const char *filein, Student *a[], int n)
{
  int count = 0;
  ifstream fin(filein);
  
  if (!fin)
    return -1;
  fin >> ws;
  while (!fin.eof())
    {   
      a[count] = new Student;
      fin >> *(a[count]) >> ws;
      count++;
    }
  fin.close();
  return (count);
}

// Writes a file fileout of students record from the first n
// elements of the array a of Students. It returns 0 in case of success,
// -1 if failure
int writeStudentFile(const char *fileout, const Student * const a[], 
					 int n)
{
  ofstream fout(fileout);
  if (!fout)
      return -1;
  for (int row = 0; row < n; row++)
    {
      fout << *(a[row]) << '\n';
    }
  fout.close();
  return 0;
}


// It prints out to the standard output the first
// n records of a
void printStudentTable(const Student * const a[], int n)
{
  cout << "LAST NAME       FIRST NAME           MIDTERM   FINAL   HOMEWORKS" << endl 
       << "====================================================================" << endl;
  for (int row=0; row < n; row++)
    {
      cout << *(a[row]) << endl;
    }
}

// It sorts the first n records of a in non-decreasing order
// using selection sort
void sortStudent(Student *a[], int n)
{
  for (int limit = n-1; limit > 0; --limit)
    {
      int pos = 0;
      for (int k = 1; k<=limit; ++k)
	if (a[k]->get_lname() > a[pos]->get_lname())
	  pos = k;
      Student *temp = a[pos];
      a[pos] = a[limit];
      a[limit] = temp;
    }
}






