#include <vector>
#include <string>
#include <iostream>
#include "common.h"

void str2node (const char *str, std::vector <node_t>& node)
{
   try {

     unsigned int size = 0;
     std::vector <std::string> tmp;
     unsigned int len = strlen (str);
     std::string buf = "";

     for (unsigned int i = 0; i < len; i++) {
	if (str[i] == '(' || str[i] == ')') {
	  if (! buf.empty()) {
	    tmp.push_back (buf);
	    buf = "";
	    ++size;
	  }
	  if (str[i] == ')') tmp.push_back (")");
	} else if (str[i] == '\t' || str[i] == ' ') { 	  // do nothing
	} else {
	  buf += str[i];
	}
      }

      if (! buf.empty()) throw 2;

      node.resize (size);
      std::vector <int> sibling (size);
      for (unsigned int i = 0; i < size; ++i) {
	node[i].parent = -1;
	node[i].child = -1;
	node[i].sibling = -1;
	sibling[i] = -1;
      }

      std::vector <int> sr;
      unsigned int id = 0;
      int top = 0;

      for (unsigned int i = 0; i < tmp.size(); ++i) {
	if (tmp[i] == ")") {
	  top = sr.size()-1;
	  if (top < 1) continue;
	  unsigned int child  = sr[top];
	  unsigned int parent = sr[top-1];
	  node[child].parent = parent;
	  if (node[parent].child == -1) node[parent].child = child;
	  if (sibling[parent] != -1) node[sibling[parent]].sibling = child;
	  sibling[parent] = child;
	  sr.resize (top);
	} else {
	  node[id].val = tmp[i];
	  sr.push_back (id);
	  id++;
	}
      }

      return;
    }

    catch (const int) {
      std::cerr << "Fatal: parse error << [" << str << "]\n";
      std::exit (-1);
    }
}
