// main01.cc P. Conrad, 4/4/05
// demonstrate building a linked list of acct numbers
// this program fixes the bug that was in main01.cc

#include "llist01.h"

#include <iostream>
#include <fstream>

using namespace std;

void printLinkedListOnCout(Acct_S *head);

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

  if (argc!=2)
    {
      cerr << "Usage: " << argv[0] << " inputFile " << endl;
      return -1;
    }

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

  if (!infile)
    {
      cerr << "Could not open " << argv[1] << endl;
      return -2;
    }

  int thisAcctNum;
  char thisName[NAME_MAX];

  Acct_S *head, *tail, *p;

  head=NULL;
  tail=NULL;

  int count = 0;

  infile >> thisAcctNum >> thisName;
  while (!infile.eof())
    {
      count++; // we got another item from the file successfully.
      p = new Acct_S; // allocate a new node from the heap
      
      // set the fields in the struct 

      p->acctNum = thisAcctNum;
      strncpy(p->name, thisName, NAME_MAX-1);
      p->name[NAME_MAX-1] = '\0'; // for safety.
      p->next = NULL;
      
      // link into the list

      if (head==NULL)
	head = tail = p;
      else
	{
	  tail -> next = p;
	  tail = p;
	}
      
      // try to read the next line from the file
      infile >> thisAcctNum >> thisName;
    }
  
  cout << "The program read " << count << " lines from the file " << endl;
  cout << "Here they are: " << endl;

  for (p=head; p; p=p->next)
    cout << "\t" << p->acctNum << "\t" << p->name << endl;

  cout << endl;
  
  cout << "Now I will print out the linked list by calling a function:"
       << endl;

  printLinkedListOnCout(head);

  return 0;

}





