////////////////////////////////////////////////////////////////////////////////
// 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> //1//
#include <fstream>
#include <limits>
using namespace std;

#define FILENAME	"student_data.csv" //2//
#define RECORDS		5
#define SUBJECTS	4
#define MAXSTREAM	numeric_limits<streamsize>::max()

int main()
{
	//Record for RECORDS number of students
	char name[RECORDS][100];//3//
	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) ; //4//
	
	//Quit if unable to open a file
	if (!ifile.is_open())//5//
	{
		cout << "Error opening file " << FILENAME << endl;//6//
		return -1;
	}
	
	//Get data for every student
	for (int i = 0; i < RECORDS; i++)
	{	
		//Read name field
		ifile.get(name[i], 100, ',');//7
		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(); //8
	
	//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]) //10
			{
				highest_marks[j] = marks[i][j]; //9
				highest_name_index[j] = j;//11
			}
		}		
	}
	
	//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); //12 //calculate average for each subject
		cout << "Subject " << i + 1 << " : " << endl; //13
		cout << "\tHighest mark = "  				
			 << name[highest_name_index[i]]
			 << " (" << highest_marks[i] << ")" << endl;
		cout << "\tAverage mark = " << avg[i] << endl;   
	}
	
	return 0;
}

