#include <cstdlib>
#include <iostream>
#include <fstream>
#include "ListReader.h"
#include "SortedList.h"
#include "Node.h"

using namespace std;

void print(SortedList& list, bool bothways) {
  NodePtr v;
  cout << "   ";
  if (bothways)
    cout << "[front to back]:";
  for (v = list.header->next;  v!=NULL && v!=list.trailer; v = v->next)
    cout << " " << v->element;
  if (v==NULL)
    cout << " (unexpected NULL pointer)";
  cout << endl;
  if (bothways) {
    cout << "   [back to front]:";
    for (v = list.trailer->prev;  v!=NULL && v!=list.header; v = v->prev)
      cout << " " << v->element;
    if (v==NULL)
      cout << " (unexpected NULL pointer)";
    cout << endl;
  }
}


int main(int argc, const char* argv[]) {
  filebuf fb;

  // override input based upon file, if valid
  if (argc>1) {
    fb.open(argv[1],ios::in);
    if (fb.is_open()) {
      ListReader::isr = new istream(&fb);
    } else {
      cout << "Input file '" << argv[1] << "' not found.\n";
      cout << "Defaulting to keyboard input.\n\n";
    }
  }


  // is there a limit on the number of lines to read?
  int LIMIT = -1;
  if (argc>2) {
    LIMIT = atoi(argv[2]);
    if (LIMIT < 1) {
      LIMIT = -1;
      cout << "Second argument (" << argv[2] << ") ignored.\n\n";
    } else {
      ListReader::lineLimit = LIMIT;
    }
  }


  try {
    while (true) {
      SortedList A;
      SortedList B;
      cout << "\nBefore the merge, the first list appears as follows.\n";
      print(A,false);
      cout << "\nBefore the merge, the second list appears as follows.\n";
      print(B,false);
      cout << "\nCalling merge...\n";
      A.merge(B);
      cout << "\nThe merged list appears as follows.\n";
      print(A,true);
      cout << endl;
    }
  } catch (...) {
    // The list builder will throw an exception when '-1' is reached in input
    cout << "GoodBye\n";
  }

}
