////////////////////////////////////////////////////////////////////////////////
// School of Computing, Universiti Teknologi Malaysia
// SCSJ1013- Programming Technique I
// Semester 1, 2018/2019
// Skill-Based Test: Question 1 (35 Marks)
// 14 Dec 2018
//
// Name:
// Matrics No:
// Section: 
//
////////////////////////////////////////////////////////////////////////////////

#include <iostream> 
#include <fstream>
#include <limits>
using namespace std;

#define FILENAME	"student_data.csv"
#define RECORDS		5
#define SUBJECTS	4
#define MAXSTREAM	numeric_limits<streamsize>::max()

int main()
{
	//Record for RECORDS number of students
	char name[RECORDS][100];
	int marks[RECORDS][SUBJECTS];
	
	//Statistics
	float avg[SUBJECTS] = {0};
	int total[SUBJECTS] = {0};
	int highest_marks[SUBJECTS] = {0};
	int highest_name_index[SUBJECTS] = {0};
	
	//Open file
	fstream ifile(FILENAME, ios::in) ;
	
	//Quit if unable to open a file
	if (!ifile.is_open())
	{
		cout << "Error opening file " << FILENAME << endl;
		return -1;
	}
	
	//Get data for every student
	for (int i = 0; i < RECORDS; i++)
	{	
		//Read name field
		ifile.get(name[i], 100, ',');
		ifile.ignore(MAXSTREAM, ','); //Ignore comma
		
		//Read marks for every subject
		for (int j = 0; j < SUBJECTS-1; j++) 
		{
			ifile >> marks[i][j];
			ifile.ignore(MAXSTREAM, ',');
		}
		ifile >> marks[i][SUBJECTS-1];
		ifile.ignore(MAXSTREAM, '\n');
	}
	
	//Close file			
	ifile.close();
	
	//Calculate total marks for each subject and get the highest marks for each subject
	for (int i = 0; i < RECORDS; i++)
	{
		for (int j = 0; j < SUBJECTS; j++)
		{
			//calculate total marks for each subject
			total[j] += marks[i][j];
			
			//get the highest marks for each subject
			if (marks[i][j] > highest_marks[j])
			{
				highest_marks[j] = marks[i][j];
				highest_name_index[j] = j;
			}
		}		
	}
	
	//Display statistics for all subjects - the average marks and highest marks for each subject
	cout<<"Statistics for all subjects : "<<endl;
	for (int i = 0; i < SUBJECTS; i++)
	{
		avg[i] = total[i] / static_cast<float>(RECORDS);  //calculate average for each subject
		cout << "Subject " << i+1 << " : " << endl;
		cout << "\tHighest mark = "  				
			 << name[highest_name_index[i]]
			 << " (" << highest_marks[i] << ")" << endl;
		cout << "\tAverage mark = " << avg[i] << endl;   
	}
	
	return 0;
}

