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

#include "stdafx.h"

#include <iostream>
#include <iomanip>

#include "tree.cpp"

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, int &res) {

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

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

}


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

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

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

		pos++;

		int r;
		bool eol = is_num(str, pos, r);
		
		if (plus) res = l * r;
		else res = l / r;

		if (eol) return true;

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

	}

	return false;

}

bool is_factor(char *str, int &pos, int &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, int l, int &res) {

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

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

		pos++;

		int r;
		bool eol = is_factor(str, pos, r);
		
		if (plus) res = l + r;
		else res = l - r;

		if (eol) return true;

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

	return false;

}

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

	if (str[pos] != 0) {

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

	}

	return true;

}

using namespace std;

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

	char expr[] = "2*3+4";

	int pos = 0;
	int res = 0;

	cout << "is_term: " << is_term(expr, pos, res) << endl;
	cout << "pos: " << pos << " res: " << res << endl;

	return 0;
}
