/*
NAME
	calculator with Window Toolkit (wt) module
SYNOPSIS

AUTHOR
	Yoshiyuki Ohno
HISTORY
	2005/10/09(Sun)
*/

wt.newFrame({

%frame condition
size(500,500),
title("calc"),
gridPanel(5,4),
addButton("7",0,"seven"),        addButton("8",1,"eight"),
addButton("9",2,"nine"),         addButton("/",3,"devide"),
addButton("4",4,"four"),         addButton("5",5,"five"),
addButton("6",6,"six"),          addButton("*",7,"multiply"),
addButton("1",8,"one"),          addButton("2",9,"two"),
addButton("3",10,"three"),       addButton("-",11,"minus"),
addButton("AC",12,"ac"),         addButton("0",13,"zero"), 
addButton("=",14,"equal"),       addButton("+",15,"plus"),
addButton("OFF",16,"terminate").

%default atom
allclear.

%rules
zero  :- n(0).  one   :- n(1).
two   :- n(2).  three :- n(3).
four  :- n(4).  five  :- n(5).
six   :- n(6).  seven :- n(7).
eight :- n(8).  nine  :- n(9).

equal    :- ope("=").
plus     :- ope("+").
minus    :- ope("-").
multiply :- ope("*").
devide   :- ope("/").

allclear :- lastOp(0,"="),screen(0),state(fresh),pre(ac).

screen(S),n(N),state(int),pre(P) :- int(S),int(N),unary(P) | 
  V=10*S,screen(V+N),state(int),print_n(N),pre(num).
screen(S),n(N),state(fresh) :- int(S),int(N) | 
  screen(N),state(int),print_n(N).
lastOp(D,"="),screen(S),ope(OP) :- int(D) | setOp(S,OP).
lastOp(D,"+"),screen(S),ope(OP) :- V=D+S | setOp(V,OP).
lastOp(D,"-"),screen(S),ope(OP) :- V=D-S | setOp(V,OP).
lastOp(D,"*"),screen(S),ope(OP) :- V=D*S | setOp(V,OP).
lastOp(D,"/"),screen(S),ope(OP) :- V=D/S | setOp(V,OP).
lastOp(D,OP),screen(S),ac,state(F),pre(P) :- 
  int(D),unary(OP),unary(S),unary(F),unary(P) | allclear,print_clear.
setOp(V,OP),state(F) :- int(V),unary(F) | 
  update,lastOp(V,OP),screen(V),state(fresh).

print_n(N),pre(P) :- int(N),unary(P) | 
  pre(P),
  [:/*inline*/
    int i = Integer.parseInt(me.nth(0));
    String pre = me.nthAtom(1).toString();
    if(pre.equals("=")) System.out.print("\n");
    System.out.print(i);
    mem.removeAtom(me.nthAtom(0));
    mem.removeAtom(me.nthAtom(1));
    mem.removeAtom(me); 
  :](N,P).

update,lastOp(V,OP),pre(P) :- int(V),unary(OP),unary(P) | 
  lastOp(V,OP),pre(OP),
  [:/*inline*/
    int i = Integer.parseInt(me.nth(0));
    String op = me.nthAtom(1).toString();
    if(op.equals("=")){
      System.out.print(" =\n"+i+"\n");
    }else{
      System.out.print(" "+op+" ");
    }
    mem.removeAtom(me.nthAtom(0));
    mem.removeAtom(me.nthAtom(1));
    mem.removeAtom(me); 
  :](V,OP).

print_clear :-   
  [:/*inline*/
    System.out.print("\n\n");
    mem.removeAtom(me); 
  :].
}).