package org.nfunk.jep.function;

import java.util.Stack;
import java.util.Vector;
import org.nfunk.jep.ParseException;

public class Cross extends PostfixMathCommand {
  static Subtract sub = new Subtract();
  
  static Multiply mul = new Multiply();
  
  public void run(Stack paramStack) throws ParseException {
    checkStack(paramStack);
    Object object1 = paramStack.pop();
    Object object2 = paramStack.pop();
    paramStack.push(cross(object2, object1));
  }
  
  public Object cross(Object paramObject1, Object paramObject2) throws ParseException {
    if (paramObject1 instanceof Vector && paramObject2 instanceof Vector)
      return cross((Vector)paramObject1, (Vector)paramObject2); 
    throw new ParseException("Cross: Invalid parameter type, both arguments must be vectors");
  }
  
  public Object cross(Vector paramVector1, Vector paramVector2) throws ParseException {
    int i = paramVector1.size();
    if ((i != 2 && i != 3) || i != paramVector2.size())
      throw new ParseException("Cross: both sides must be of length 3"); 
    if (i == 3) {
      Vector vector = new Vector(3);
      vector.setSize(3);
      vector.setElementAt(sub.sub(mul.mul(paramVector1.elementAt(1), paramVector2.elementAt(2)), mul.mul(paramVector1.elementAt(2), paramVector2.elementAt(1))), 0);
      vector.setElementAt(sub.sub(mul.mul(paramVector1.elementAt(2), paramVector2.elementAt(0)), mul.mul(paramVector1.elementAt(0), paramVector2.elementAt(2))), 1);
      vector.setElementAt(sub.sub(mul.mul(paramVector1.elementAt(0), paramVector2.elementAt(1)), mul.mul(paramVector1.elementAt(1), paramVector2.elementAt(0))), 2);
      return vector;
    } 
    return sub.sub(mul.mul(paramVector1.elementAt(0), paramVector2.elementAt(1)), mul.mul(paramVector1.elementAt(1), paramVector2.elementAt(0)));
  }
}
