// Geoff Hagopian PPP4 exercise 7
/*
7. Modify the “mini calculator” from exercise 5 to accept (just) 
single-digit numbers written as either digits or spelled out.
*/
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int calculate(int, int, char);
int calculate(string, string, char);

int main() {
	int operand1, operand2;
	string oper1, oper2;
	char operation, firstChar;
	cout << "Enter two single digits operands (or their words) followed by an operation: ";
	cin >> firstChar;
	if (47 < (int)firstChar && (int)firstChar < 58) {
		cin.unget(); // putback(firstChar);
		cin >> operand1 >> operand2 >> operation;
		cout << operand1 << operation << operand2
			<< " = " << calculate(operand1, operand2, operation) << endl;
	}
	else {
		cin.putback(firstChar);
		cin >> oper1 >> oper2 >> operation;
		cout << oper1 << operation << oper2
			<< " = " << calculate(oper1, oper2, operation);
	}
	while (cin >> operand1 >> operand2 >> operation) {
		cout << operand1 << operation << operand2
			<< " = " << calculate(operand1, operand2, operation);
	}
}

int calculate(int x, int y, char op) {
	switch (op) {
	case '+':
		return x + y;
	case '-':
		return x - y;
	case '/': {
		//if (y == 0) throw runtime_error("division by zero");
		//else 
		return x / y;
	}
	case '*':
		return x * y;
	default:
		cerr << "I don't know that operation.\n";
		return 0;
	}
}

int convertToInt(string s) {
	vector<string> digits{ "zero","one","two","three","four","five","six","seven","eight","nine" };
	for (int returnVal = 0; returnVal < digits.size(); ++returnVal) {
		if (digits[returnVal] == s) return returnVal;
	}
	return 0; // didn't find it
}

int calculate(string x, string y, char op) {
	switch (op) {
	case '+':
		return convertToInt(x) + convertToInt(y);
	case '-':
		return convertToInt(x) - convertToInt(y);
	case '*':
		return convertToInt(x) * convertToInt(y);
	case '/':
		return convertToInt(x) / convertToInt(y);
	default:
		return 0;  //handle error?
	}
}