/******************************************************************************************
ex3.cpp
    Find the oldest person in the list
******************************************************************************************/
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

// class definition
class person {
    public:
        string first;
        string last;
        int age;
};

// prototypes
int indexOfOldest(person [], int size);
void readFile(string filename, person [], const int maximum, int& size);
void showPeople(person [], const int size);

// MAIN!
void main() {
    int count=0;
    const int maxsize=100;
    person people[maxsize];

    string filename;
    cout << "Enter the file to read: ";
    cin >> filename;
    readFile(filename, people, maxsize, count);

    int oldest = indexOfOldest(people, count);
    cout << "The oldest is " << people[oldest].first << ' ' << people[oldest].last
         << ", who is " << people[oldest].age << " years old.";
}

//------- Find the oldest person in the list ------
int indexOfOldest(person list[], int size) {
    int oldestAge = list[0].age;
    int oldestPos = 0;

    for (int i = 1; i < size; i++)
        if (list[i].age > oldestAge) {
            oldestAge = list[i].age;
            oldestPos = i;
        }

    return oldestPos;
}

//------- display the whole list ------
void showPeople(person people[], const int size) {
    for (int i=0; i < size; i++) {
        cout << people[i].last << ", " << people[i].first << " (" << people[i].age << ")\n";
    }
}

//------- fill each person in the list from a file ------
void readFile(string filename, person people[], const int maximum, int& size) {
    ifstream fin(filename.c_str());

    for (int i=0; i < maximum; i++) {
        if(fin >> people[i].last >> people[i].first >> people[i].age)
            size++;
    }
}