package org.nfunk.jep.function;

import java.util.Stack;
import org.nfunk.jep.Node;
import org.nfunk.jep.ParseException;
import org.nfunk.jep.ParserVisitor;
import org.nfunk.jep.type.Complex;

public class If extends PostfixMathCommand implements SpecialEvaluationI {
  public Object evaluate(Node paramNode, Object paramObject, ParserVisitor paramParserVisitor, Stack paramStack) throws ParseException {
    double d;
    int i = paramNode.jjtGetNumChildren();
    if (i < 3 || i > 4)
      throw new ParseException("If operator must have 3 or 4 arguments."); 
    paramNode.jjtGetChild(0).jjtAccept(paramParserVisitor, paramObject);
    checkStack(paramStack);
    Double double_ = (Double)paramStack.pop();
    if (double_ instanceof Double) {
      d = ((Double)double_).doubleValue();
    } else if (double_ instanceof Complex) {
      d = ((Complex)double_).re();
    } else {
      throw new ParseException("Condition in if operator must be double or complex");
    } 
    if (d > 0.0D) {
      paramNode.jjtGetChild(1).jjtAccept(paramParserVisitor, paramObject);
    } else if (i == 3 || d < 0.0D) {
      paramNode.jjtGetChild(2).jjtAccept(paramParserVisitor, paramObject);
    } else {
      paramNode.jjtGetChild(3).jjtAccept(paramParserVisitor, paramObject);
    } 
    return paramObject;
  }
}
