// se.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <iomanip>

#include "tree.cpp"

class ExprNode {
public:
	bool is_num;
	char op;
	int num;
	ExprNode(bool c_is_num = true, char c_op = '+', int c_num = 0) : is_num(c_is_num), op(c_op), num(c_num) {}
	friend ostream& operator<< (ostream& out, const ExprNode& obj);
};

ostream& operator<< (ostream& out, const ExprNode& obj) {
	if (obj.is_num) {
		cout << obj.num;
	} else {
		cout << obj.op;
	}
	return out;
}

typedef Tree<ExprNode> ExprTree;
ExprTree expr_t;

bool is_digit(char c) {
	switch (c) {
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			return true;
	}

	return false;
}

bool is_num(char *str, int &pos, ExprTree &res) {

	int i = pos;
	if (str[i] != 0 && is_digit(str[i])) {

		int n = atoi(&str[i]);
		ExprNode en(true, 0, n);
		ExprTree t(en);
		res = t;

	}

	pos = ++i;
	return (str[i] == 0);

}


bool is_factor2(char *str, int &pos, ExprTree l, ExprTree &res) {

	if (str[pos] == '*' || str[pos] == '/') {

		bool plus = (str[pos] == '*');
		pos++;

		ExprTree r;
		bool eol = is_num(str, pos, r);
		
		if (plus) { 

			ExprNode en(false, '*', 0);
			ExprTree t(en, l, r);
			res = t; 

		} else { 

			ExprNode en(false, '/', 0);
			ExprTree t(en, l, r);
			res = t; 

		}

		if (eol) return true;

		return is_factor2(str, pos, res, res);

	}

	return false;

}

bool is_factor(char *str, int &pos, ExprTree &res) {

	if (str[pos] != 0) {

		bool eol = is_num(str, pos, res);
		if (!eol) return is_factor2(str, pos, res, res);

	}

	return true;

}

bool is_term2(char *str, int &pos, ExprTree l, ExprTree &res) {

	if (str[pos] == '+' || str[pos] == '-') {

		bool plus = (str[pos] == '+');
		pos++;

		ExprTree r;
		bool eol = is_factor(str, pos, r);
		
		if (plus) { 

			ExprNode en(false, '+', 0);
			ExprTree t(en, l, r);
			res = t;

		} else { 

			ExprNode en(false, '-', 0);
			ExprTree t(en, l, r);
			res = t; 

		}

		if (eol) return true;

		return is_term2(str, pos, res, res);

	}

	return false;

}

using namespace std;

bool is_term(char *str, int &pos, ExprTree &res) {

	if (str[pos] != 0) {

		bool eol = is_factor(str, pos, res);
		if (!eol) return is_term2(str, pos, res, res);

	}

	return true;

}


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

	char expr[] = "1-2-3*6*7/1-2*4/3";

	int pos = 0;
	ExprTree t;

	if (is_term(expr, pos, t))
		t.Print();

	return 0;
}

