#include<iostream>
#include<fstream>
#include<string>

using namespace std;

void chyba(char * s){
	cout << "Vyraz " << s << " obsahuje chybu." << endl;
	system("PAUSE");
	exit(1);
}

class vyraz
{
private:
	string obsah;
	int spocti(string co, int * n);
public:
	vyraz(char * s);
	int vyhodnot(int * n);
	string vypis();
};


vyraz::vyraz(char *s){
	obsah.clear();
	bool promenna = false, operand = false, minus = false;
	int zavorky = 0;
	for(unsigned int i = 0; i<strlen(s); i++){
		if(s[i] != ' ' && s[i] != '\t'){
			if(s[i] == '(') zavorky++; else if(s[i] == ')') {
				zavorky--;
				if(zavorky < 0) chyba(s);
			}else if(s[i] == '+' || s[i] == '*' || s[i] == '/'){
				promenna = false;
				if(operand || minus) chyba(s);
				operand = true;
			}else if(s[i] == '-'){
				promenna = false;
				operand = false;
				minus = true;
			}else if(s[i] == '$'){
				operand = false;
				minus = false;
				obsah += s[i];
				i++;
				if(s[i] < '0' || s[i] > '9') chyba(s);
				promenna = true;
			}else if(s[i] >= '0' && s[i] <= '9'){
				operand = false;
				minus = false;
				if(promenna) chyba(s);
			}else {
				chyba(s);
			}
			obsah += s[i];
		}
	}
	if(zavorky > 0) chyba(s);
}


int vyraz::spocti(string co, int * n){
	string leva, prava;
	bool operand = false;
	unsigned int i=0, zavorek=0;
	while(co[0] == '(' && co[co.length() - 1] == ')'){
		co.erase(co.begin());
		co.erase(co.end()-1);
	}
	if(co.find('+',0) == string::npos && co.find('-',0) == string::npos && co.find('*',0) == string::npos && co.find('/',0) == string::npos) {
		if(co[0] != '$') {
			return atoi(co.c_str());			
		} else {
			co.erase(co.begin());
			return n[atoi(co.c_str())];
		}
	}
	while(i<co.length()){
		if(co[i] == '(') zavorek++;
		if(co[i] == ')') zavorek--;
		if(zavorek == 0 && co[i] == '+') return spocti(co.substr(0,i), n) + spocti(co.substr(i+1), n);
		if(zavorek == 0 && co[i] == '-' && !operand) return spocti(co.substr(0,i), n) - spocti(co.substr(i+1), n);
		if(co[i] == '*' || co[i] == '+' || co[i] == '-' || co[i] == '/') operand = true; else operand = false;
		i++;
	}
	i=0;
	zavorek = 0;
	while(i<co.length()){
        if(co[i] == '(') zavorek++;
		if(co[i] == ')') zavorek--;
		if(zavorek == 0 && co[i] == '*') return spocti(co.substr(0,i), n) * spocti(co.substr(i+1), n);
		if(zavorek == 0 && co[i] == '/') return spocti(co.substr(0,i), n) / spocti(co.substr(i+1), n);
		i++;
	}
	return 0;
}

int vyraz::vyhodnot(int * n){
	return spocti(obsah, n);
}

string vyraz::vypis(){
	return obsah;
}

int main( int argc, char* argv[]) {
	int i;
	vyraz a("((2 +3 * -$0))");
	//vyraz a("(5+ 6 +    7)"), b("(1*-2+($0-$1)+6)");
	int * prom = new int[2];
	prom[0] = 10;
	prom[1] = 2;
	cout << "Promenne: ";
	for(i = 0; i<2; i++) cout << prom[i] << " ";
	cout << endl;
	cout << a.vypis() << " = " << a.vyhodnot(prom) << endl;
	

	system("PAUSE");
}