package rpn.ic;

import java.util.Hashtable;
import rpn.*;
import rpn.items.*;

public class ICInput extends ItemInput {

	public ICInput(Calculator ca, Input in) {
		super(ca, in);
	}
	
	public Item tokenToItem() {
		// read input and interpret it
		int t = in.getToken();
		switch(t) {
			case IntTok:
			case NegIntTok: {
				try {
					int N = in.getInt();
					return(new IntItem(ca, N));
				} catch (OverflowException exc) {
					
				}
			}
			case CommentTok: {
				String s = in.getWord();
				return(new CommentItem(ca, s));
			}
			case SingleTok: 
			case WordTok: {
				// 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) {
					return(x);
				} 
				return(new ErrItem(ca, s + " undefined!"));
			}
			case EOFTok: {
				return(new EOFItem(ca));
			}
			case StringTok: {
				return(new StringItem(ca, in.getString()));
			}
			case LiteralTok: {
				return(new LiteralItem(ca, in.getLiteral()));
			}
			case LFTok: {
				return(new LFItem(ca));
			}
			default: {
				return(new ErrItem(ca, "Unrecognizable input " + tokenName[t]));
			}
		}
	}
}