package rpn.basic;

import java.util.Hashtable;
import rpn.Calculator;

public class RCurlItem extends Item {

	public RCurlItem(Calculator ca) {
		super(ca);
		ca.systemInstall(this);
	}
	
	public void exec() {
		int h = ca.procDepth;
		int n = ca.size();
		int i;
		for (i=n;i>0;i--) {
			Item it = (Item) ca.item(i-1);
			if (it instanceof LCurlItem) {
				// System.out.println("-h = " + h);
				if (--h == 0) {
					break;
				}
			} else if (it instanceof RCurlItem) {
				// System.out.println("+h = " + h);
				h++;
			}
		}
		if (h == 0) {
			Item a[] = new Item[n-i];
			for (int j=n;j>i;j--) {
				a[j-i-1] = (Item) ca.pop();
			}
			ca.pop();
			Item it = new ProcItem(ca, a);
			ca.push(it);
			ca.procDepth = 0;
		} else {
			ca.error(this, CalcErr.UnmatchedCurl);
		}
	}
	
	public void store() {
		if (ca.procDepth == 1) {
			exec();
		} else {
			super.exec();
			ca.procDepth--;
		}
	}
	
	public String toString() {
		return("}");
	}
}