#include <iostream>
#include <sstream>
#include "LinkedList.h"
using std::string;
using std::cout;
using std::endl;
using std::istringstream;
using std::isdigit;

bool isOperator(char op) {
  switch(op) {
  case '+':
  case '-':
  case '*':
  case '/':
  case '~':
    return true;
  }
  return false;
}

int eval(char op, Stack *stack) {
  int result = 0;
  
  int first = stack->pop();
  // unary operations
  if (op == '~') {
    result = -first;
  }
  // binary operations
  else {
    int second = stack->pop();
    
    cout << first << " " << op << " " << second << endl;
    switch (op) {
    case '+':
      result = first + second;
      break;
    case '-':
      result = first - second;
      break;
    case '*':
      result = first * second;
      break;
    case '/':
      result = first / second;
      break;
    }
  }
  return result;
}

int main(int argc, char *argv[]) {
  if (argc > 1) {
    string s(argv[1]);
    
    Stack *stack = new LinkedList();
    
    istringstream tokens(s);
    char nextChar;
    bool streamError = false;
    while (tokens >> nextChar && !streamError) {
      if (isdigit(nextChar)) {
        tokens.putback(nextChar);
        
        int value;
        tokens >> value;
        stack->push(value);
      }
      else if (isOperator(nextChar)) {
        int result = eval(nextChar, stack);
        stack->push(result);
      }
      else {
        cout << "error, invalid character encountered" << endl;
        streamError = true;
      }
    }
    
    cout << stack->peek();
    delete stack;
  }
  else {
    cout << "Insufficient arguments" << endl;
  }
  
}
