// linkedListDemo.cpp for CISC181   11/16/04
// P. Conrad

#include <iostream>
#include <cstring>
#include <fstream>
#include <cassert>
using namespace std;

#define NAMELEN 10
#define INPUTLINELEN 256

struct Score_S
{
  char name[NAMELEN];
  int score;
  Score_S *next;
};


int main(int argc, char *argv[])
{
  Score_S *p; // a "working" pointer for allocating new structs
  Score_S *head, *tail; // points to head and tail of linked list

  p = new Score_S;

  char inputLine[INPUTLINELEN];

  char *namePtr, *scorePtr;

  if (argc!=2)
    {
      cerr << "Usage: " << argv[0] << " inputfile " << endl;
      exit(-1);
    }
  ifstream inf(argv[1],ios::in);

  if (!inf)
    {
      cerr << "Could not open scores.dat" << endl;
      exit(-1);
    }

  inf.getline(inputLine,INPUTLINELEN,'\n');
  



  head = NULL; tail = NULL;

  while (!inf.eof())
    {
      
      namePtr = strtok(inputLine,",");
      scorePtr = strtok(NULL,",");

      p  = new Score_S;
      strncpy(p->name,namePtr,NAMELEN);
      p->name[NAMELEN-1]='\0';
      p->score=atoi(scorePtr);
      p->next = NULL;
      
      // link into linked list

      if (head==NULL)
	{
	  assert(tail ==NULL);

	  head = p;
	  tail = p;
	}
      else
	{
	  assert(tail!=NULL);
	  tail->next = p;
	  tail = p; // show what error results if you delete this line
	}

      inf.getline(inputLine,INPUTLINELEN,'\n');
    }


  cout << "Here's a traversal of the entire linked list \n";

  for (Score_S *q=head; q!=NULL; q=q->next)
    {
      cout << "name: " << q->name<< " score: " << q->score << endl;
    }

}

