/* This program determines which users were logged into a computer
 * system for a given period of time.
 *
 * Input (keyboard): Name of the log file
 * Iput (file):      User ids
 * Output (screen):  A list of distinct user-ids and for each id,
 *                     the number of logins.
 *******************************************************************/

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

template <typename ItemType>
int Search(const vector<ItemType> & v, ItemType item);

int main()
{
  // Get name of log file and open a stream to it
  string logFile;     // log file of user-ids.
  cout << "Enter name of log file: ";
  cin >> logFile;
  ifstream inStream(logFile.data());  // open input stream to log file
  if (!inStream.is_open())
  {
    cerr << "Unable to open file " << logFile << endl;
    exit(-1);
  }

  // Read user-ids from file, add new ones to list of user-ids,
  // and increment login count for each user-id
  vector<string> userId;   // list of user-ids;
  vector<int> loginCount;  // list of login counts
  string aUserId;          // current user-id being processed

  for (;;)
  {
    getline(inStream, aUserId);
    if (inStream.eof()) break;

    int loc = Search(userId, aUserId);
    if (loc < userId.size())
      loginCount[loc]++;
    else
    {
      userId.push_back(aUserId);
      loginCount.push_back(1);
    }
  }

  // Display the list of user-ids and login counts
  for (int i = 0; i < userId.size(); i++)
    cout << "Logins for " << userId[i] << ": " << loginCount[i] << endl;
}

/* Function Search performs a linear search of values
 * stored in a vector.
 *
 * Receive: a vector v and item of the same type as
 *           the elements of v
 * Return:  position of item if found; the size of v otherwise
 **************************************************************/

template <typename ItemType>
int Search(const vector<ItemType> & v, ItemType item)
{
  int i = 0;
  for (;;)
  {
    if (i >= v.size() || item == v[i])
      return i;
    //else
    i++;
  }
}

