package com.eactive.eai.transformer.function.generic;

import java.nio.ByteBuffer;
import java.util.Stack;

import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;

public class ShortToBytes extends PostfixMathCommand {
    public ShortToBytes() {
        numberOfParameters = 1;
    }

    public void run(Stack inStack) throws ParseException {
    	checkStack(inStack);

        Object p1 = inStack.pop();
        

        if (p1 instanceof byte[]) {
            byte[] bytes = (byte[]) p1;

            if (bytes.length != 2)
            	throw new ParseException("'ShortToBytes' function argument must be  2 bytes binary");
            /*
            int i = (((bytes[0] & 0xFF) << 8)
	              + (bytes[1] & 0xFF));
	        inStack.push(new Integer(i));       
            */
            
            // 2010.02.12
            // unsigned -> signed ·Î ¼öÁ¤ÇÔ
    		ByteBuffer bb = ByteBuffer.allocate(2); 
    		bb.put(bytes[0]); 
    		bb.put(bytes[1]); 
    		short shortVal = bb.getShort(0);    		
    		inStack.push(new Integer(shortVal));        
        } else {
            throw new ParseException("Invalid parameter type");
        }        
    }
}
