// readAttendanceFile.cc  P. Conrad Fall 2005 CISC181
// read a file into a linked list


#include <iostream>
#include <fstream>
#include <cstring> // for strtok and for strlen
#include <cstdlib> // for atoi
using namespace std;



// NOTE!  The Student_S struct here has two pointer fields in it.
// The assumption is that we will allocate space on the heap
// in which to store the actual username and firstname.
// If we don't do it, we have a pointer without a pointee.
// See the video "Pointer Fun with Binky" (google that) for a
// graphic illustration (with cartoon violence) of what happens
// when you dereference a pointer that has no pointee.

struct Student_S
{
  char *username;
  int areaCode;
  char *firstname;
};


void printStudent(const Student_S & s)
{
  
  /* the const helps me avoid errors such as:

     if (s.username = NULL)
       return;

  */

  if (s.username == NULL || s.firstname == NULL)
    {
      cout << "warning, data for this record is null" << endl;
      return;
    }
  
  cout << "username: " << s.username << endl
       << "areacode: " << s.areaCode << endl
       << "firstname: " << s.firstname << endl;
}

const int MAX_NUM_STUDENTS = 60;

const int MAXBUF = 1024;

int main(int argc, char *argv[])
{

  // check command line arguments

  if (argc!=2)
    {
      cerr << "Usage: " << argv[0] << " inputFileName " << endl;
      exit(1);
    }
  
  // try to open the input file

  ifstream infile (argv[1], ios::in);

  if (!infile)
    {
      cerr << "Could not open the file: " <<  argv[1] << endl;
      exit(2);
    }

  // declare the head and tail of a linked list

  Student_S *head;
  Student_S *tail;

  // or Student_S *head, *tail;

  head = NULL;
  tail = NULL;

  // this is the buffer we'll use to read from the file

  char buf[MAXBUF];
  
  // the next three variables are NOT places to store something.
  // they are just pointers into the array known as "buf"
  // they mark the starting positions of the three parts of the input line

  char *theUsername;
  char *theAreaCodeAsString;
  char *theFirstName;

  int count = 0;

  infile.getline(buf,MAXBUF); // read up to 1024 chars, or until \n

  while (!infile.eof() && !infile.fail())
    {
      // use strtok to break up buf into individual fields
      
      cout << "buffer: |" << buf << "|" << endl;
      
      theUsername = strtok(buf,",");
      theAreaCodeAsString = strtok(NULL,",");
      theFirstName = strtok(NULL,",");

      // @@ NEXT LECTURE, We'll fill in the code here
      // @@ to add a new node to our linked list.


      infile.getline(buf,MAXBUF); // read up to 1024 chars, or until \n

    }
  
  // THIS IS HOW WE PRINTED A WHOLE ARRAY
  //   for (int i=0; i<count; i++)
  //  printStudent(students[i]);

  // @@ REPLACE THIS WITH A LOOP TO PRINT THE WHOLE LINKED LIST

  return 0;

  

}








