
#include <iostream>
#include <fstream>
#include <ctype.h>

#include "queue.h"
#include "btree.h"

void Visit  (char& a, int d) { cout << a << " "; }

void Visitd (char& a, int d) 
{ 
  for (d *= 4; d > 0; d--) 
    cout << " "; 
  cout << a << endl; 
}


int
main (int argn, char *argv[])
{
  char expr[255];
  BTree<char> *bt;
  Stack< BTree<char>* > st;

  ifstream fin (argv[1]);
  if (fin) {
      fin.read (expr, 255);
      fin.close ();
    }
  else
    cin >> expr;

  for (int i = 0; expr[i]; i++)
    {
      if (isalpha (expr[i]))
	{
	  bt = new BTree<char> (expr[i]);
	  st.Push (bt);
	}
      else
	{
	  BTree<char> *l = NULL, *r = NULL;
	  st.Pop (r); st.Pop (l);
	  bt = new BTree<char> (expr[i], l, r);
	  st.Push (bt);
	  delete l; delete r;
	}
    }
  st.Pop (bt);
  if (!st.isEmpty ()) 
    {
      delete bt;
      while (st.Pop (bt))
	delete bt;
      cout << "Error during parsing" << endl;
      return 0;
    }

  // Print the tree
  bt->Preorder (Visitd); 

  // Print the expression 
    cout << "Preorder:   "; bt->Preorder  (Visit); cout << endl;
    cout << "Inorder:    "; bt->Inorder   (Visit); cout << endl;
    cout << "Postorder:  "; bt->Postorder (Visit); cout << endl;

  delete bt;

  return 0;
}

