package rpn.vc;

import java.util.Hashtable;
import rpn.*;
import rpn.basic.*;
import rpn.doubles.DoubleItem;

/** This is the token interpreter for vc. */

public class VCInterpreter implements ItemInterpreter, SimpleToken {

	public Item getItem(Calculator ca, Input in) {
		int t = in.getToken();
		Item it = null;
		switch(t) {
			case IntTok: {
				try {
					int N = in.getInt();
					it = new IntItem(ca, N);
					break;
				} catch (OverflowException exc) {
					double x = in.getDouble();
					it = new DoubleItem(ca, x);
					break;
				}
			}
			case NegIntTok: {
				try {
					int N = in.getNegInt();
					it = new IntItem(ca, N);
					break;
				} catch (OverflowException exc) {
					double x = in.getDouble();
					it = new DoubleItem(ca, x);
					break;
				}
			}
			case RealTok:
			case NegRealTok: {
				double x = in.getDouble();
				it = new DoubleItem(ca, x);
				break;
			}
			case CommentTok: {
				// String s = in.getWord();
				// it = new CommentItem(ca, s);
				break;
			}
			case SingleTok: {
				// look up in the system dictionary
				String s = in.getWord();
				int n = ca.dictStackSize();
				Item x = null;
				while (x == null && n > 0) {
					Hashtable h = (Hashtable) ca.dictPeek(--n);
					x = (Item) (h.get(s));
				}
				if (x != null) {
					it = x;
					break;
				} 
				it = new ErrItem(ca, new WordItem(ca, s), CalcErr.Undefined);
				break;
			}
			case WordTok: {
				// look up in the system dictionary
				String s = in.getWord();
				it = new WordItem(ca, s);
				break;
			}
			case EOFTok: {
				it = new EOFItem(ca);
				break;
			}
			case StringTok: {
				it = new StringItem(ca, in.getString());
				break;
			}
			case LiteralTok: {
				it = new LiteralItem(ca, in.getLiteral());
				break;
			}
			case LFTok: {
				// it = new LFItem(ca);
				break;
			}
			default: {
				it = new ErrItem(ca, new InputErrItem(ca), CalcErr.InvalidInput);
				break;
			}
		}
		return(it);
	}
}