'use strict';

const _ = require('underscore');
const rpn = require('./rpn');

const precedence = {
    '^': 3,
    '*': 2,
    '/': 2,
    '-': 1,
    '+': 1,
    '(': 0
};

let convertInfix = function(tokens) {
    let stack = [];
    let output = [];

    tokens.forEach(function(token) {
        if (_.isNumber(token)) {
            output.push(token);
        } else if (token === '(') {
            stack.push(token);
        } else if (token === ')') {
            while (true) {
                if (stack.length <= 0) {
                    throw 'Stack underflow';
                }
                let operator = stack.pop();
                if (operator === '(') {
                    break;
                }
                output.push(operator);
            }
        } else {
            let tokenPrecedence = precedence[token];
            while (true) {
                let stackPrecedence = precedence[stack[stack.length-1]] || 0;
                if (tokenPrecedence > stackPrecedence) {
                    stack.push(token);
                    break;
                } else if (tokenPrecedence < stackPrecedence) {
                    output.push(stack.pop());
                } else {
                    output.push(stack.pop());
                    stack.push(token);
                    break;
                }
            }
        }
    });

    while (stack.length > 0) {
        output.push(stack.pop());
    }

    return output;
};

let evaluateInfix = _.compose(rpn.evaluateRpn, convertInfix);

module.exports = {
    convertInfix,
    evaluateInfix
};

@@ -977,17 +977,18 @@
 cedence 
-%3E
+%3C=
  stackPr
@@ -1019,32 +1019,39 @@
         
-stack.push(token
+output.push(stack.pop()
 );%0A     
@@ -1057,34 +1057,26 @@
             
-    break;
+%7D%0A
 %0A           
@@ -1072,39 +1072,32 @@
                 
-%7D else 
 if (tokenPrecede
@@ -1100,17 +1100,18 @@
 cedence 
-%3C
+%3E=
  stackPr
@@ -1126,125 +1126,8 @@
 ) %7B%0A
-                    output.push(stack.pop());%0A                %7D else %7B%0A                    output.push(stack.pop());%0A
     
@@ -1151,33 +1151,32 @@
 tack.push(token)
-;
 %0A               

Clean up logic in the infix converter.