import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;

//******************* Board ***********************

class EmptyPaint extends Thread
{	Board B;
	int W,H;
	EmptyPaint (Board b, int w, int h)
	{	B=b; W=w; H=h;
		start();
	}
	public void run ()
	{	try { sleep(100); } catch (Exception e) {}
		B.createwood(B,W,H);
		B.updateboard();
	}
}

/**
This is the main file for presenting a Go board.
<P>
Handles the complete display of a Go board.
The display is kept on an offscreen image.
Stores a Go game in a node list (with variants).
Handles the display of the current node.
Updates an information label to inform about the next move etc.
(To be passed to the constructor).
<P>
This class handles mouse input to set the next move.
It also has methods to move in the node tree.
These methods are called from GoFrame.
@see GoFrame
*/

public class Board extends Panel
    implements MouseListener, MouseMotionListener, KeyListener
{	int O,W,D,S,OT,OTU; // pixel coordinates
	// O=offset, W=total width, D=field width, S=board size (9,11,13,19)
	// OT=offset for coordinates to the right and below
	// OTU=offset above the board and below for coordinates
	int lasti=-1,lastj=0; // last move (used to highlight the move)
	boolean showlast; // internal flag, if last move is to be highlighted
	Image Empty,ActiveImage; // offscreen images of empty and current board
	Position P; // current positon
	Tree History; // the game history
	Tree Pos; // The current position in the History.
	int number; // number of next move
	Label L,Lm; // labels to display information.
	int State; // states: 1 is black, 2 is white, 3 is set black etc.
		// see GoFrame.setstate(int)
	TextArea Comment; // Comment text area
	Font font; // Font for board letters and coordinates
	FontMetrics fontmetrics; // metrics of this font
	GoFrame GF; // frame containing the board
	boolean Active;
	char[] Buffer; // the buffer for reading of files
	int BufferN;
	int maxbuffer=4096;
	int MainColor=1;
	public int MyColor=0;
	int sendi=-1,sendj;
		// board position which has been sended to server
	Dimension Dim; // Note size to check for resizeing at paint
	int SpecialMarker=Field.SQUARE;
	String TextMarker="A";
	public int Pw,Pb; // Prisoners (white and black)
	String LaterLoad=""; // File to be loaded at repaint
	static Image StaticImage=null;
	Image BlackStone,WhiteStone;
	int Range=-1; // Numbers display from this one
	boolean KeepRange=false;
	String NodeName="",LText="";
	boolean DisplayNodeName=false;
	public boolean Removing=false;

	/**
	Initialize with a label to indicate the next move and
	a label to for the board position.
	Initialize with board size 19.
	The textarea is used to display a comment.
	<P>
	The GoFrame must be known, because it contains configuration
	information and the board enables or disables the navigation
	buttons.
	*/
	public Board (Label l, Label lm, int size, TextArea comment,
		GoFrame gf)
	{	S=size; D=16; W=S*D;
		L=l; Lm=lm;
		Empty=null;
		number=1;
		Comment=comment;
		P=new Position(S);
		Node n;
		History=new Tree(n=new Node(number));
		n.main(true);
		Pos=History;
		showlast=true;
		GF=gf;
		State=1;
		Active=true;
		Buffer=new char[maxbuffer];
		BufferN=0;
		Dim=new Dimension();
		Dim.width=0; Dim.height=0;
		Pw=Pb=0;
		setfonts();
		addMouseListener(this);
		addMouseMotionListener(this);
		addKeyListener(this);
	}

	void setfonts ()
	{	font=Global.BoardFont;
		fontmetrics=getFontMetrics(font);
	}

	public Dimension getMinimumSize ()
	{	Dimension d=getSize();
		if (d.width==0) return d=Dim;
		d.width=d.height+5;
		return d;
	}

	public Dimension getPreferredSize ()
	{	return getMinimumSize();
	}

	public void updateall ()
	// Update all the board
	{	if (ActiveImage==null) return;
		synchronized (this)
		{	ActiveImage.getGraphics().drawImage(Empty,0,0,this);
		}
		int i,j;
		for (i=0; i<S; i++)
			for (j=0; j<S; j++)
				update(i,j);
		showinformation();
	}

	public void updateboard ()
	{	BlackStone=WhiteStone=null;
		setfonts();
		makeimages();
		updateall();
		copy();
	}

	public void makeimages ()
	// Create images and repaint
	{	Dim=getSize();
		boolean c=Global.getParameter("coordinates",true);
		boolean ulc=Global.getParameter("upperleftcoordinates",true);
		boolean lrc=Global.getParameter("lowerrightcoordinates",true);
		D=Dim.height/(S+1+(c?((ulc?1:0)+(lrc?1:0)):0));
		O=D/2; W=S*D+2*O;
		if (c)
		{	if (lrc) OT=D;
			else OT=0;
			if (ulc) OTU=D;
			else OTU=0;
		}
		else OT=OTU=0;
		W+=OTU+OT;
		if (!GF.Show) return;
		synchronized (this)
		{	Empty=createImage(W,W);
		}
		emptypaint();
		ActiveImage=createImage(W,W);
		updateall();
		copy();
	}

	public void paint (Graphics g)
	// repaint the board (generate images at first call)
	{	Dimension d=getSize();
		if (Dim.width!=d.width || Dim.height!=d.height)
		{	Dim=d;
			makeimages();
		}
		else
		{	g.drawImage(ActiveImage,0,0,this);
		}
		if (!LaterLoad.equals("") && GF.Show)
		{	String s=LaterLoad;
			LaterLoad="";
			GF.doload(s);
		}
	}

	// The following is for the thread, which tries to draw the
	// board on program start, to save time.

	static WoodPaint woodpaint=null;

	/**
	Create an image of the wooden board. The component is used
	to create the image.
	*/
	static public void createwood (Component comp, int w, int h)
	{	if (w==0 || h==0) return;
		int p[]=new int[w*h];
		int i,j;
		double f=9e-1;
		int col=Global.getColor("boardcolor",170,120,70).getRGB();
		int blue=col&0x0000FF,green=(col&0x00FF00)>>8,red=(col&0xFF0000)>>16;
		for (i=0; i<h; i++)
			for (j=0; j<w; j++)
			{	f=((Math.sin(13*(double)j/w)+1)/2+1e-1*Math.cos(3*(double)i/h)+
					5e-2*Math.sin(10*(double)i/h))
					*10+5e-1;
				f=f-Math.floor(f);
				if (f<2e-1) f=1-f/2;
				else if (f<4e-1) f=1-(4e-1-f)/2;
				else f=1;
				if (i==w-1 || (i==w-2 && j<w-2) || j==0
					|| (j==1 && i>1)) f=f/2;
				if (i==0 || (i==1 && j>1) || j>=w-1
					|| (j==w-2 && i<h-1))
					p[w*i+j]=(255<<24)|
					((int)(128+red*f/2)<<16)|((int)(128+green*f/2)<<8)|
					(int)(128+blue*f/2);
				else
					p[w*i+j]=(255<<24)|
					((int)(red*f)<<16)|((int)(green*f)<<8)|(int)(blue*f);
			}
		StaticImage=comp.createImage(
				new MemoryImageSource(w,h,ColorModel.getRGBdefault(),
						p,0,w));
		Global.setParameter("sboardwidth",w);
		Global.setParameter("sboardheight",h);
	}

	// Now come the normal routine to draw a board.

	EmptyPaint EPThread=null;

	/**
	Try to paint the wooden board. If the size is correct, use
	the predraw board. Otherwise generate an EmptyPaint thread
	to paint a board.
	*/
	public synchronized boolean trywood (Graphics gr, int w, int h)
	{	if (StaticImage!=null && StaticImage.getWidth(this)==w)
			// use predrawn image
		{	gr.drawImage(StaticImage,O+OTU,O+OTU,this);
			return true;
		}
		else
		{	if (EPThread!=null && EPThread.isAlive()) EPThread.stop();
			EPThread=new EmptyPaint(this,w,h);
		}
		return false;
	}

	public void stonespaint ()
	// Create the (beauty) images of the stones (black and white)
	{	int col=GF.BoardColor.getRGB();
		int blue=col&0x0000FF,green=(col&0x00FF00)>>8,red=(col&0xFF0000)>>16;
		boolean Alias=Global.getParameter("alias",true);
		if (BlackStone==null || BlackStone.getWidth(this)!=D+2)
		{	int d=D+2;
			int pb[]=new int[d*d];
			int pw[]=new int[d*d];
			int i,j,g,k;
			double di,dj,d2=(double)d/2.0-5e-1,r=d2-2e-1,f=Math.sqrt(3);
			double x,y,z,xr,xg,hh;
			k=0;
			if (Global.getParameter("smallerstones",false)) r-=1;
			for (i=0; i<d; i++)
				for (j=0; j<d; j++)
				{	di=i-d2; dj=j-d2;
					hh=r-Math.sqrt(di*di+dj*dj);
					if (hh>=0)
					{	z=r*r-di*di-dj*dj;
					    if (z>0) z=Math.sqrt(z)*f;
					    else z=0;
						x=di; y=dj;
						xr=Math.sqrt(6*(x*x+y*y+z*z));
						xr=(2*z-x+y)/xr;
						if (xr>9e-1) xg=(xr-9e-1)*10;
						else xg=0;
						if (hh>8e-1 || !Alias)
						{	g=(int)(10+10*xr+xg*140);
							pb[k]=(255<<24)|(g<<16)|(g<<8)|g;
							g=(int)(200+10*xr+xg*45);
							pw[k]=(255<<24)|(g<<16)|(g<<8)|g;
						}
						else
						{	hh=(8e-1-hh)/8e-1;
							g=(int)(10+10*xr+xg*140);
							pb[k]=((255<<24)
							    |(((int)((1-hh)*g+hh*red))<<16)
								|(((int)((1-hh)*g+hh*green))<<8)
								|((int)((1-hh)*g+hh*blue)));
							g=(int)(200+10*xr+xg*45);
							pw[k]=((255<<24)
							    |(((int)((1-hh)*g+hh*red))<<16)
								|(((int)((1-hh)*g+hh*green))<<8)
								|((int)((1-hh)*g+hh*blue)));
						}
					}
					else pb[k]=pw[k]=0;
					k++;
				}
			BlackStone=createImage(
				new MemoryImageSource(d,d,ColorModel.getRGBdefault(),
							pb,0,d));
			WhiteStone=createImage(
				new MemoryImageSource(d,d,ColorModel.getRGBdefault(),
							pw,0,d));
		}
	}

	public void emptypaint ()
	// Draw an empty board onto the graphics context g.
	// Including lines, coordinates and markers.
	{	if (woodpaint!=null && woodpaint.isAlive()) woodpaint.stop();
		synchronized (this)
		{	Graphics g=Empty.getGraphics();
			if (!Global.getParameter("beauty",false)
				|| !trywood(g,S*D,S*D)) // beauty board not available
			{	g.setColor(GF.BoardColor);
				g.fillRect(O+OTU,O+OTU,S*D,S*D);
			}
			if (Global.getParameter("beautystones",false)) stonespaint();
			g.setColor(Color.black);
			int i,j,x,y1,y2;
			// Draw lines
			x=O+OTU+D/2; y1=O+OTU+D/2; y2=O+D/2+OTU+(S-1)*D;
			for (i=0; i<S; i++)
			{	g.drawLine(x,y1,x,y2);
				g.drawLine(y1,x,y2,x);
				x+=D;
			}
			if (S==19) // handicap markers
			{	for (i=0; i<3; i++)
					for (j=0; j<3; j++)
						hand(g,3+i*6,3+j*6);
			}
			else if (S>=11) // handicap markers
			{	if (S>=15 && S%2==1)
				{	int k=S/2-3;
					for (i=0; i<3; i++)
						for (j=0; j<3; j++)
							hand(g,3+i*k,3+j*k);
				}
				else
				{	hand(g,3,3);
					hand(g,S-4,3);
					hand(g,3,S-4);
					hand(g,S-4,S-4);
				}
			}
			// coordinates to the left and above
			if (OT>0)
			{	g.setFont(font);
				int y=O+OTU;
				int h=fontmetrics.getAscent()/2-1;
				for (i=0; i<S; i++)
				{	String s=""+(S-i);
					int w=fontmetrics.stringWidth(s)/2;
					g.drawString(s,O+OTU+S*D+D/2-w,y+D/2+h);
					y+=D;
				}
				x=O+OTU;
				char a[]=new char[1];
				for (i=0; i<S; i++)
				{	j=i;
					if (j>7) j++;
					a[0]=(char)('A'+j);
					String s=new String(a);
					int w=fontmetrics.stringWidth(s)/2;
					g.drawString(s,x+D/2-w,O+OTU+S*D+D/2+h);
					x+=D;
				}
			}
			// coordinates below and to the right
			if (OTU>0)
			{	g.setFont(font);
				int y=O+OTU;
				int h=fontmetrics.getAscent()/2-1;
				for (i=0; i<S; i++)
				{	String s=""+(S-i);
					int w=fontmetrics.stringWidth(s)/2;
					g.drawString(s,O+D/2-w,y+D/2+h);
					y+=D;
				}
				x=O+OTU;
				char a[]=new char[1];
				for (i=0; i<S; i++)
				{	j=i;
					if (j>7) j++;
					a[0]=(char)('A'+j);
					String s=new String(a);
					int w=fontmetrics.stringWidth(s)/2;
					g.drawString(s,x+D/2-w,O+D/2+h);
					x+=D;
				}
			}
		}
	}

	public void hand (Graphics g, int i, int j)
	// help function for emptypaint (Handicap point)
	{	g.setColor(Color.black);
		int s=D/10;
		if (s<2) s=2;
		g.fillRect(O+OTU+D/2+i*D-s,O+OTU+D/2+j*D-s,2*s+1,2*s+1);
	}

	boolean MouseDown=false;

	public void mousePressed (MouseEvent e)
	{	MouseDown=true;
	    requestFocus();
	}

	public void mouseReleased (MouseEvent e)
	// handle mouse input
	{	if (!MouseDown) return;
	    int x=e.getX(),y=e.getY();
		MouseDown=false;
		if (ActiveImage==null) return;
		if (!Active) return;
		if (GF.blocked() && ((Node)Pos.content()).main()
			&& !Pos.haschildren()) return;
		getinformation();
		x-=O+OTU; y-=O+OTU;
		int i=x/D,j=y/D; // determine position
		if (x<0 || y<0 || i<0 || j<0 || i>=S || j>=S) return;
		Node n=(Node)Pos.content();
		switch (State)
		{	case 3 : // set a black stone
				if (n.main() && GF.wantsmove()) return;
				set(i,j,1);
				undonode(n); setnode(n);
				showinformation();
				break;
			case 4 : // set a white stone
				if (n.main() && GF.wantsmove()) return;
				set(i,j,-1);
				undonode(n); setnode(n);
				showinformation();
				break;
			case 5 : mark(i,j); break;
			case 6 : letter(i,j); break;
			case 7 :
				if (Pos.haschildren()) return;
				delete(i,j);
				undonode(n); setnode(n);
				showinformation(); break;
			case 8 :
				if (Pos.haschildren()) return;
				removegroup(i,j);
				undonode(n); setnode(n);
				showinformation(); break;
			case 9 : specialmark(i,j); break;
			case 10 : textmark(i,j); break;
			case 1 :
			case 2 :
				if (e.isShiftDown()) // create variation
				{	if (e.isControlDown()) changemove(i,j);
					else variation(i,j);
				}
				else if (e.isControlDown())
					// goto variation
				{	if (P.tree(i,j)!=null)
					{	Tree newpos=P.tree(i,j);
						if (newpos.parent()==Pos.parent())
						{	goback();
							Pos=newpos;
							setnode((Node)Pos.content());
							showinformation();
							copy();
						}
					}
				}
				else if (e.isMetaDown())
				{	if (P.tree(i,j)!=null)
					{	Tree newpos=P.tree(i,j);
						if (newpos.parent()==Pos.parent())
						{	goback();
							Pos=newpos;
							setnode((Node)Pos.content());
							showinformation();
							copy();
						}
					}
					else variation(i,j);
				}
				else // place a W or B stone
				{	if (Pos.haschildren()) return;
					if (((Node)Pos.content()).main() && GF.wantsmove())
					{	if (GF.moveset(i,j))
						{	sendi=i; sendj=j;
							update(i,j);
							MyColor=P.color();
						}
						Sound.play("click","",false);
					}
					else set(i,j); // try to set a new move
				}
				break;
		}
		showinformation();
		copy(); // show position
	}

	public void mouseMoved (MouseEvent e)
	// show coordinates in the Lm Label
	{	if (!Active) return;
	    if (DisplayNodeName)
	    {   L.setText(LText);
	        DisplayNodeName=false;
	    }
	    int x=e.getX(),y=e.getY();
		x-=O+OTU; y-=O+OTU;
		int i=x/D,j=y/D; // determine position
		if (i<0 || j<0 || i>=S || j>=S) return;
		Lm.setText(Field.coordinate(i,j,S));
	}

	public void mouseEntered (MouseEvent e)
	// start showing coordinates
	{	if (!Active) return;
	    if (DisplayNodeName)
	    {   L.setText(LText);
	        DisplayNodeName=false;
	    }
	    int x=e.getX(),y=e.getY();
		x-=O+OTU; y-=O+OTU;
		int i=x/D,j=y/D; // determine position
		if (i<0 || j<0 || i>=S || j>=S) return;
		Lm.setText(Field.coordinate(i,j,S));
	}

	public void mouseExited (MouseEvent e)
	// stop showing coordinates
	{	if (!Active) return;
	    Lm.setText("--");
	    if (!NodeName.equals(""))
	    {   L.setText(NodeName);
	        DisplayNodeName=true;
	    }
	}

	public void mouseClicked (MouseEvent e) {}
	public void mouseDragged (MouseEvent e) {}

    public void keyPressed (KeyEvent e)
  	{	if (e.isActionKey())
  		{	switch (e.getKeyCode())
  			{	case KeyEvent.VK_DOWN : forward(); break;
  				case KeyEvent.VK_UP : back(); break;
  				case KeyEvent.VK_LEFT : varleft(); break;
  				case KeyEvent.VK_RIGHT : varright(); break;
  				case KeyEvent.VK_PAGE_DOWN : fastforward(); break;
  				case KeyEvent.VK_PAGE_UP : fastback(); break;
  				case KeyEvent.VK_BACK_SPACE :
  				case KeyEvent.VK_DELETE : undo(); break;
  				case KeyEvent.VK_HOME : varmain(); break;
  				case KeyEvent.VK_END : varmaindown(); break;
  				case KeyEvent.VK_INSERT : GF.callsetname(); break;
  			}
  		}
  		else
  		{	switch (e.getKeyChar())
  			{	case '*' : varmain(); break;
  				case '/' : varmaindown(); break;
  				case 'v' :
  				case 'V' : varup(); break;
  				case 'm' :
  				case 'M' : mark(); break;
  				case 'p' :
  				case 'P' : resume(); break;
  				case 'c' :
  				case 'C' : specialmark(Field.CIRCLE); break;
  				case 's' :
  				case 'S' : specialmark(Field.SQUARE); break;
  				case 't' :
  				case 'T' : specialmark(Field.TRIANGLE); break;
  				case 'l' :
  				case 'L' : letter(); break;
  				case 'r' :
  				case 'R' : specialmark(Field.CROSS); break;
  				case 'w' : setwhite(); break;
  				case 'b' : setblack(); break;
  				case 'W' : white(); break;
  				case 'B' : black(); break;
  				case '+' : gotonext(); break;
  				case '-' : gotoprevious(); break;
  				// Bug (VK_DELETE not reported as ActionEvent)
  				case KeyEvent.VK_BACK_SPACE :
  				case KeyEvent.VK_DELETE : undo(); break;
  			}
  		}
  	}

    public void keyReleased (KeyEvent e) {}
    public void keyTyped (KeyEvent e) {}

	public void set (int i, int j)
	// set a new move, if the board position is empty
	{	Action a;
		synchronized (Pos)
		{	if (P.color(i,j)==0) // empty?
			{	if (((Node)Pos.content()).actions()!=null ||
					Pos.parent()==null)
				// create a new node, if there the current node is not
				// empty, else use the current node. exception is the first
				// move, where we always create a new move.
				{	Node n=new Node(++number);
					if (P.color()>0)
					{	a=new Action("B",Field.string(i,j));
					}
					else
					{	a=new Action("W",Field.string(i,j));
					}
					n.addaction(a); // note the move action
					n.main(Pos);
					setaction(n,a,P.color()); // display the action
					// !!! We alow for suicide moves
					Tree newpos=new Tree(n);
					Pos.addchild(newpos); // note the move
					Pos=newpos; // update current position pointer
				}
				else
				{	Node n=(Node)Pos.content();
					if (P.color()>0)
					{	a=new Action("B",Field.string(i,j));
					}
					else
					{	a=new Action("W",Field.string(i,j));
					}
					n.addaction(a); // note the move action
					n.main(Pos);
					setaction(n,a,P.color()); // display the action
					// !!! We alow for suicide moves
				}
			}
		}
	}

	public void delete (int i, int j)
	// delete the stone and note it
	{	if (P.color(i,j)==0) return;
		synchronized (Pos)
		{	Node n=(Node)Pos.content();
			Action a;
			a=new Action("AE",Field.string(i,j));
			n.expandaction(a);
			n.addchange(new Change(i,j,P.color(i,j)));
			P.color(i,j,0); update(i,j); showinformation(); copy();
		}
	}

	public void changemove (int i, int j)
	// change a move to a new field (dangerous!)
	{	if (P.color(i,j)!=0) return;
		synchronized (Pos)
		{	ListElement la=((Node)Pos.content()).actions();
			while (la!=null)
			{	Action a=(Action)la.content();
				if (a.type().equals("B") || a.type().equals("W"))
				{	undonode((Node)Pos.content());
					a.arguments().content(Field.string(i,j));
					setnode((Node)Pos.content());
					break;
				}
			}
		}
	}

	public void removegroup (int i0, int j0)
	// completely remove a group (at end of game, before count)
	// note all removals
	{	if (Pos.haschildren()) return;
		if (P.color(i0,j0)==0) return;
		if (GF.wantsmove() && ((Node)Pos.content()).main())
		{	GF.moveset(i0,j0);
		}
		Action a;
		P.markgroup(i0,j0);
		int i,j;
		int c=P.color(i0,j0);
		Node n=(Node)Pos.content();
		for (i=0; i<S; i++)
			for (j=0; j<S; j++)
			{	if (P.marked(i,j))
				{	a=new Action("AE",Field.string(i,j));
					n.addchange(new Change(i,j,P.color(i,j)));
					n.expandaction(a);
					if (P.color(i,j)>0) { n.Pb++; Pb++; }
					else { n.Pw++; Pw++; }
					P.color(i,j,0); update(i,j);
				}
			}
	}

	public void remove (int i0, int j0)
	// completely remove a group (at end of game, before count)
	// note all removals
	{	int s=State;
		varmaindown();
		State=s;
		if (P.color(i0,j0)==0) return;
		Action a;
		P.markgroup(i0,j0);
		int i,j;
		int c=P.color(i0,j0);
		Node n=(Node)Pos.content();
		for (i=0; i<S; i++)
			for (j=0; j<S; j++)
			{	if (P.marked(i,j))
				{	a=new Action("AE",Field.string(i,j));
					n.addchange(new Change(i,j,P.color(i,j)));
					n.expandaction(a);
					if (P.color(i,j)>0) { n.Pb++; Pb++; }
					else { n.Pw++; Pw++; }
					P.color(i,j,0); update(i,j);
				}
			}
		copy();
	}

	public void mark (int i, int j)
	// Emphasize the field at i,j
	{	Node n=(Node)Pos.content();
		Action a=new MarkAction(Field.string(i,j));
		n.expandaction(a);
		update(i,j);
	}

	public void specialmark (int i, int j)
	// Emphasize with the SpecialMarker
	{	Node n=(Node)Pos.content();
		String s;
		switch (SpecialMarker)
		{	case Field.SQUARE : s="SQ"; break;
			case Field.CIRCLE : s="CR"; break;
			case Field.TRIANGLE : s="TR"; break;
			default : s="MA"; break;
		}
		Action a=new Action(s,Field.string(i,j));
		n.expandaction(a);
		update(i,j);
	}

	public void textmark (int i, int j)
	{	Node n=(Node)Pos.content();
		Action a=new Action("LB",Field.string(i,j)+":"+TextMarker);
		n.expandaction(a);
		update(i,j);
	}

	public void letter (int i, int j)
	// Write a character to the field at i,j
	{	Node n=(Node)Pos.content();
		Action a=new LabelAction(Field.string(i,j));
		n.expandaction(a);
		update(i,j);
	}

	public void set (int i, int j, int c)
	// set a new stone, if the board position is empty
	// and we are on the last node.
	{	if (Pos.haschildren()) return;
	    synchronized (Pos)
		{	Action a;
			if (P.color(i,j)==0) // empty?
			{	Node n=(Node)Pos.content();
				n.addchange(new Change(i,j,0));
				if (c>0)
				{	a=new Action("AB",Field.string(i,j));
				}
				else
				{	a=new Action("AW",Field.string(i,j));
				}
				n.expandaction(a); // note the move action
				P.color(i,j,c);
				update(i,j);
			}
		}
	}

	public void capture (int i, int j, Node n)
	// capture neighboring groups without liberties
	// capture own group on suicide
	{	int c=-P.color(i,j);
		if (i>0) capturegroup(i-1,j,c,n);
		if (j>0) capturegroup(i,j-1,c,n);
		if (i<S-1) capturegroup(i+1,j,c,n);
		if (j<S-1) capturegroup(i,j+1,c,n);
		if (P.color(i,j)==-c)
		{	capturegroup(i,j,-c,n);
		}
	}

	public void capturegroup (int i, int j, int c, Node n)
	// Used by capture to determine the state of the groupt at (i,j)
	// Remove it, if it has no liberties and note the removals
	// as actions in the current node.
	{	int ii,jj;
		Action a;
		if (P.color(i,j)!=c) return;
		if (!P.markgrouptest(i,j,0)) // liberties?
		{	for (ii=0; ii<S; ii++)
				for (jj=0; jj<S; jj++)
				{	if (P.marked(ii,jj))
					{	n.addchange(new Change(ii,jj,P.color(ii,jj)));
						if (P.color(ii,jj)>0) { Pb++; n.Pb++; }
						else { Pw++; n.Pw++; }
						P.color(ii,jj,0);
						update(ii,jj); // redraw the field (offscreen)
					}
				}
		}
	}

	public void variation (int i, int j)
	{	if (Pos.parent()==null) return;
		if (P.color(i,j)==0) // empty?
		{	int c=P.color();
		    goback();
		    P.color(-c);
			set(i,j);
			number=2;
			((Node)Pos.content()).number(2);
		}
	}

	public String formtime (int t)
	{	int s,m,h=t/3600;
		if (h>=1)
		{	t=t-3600*h;
			m=t/60;
			s=t-60*m;
			return ""+h+":"+twodigits(m)+":"+twodigits(s);
		}
		else
		{	m=t/60;
			s=t-60*m;
			return ""+m+":"+twodigits(s);
		}
	}

	public String twodigits (int n)
	{	if (n<10) return "0"+n;
		else return ""+n;
	}

	public String lookuptime (String type)
	{	int t;
		if (Pos.parent()!=null)
		{	String s=((Node)Pos.parent().content()).getaction(type);
			if (!s.equals(""))
			{	try { t=Integer.parseInt(s); return formtime(t); }
				catch (Exception e) { return ""; }
			}
			else return "";
		}
		return "";
	}

	public void showinformation ()
	// update the label to display the next move and who's turn it is
	// and disable variation buttons
	// update the navigation buttons
	// update the comment
	{	Node n=(Node)Pos.content();
		number=n.number();
		NodeName=n.getaction("N");
		String ms="";
		if (n.main())
		{	if (!Pos.haschildren()) ms="** ";
			else ms="* ";
		}
		switch (State)
		{	case 3 : LText=ms+"Set black stones"; break;
			case 4 : LText=ms+"Set white stones"; break;
			case 5 : LText=ms+"Mark fields"; break;
			case 6 : LText=ms+"Place letters"; break;
			case 7 : LText=ms+"Delete stones"; break;
			case 8 : LText=ms+"Remove prisoners"; break;
			case 9 : LText=ms+"Set special marker"; break;
			case 10 : LText=ms+"Text: "+TextMarker; break;
			default :
				if (P.color()>0)
				{	String s=lookuptime("BL");
					if (!s.equals(""))
						LText=ms+"Next move: Black "+number+" ("+s+")";
					else
						LText=ms+"Next move: Black "+number;
				}
				else
				{	String s=lookuptime("WL");
					if (!s.equals(""))
						LText=ms+"Next move: White "+number+" ("+s+")";
					else
						LText=ms+"Next move: White "+number;
				}
		}
		if (NodeName.equals(""))
		{   L.setText(LText);
		    DisplayNodeName=false;
		}
		else
		{   L.setText(NodeName);
		    DisplayNodeName=true;
		}
		GF.setstate(3,!n.main());
		GF.setstate(4,!n.main());
		GF.setstate(7,!n.main() || Pos.haschildren());
		if (State==1 || State==2)
		{	if (P.color()==1) State=1;
			else State=2;
		}
		GF.setstate(1,Pos.parent()!=null &&
			Pos.parent().firstchild()!=Pos);
		GF.setstate(2,Pos.parent()!=null &&
			Pos.parent().lastchild()!=Pos);
		GF.setstate(5,Pos.haschildren());
		GF.setstate(6,Pos.parent()!=null);
		if (State!=9) GF.setstate(State);
		else GF.setmarkstate(SpecialMarker);
		int i,j;
		// delete all marks and variations
		for (i=0; i<S; i++)
			for (j=0; j<S; j++)
			{	if (P.tree(i,j)!=null)
				{	P.tree(i,j,null);
					update(i,j);
				}
				if (P.marker(i,j)!=Field.NONE)
				{	P.marker(i,j,Field.NONE);
					update(i,j);
				}
				if (P.letter(i,j)!=0)
				{	P.letter(i,j,0);
					update(i,j);
				}
				if (P.haslabel(i,j))
				{	P.clearlabel(i,j);
					update(i,j);
				}
			}
		Tree p=Pos.parent();
		ListElement la;
		Action a;
		String s;
		if (p!=null && p.parent()!=null) // setup the variation marks
		{	ListElement l=p.firstchild().listelement();
			while (l!=null)
			{	p=(Tree)l.content();
				if (p!=Pos)
				{	la=((Node)p.content()).actions();
					while (la!=null)
					{	a=(Action)la.content();
						if (a.type().equals("W") || a.type().equals("B"))
						{	s=(String)a.arguments().content();
							i=Field.i(s);
							j=Field.j(s);
							if (valid(i,j))
							{	P.tree(i,j,p);
								update(i,j);
							}
							break;
						}
						la=la.next();
					}
				}
				l=l.next();
			}
		}
		la=((Node)Pos.content()).actions();
		String sc="";
		int let=1;
		while (la!=null) // setup the marks and letters
		{	a=(Action)la.content();
			if (a.type().equals("C"))
			{	sc=(String)a.arguments().content();
			}
			else if (a.type().equals("SQ") || a.type().equals("SL"))
			{	ListElement larg=a.arguments();
				while (larg!=null)
				{	s=(String)larg.content();
					i=Field.i(s);
					j=Field.j(s);
					if (valid(i,j))
					{	P.marker(i,j,Field.SQUARE);
						update(i,j);
					}
					larg=larg.next();
				}
			}
			else if (a.type().equals("MA") || a.type().equals("M"))
			{	ListElement larg=a.arguments();
				while (larg!=null)
				{	s=(String)larg.content();
					i=Field.i(s);
					j=Field.j(s);
					if (valid(i,j))
					{	P.marker(i,j,Field.CROSS);
						update(i,j);
					}
					larg=larg.next();
				}
			}
			else if (a.type().equals("TR"))
			{	ListElement larg=a.arguments();
				while (larg!=null)
				{	s=(String)larg.content();
					i=Field.i(s);
					j=Field.j(s);
					if (valid(i,j))
					{	P.marker(i,j,Field.TRIANGLE);
						update(i,j);
					}
					larg=larg.next();
				}
			}
			else if (a.type().equals("CR"))
			{	ListElement larg=a.arguments();
				while (larg!=null)
				{	s=(String)larg.content();
					i=Field.i(s);
					j=Field.j(s);
					if (valid(i,j))
					{	P.marker(i,j,Field.CIRCLE);
						update(i,j);
					}
					larg=larg.next();
				}
			}
			else if (a.type().equals("L"))
			{	ListElement larg=a.arguments();
				while (larg!=null)
				{	s=(String)larg.content();
					i=Field.i(s);
					j=Field.j(s);
					if (valid(i,j))
					{	P.letter(i,j,let);
						let++;
						update(i,j);
					}
					larg=larg.next();
				}
			}
			else if (a.type().equals("LB"))
			{	ListElement larg=a.arguments();
				while (larg!=null)
				{	s=(String)larg.content();
					i=Field.i(s);
					j=Field.j(s);
					if (valid(i,j) && s.length()>=4 &&
						s.charAt(2)==':')
					{	P.setlabel(i,j,s.substring(3));
						update(i,j);
					}
					larg=larg.next();
				}
			}
			la=la.next();
		}
   		if (!Comment.getText().equals(sc))
        {	Comment.setText(sc);
	        Comment.append("");
        }
		if (Range>=0 && !KeepRange) clearrange();
	}

	public void clearsend ()
	{	if (sendi>=0)
		{	int i=sendi; sendi=-1; update(i,sendj);
		}
	}

	public void getinformation ()
	// update the comment, when leaving the position
	{	ListElement la=((Node)Pos.content()).actions();
		Action a;
		clearsend();
		while (la!=null)
		{	a=(Action)la.content();
			if (a.type().equals("C"))
			{	if (Comment.getText().equals(""))
					((Node)Pos.content()).removeaction(la);
				else
					a.arguments().content((Object)Comment.getText());
				return;
			}
			la=la.next();
		}
		String s=Comment.getText();
		if (!s.equals(""))
		{	((Node)Pos.content()).addaction(new Action("C",s));
		}
	}

	synchronized public void update (int i, int j)
	// update the field (i,j) in the offscreen image Active
	// in dependance of the board position P.
	// display the last move mark, if applicable.
	{	if (ActiveImage==null) return;
		if (i<0 || j<0) return;
		Graphics g=ActiveImage.getGraphics();
		g.clipRect(O+OTU+i*D,O+OTU+j*D,D,D);
		synchronized (this)
		{	g.drawImage(Empty,0,0,this);
		}
		String hs;
		char c[]=new char[1];
		int xi=O+OTU+i*D;
		int xj=O+OTU+j*D;
		int n;
		if (P.color(i,j)>0)
		{	if (BlackStone!=null)
			{	g.drawImage(BlackStone,xi-1,xj-1,this);
			}
			else
			{	g.setColor(GF.BlackColor);
				g.fillOval(xi+1,xj+1,D-2,D-2);
				g.setColor(GF.BlackSparkleColor);
				g.drawArc(xi+D/2,xj+D/4,D/4,D/4,40,50);
			}
		}
		else if (P.color(i,j)<0)
		{	if (WhiteStone!=null)
			{	g.drawImage(WhiteStone,xi-1,xj-1,this);
			}
			else
			{	g.setColor(GF.WhiteColor);
				g.fillOval(xi+1,xj+1,D-2,D-2);
				g.setColor(GF.WhiteSparkleColor);
				g.drawArc(xi+D/2,xj+D/4,D/4,D/4,40,50);
			}
		}
		if (P.tree(i,j)!=null)
		{	if (GF.BWColor) g.setColor(Color.black);
			else g.setColor(Color.green);
			g.drawLine(xi+D/2-D/6,xj+D/2,xi+D/2+D/6,xj+D/2);
			g.drawLine(xi+D/2,xj+D/2-D/6,xi+D/2,xj+D/2+D/6);
		}
		if (P.marker(i,j)!=Field.NONE)
		{	g.setColor(Color.blue);
			int h=D/4;
			switch (P.marker(i,j))
			{	case Field.CIRCLE :
					g.drawOval(xi+D/2-h,xj+D/2-h,2*h,2*h);
					break;
				case Field.CROSS :
					g.drawLine(xi+D/2-h,xj+D/2-h,xi+D/2+h,xj+D/2+h);
					g.drawLine(xi+D/2+h,xj+D/2-h,xi+D/2-h,xj+D/2+h);
					break;
				case Field.TRIANGLE :
					g.drawLine(xi+D/2,xj+D/2-h,xi+D/2-h,xj+D/2+h);
					g.drawLine(xi+D/2,xj+D/2-h,xi+D/2+h,xj+D/2+h);
					g.drawLine(xi+D/2-h,xj+D/2+h,xi+D/2+h,xj+D/2+h);
					break;
				default : g.drawRect(xi+D/2-h,xj+D/2-h,2*h,2*h);
			}
		}
		if (P.letter(i,j)!=0)
		{	if (GF.BWColor) g.setColor(Color.white);
			else g.setColor(Color.yellow);
			c[0]=(char)('a'+P.letter(i,j)-1);
			hs=new String(c);
			int w=fontmetrics.stringWidth(hs)/2;
			int h=fontmetrics.getAscent()/2-1;
			g.setFont(font);
			g.drawString(hs,xi+D/2-w,xj+D/2+h);
		}
		if (P.haslabel(i,j))
		{	if (GF.BWColor) g.setColor(Color.white);
			else g.setColor(Color.pink);
			hs=P.label(i,j);
			int w=fontmetrics.stringWidth(hs)/2;
			int h=fontmetrics.getAscent()/2-1;
			g.setFont(font);
			g.drawString(hs,xi+D/2-w,xj+D/2+h);
		}
		if (sendi==i && sendj==j)
		{	if (GF.BWColor) g.setColor(Color.white);
			else g.setColor(Color.gray);
			g.drawLine(xi+D/2-1,xj+D/2,xi+D/2+1,xj+D/2);
			g.drawLine(xi+D/2,xj+D/2-1,xi+D/2,xj+D/2+1);
		}
		if (lasti==i && lastj==j && showlast)
		{	if (GF.LastNumber || (Range>=0 && P.number(i,j)>Range))
			{	if (P.color(i,j)>0) g.setColor(Color.white);
				else g.setColor(Color.black);
				hs=""+(P.number(i,j)%100);
				int w=fontmetrics.stringWidth(hs)/2;
				int h=fontmetrics.getAscent()/2-1;
				g.setFont(font);
				g.drawString(hs,xi+D/2-w,xj+D/2+h);
			}
			else
			{	if (GF.BWColor)
				{	if (P.color(i,j)>0) g.setColor(Color.white);
					else g.setColor(Color.black);
				}
				else g.setColor(Color.red);
				g.drawLine(xi+D/2-D/6,xj+D/2,xi+D/2+D/6,xj+D/2);
				g.drawLine(xi+D/2,xj+D/2-D/6,xi+D/2,xj+D/2+D/6);
			}
		}
		else if (P.color(i,j)!=0 && Range>=0 && P.number(i,j)>Range)
		{	if (P.color(i,j)>0) g.setColor(Color.white);
			else g.setColor(Color.black);
			hs=""+(P.number(i,j)%100);
			int w=fontmetrics.stringWidth(hs)/2;
			int h=fontmetrics.getAscent()/2-1;
			g.setFont(font);
			g.drawString(hs,xi+D/2-w,xj+D/2+h);
		}
		g.dispose();
	}

	public void copy ()
	// copy the offscreen board to the screen
	{	if (ActiveImage==null) return;
		try
		{   getGraphics().drawImage(ActiveImage,0,0,this);
		}
		catch (Exception e) {}
	}

	public void undonode (Node n)
	// Undo everything that has been changed in the node.
	// (This will not correct the last move marker!)
	{	clearrange();
		ListElement p=n.lastchange();
		while (p!=null)
		{	Change c=(Change)p.content();
			P.color(c.I,c.J,c.C);
			update(c.I,c.J);
			p=p.previous();
		}
		n.clearchanges();
		Pw-=n.Pw; Pb-=n.Pb;
	}

	public void setaction (Node n, Action a, int c)
	// interpret a set move action, update the last move marker,
	// c being the color of the move.
	{	String s=(String)(a.arguments().content());
		int i=Field.i(s);
		int j=Field.j(s);
		if (!valid(i,j)) return;
		n.addchange(new Change(i,j,P.color(i,j)));
		P.color(i,j,c);
		P.number(i,j,n.number()-1);
		showlast=false;
		update(lasti,lastj);
		showlast=true;
		lasti=i; lastj=j;
		update(i,j);
		P.color(-c);
		capture(i,j,n);
	}

	public void placeaction (Node n, Action a, int c)
	// interpret a set move action, update the last move marker,
	// c being the color of the move.
	{	int i,j;
		ListElement larg=a.arguments();
		while (larg!=null)
		{	String s=(String)larg.content();
			i=Field.i(s);
			j=Field.j(s);
			if (valid(i,j))
			{	n.addchange(new Change(i,j,P.color(i,j)));
				P.color(i,j,c);
				update(i,j);
			}
			larg=larg.next();
		}
	}

	public void emptyaction (Node n, Action a)
	// interpret a remove stone action
	{	int i,j,r=1;
		ListElement larg=a.arguments();
		while (larg!=null)
		{	String s=(String)larg.content();
			i=Field.i(s);
			j=Field.j(s);
			if (valid(i,j))
			{	n.addchange(new Change(i,j,P.color(i,j)));
				if (P.color(i,j)<0) { n.Pw++; Pw++; }
				else if (P.color(i,j)>0) { n.Pb++; Pb++; }
				P.color(i,j,0);
				update(i,j);
			}
			larg=larg.next();
		}
	}

	public void setnode (Node n)
	// interpret all actions of a node
	{	ListElement p=n.actions();
		if (p==null) return;
		Action a;
		String s;
		int i,j;
		n.clearchanges();
		n.Pw=n.Pb=0;
		while (p!=null)
		{	a=(Action)(p.content());
			if (a.type().equals("B"))
			{	setaction(n,a,1);
			}
			else if (a.type().equals("W"))
			{	setaction(n,a,-1);
			}
			if (a.type().equals("AB"))
			{	placeaction(n,a,1);
			}
			if (a.type().equals("AW"))
			{	placeaction(n,a,-1);
			}
			else if (a.type().equals("AE"))
			{	emptyaction(n,a);
			}
			else if (a.type().equals("SZ"))
			{	if (Pos.parent()==null)
				// only at first node
				{	try
					{	int ss=Integer.parseInt(a.argument());
						if (ss!=S)
						{	S=ss;
							P=new Position(S);
							makeimages();
							updateall();
							copy();
						}
					}
					catch (NumberFormatException e) {}
				}
			}
			p=p.next();
		}
	}

	public void setlast (Node n)
	// update the last move marker applying all
	// set move actions in the node
	{	ListElement l=n.actions();
		Action a;
		String s;
		int i=lasti,j=lastj;
		lasti=-1; lastj=-1;
		update(i,j);
		while (l!=null)
		{	a=(Action)(l.content());
			if (a.type().equals("B") || a.type().equals("W"))
			{	s=(String)a.arguments().content();
				i=Field.i(s);
				j=Field.j(s);
				if (valid(i,j))
				{	lasti=i; lastj=j; update(lasti,lastj);
					P.color(-P.color(i,j));
				}
			}
			l=l.next();
		}
		number=n.number();
	}

	public void undo ()
	// take back the last move
	{	if (((Node)Pos.content()).main()
			&& GF.wantsmove())
		{	if (!Pos.haschildren()) GF.undo();
			return;
		}
		if (Pos.haschildren()) GF.askundo(Pos);
		else doundo(Pos);
	}

	public void doundo (Tree pos1)
	{	if (pos1!=Pos) return;
		if (Pos.parent()==null)
		{	undonode((Node)Pos.content());
			((Node)Pos.content()).removeactions();
			showinformation();
			copy();
			return;
		}
		Tree pos=Pos;
		goback();
		if (((Node)pos.content()).main()
		    && Pos.parent().parent()!=null) Pos.removeall();
		else Pos.remove(pos);
		showinformation();
		copy();
	}

	public void goback ()
	// go one move back
	{	State=1;
		if (Pos.parent()==null) return;
		undonode((Node)Pos.content());
		Pos=Pos.parent();
		setlast((Node)Pos.content());
	}

	public void goforward ()
	// go one move forward
	{	if (!Pos.haschildren()) return;
		Pos=Pos.firstchild();
		setnode((Node)Pos.content());
		setlast((Node)Pos.content());
	}

	// methods to move in the game tree, including
	// update of the visible board:
	public void back ()
	{	State=1;
		getinformation();
		goback();
		showinformation();
		copy();
	}
	public void forward ()
	{	State=1;
	    getinformation();
		goforward();
		showinformation();
		copy();
	}
	public void fastback ()
	{	getinformation();
		for (int i=0; i<10; i++) goback();
		showinformation();
		copy();
	}
	public void fastforward ()
	{	getinformation();
		for (int i=0; i<10; i++) goforward();
		showinformation();
		copy();
	}
	public void allback ()
	{	getinformation();
		while (Pos.parent()!=null) goback();
		showinformation();
		copy();
	}
	public void allforward ()
	{	getinformation();
		while (Pos.haschildren()) goforward();
		showinformation();
		copy();
	}
	public void varleft ()
	{	State=1;
		getinformation();
		ListElement l=Pos.listelement();
		if (l==null) return;
		if (l.previous()==null) return;
		Tree newpos=(Tree)l.previous().content();
		goback();
		Pos=newpos;
		setnode((Node)Pos.content());
		showinformation();
		copy();
	}
	public void varright ()
	{	State=1;
		getinformation();
		ListElement l=Pos.listelement();
		if (l==null) return;
		if (l.next()==null) return;
		Tree newpos=(Tree)l.next().content();
		goback();
		Pos=newpos;
		setnode((Node)Pos.content());
		showinformation();
		copy();
	}
	public void tovarleft ()
	{	ListElement l=Pos.listelement();
		if (l==null) return;
		if (l.previous()==null) return;
		Tree newpos=(Tree)l.previous().content();
		goback();
		Pos=newpos;
		setnode((Node)Pos.content());
	}
	public void tovarright ()
	{	ListElement l=Pos.listelement();
		if (l==null) return;
		if (l.next()==null) return;
		Tree newpos=(Tree)l.next().content();
		goback();
		Pos=newpos;
		setnode((Node)Pos.content());
	}
	public void varmain ()
	{	State=1;
		getinformation();
		while (Pos.parent()!=null &&
			!((Node)Pos.content()).main())
		{	goback();
		}
		if (Pos.haschildren()) goforward();
		showinformation();
		copy();
	}
	public void varmaindown ()
	{	State=1;
		getinformation();
		while (Pos.parent()!=null &&
			!((Node)Pos.content()).main())
		{	goback();
		}
		while (Pos.haschildren())
		{	goforward();
		}
		showinformation();
		copy();
	}
	public void varup ()
	{	State=1;
		getinformation();
		if (Pos.parent()!=null) goback();
		while (Pos.parent()!=null &&
			Pos.parent().firstchild()==Pos.parent().lastchild()
			&& !((Node)Pos.content()).main())
		{	goback();
		}
		showinformation();
		copy();
	}

	public void setblack ()
	// toggle set black mode on
	{	getinformation();
		State=3;
		showinformation();
	}

	public void setwhite ()
	// toggle set white mode on
	{	getinformation();
		State=4;
		showinformation();
	}

	public void black ()
	// black to play
	{	getinformation();
		State=1;
		P.color(1);
		showinformation();
	}

	public void white ()
	// white to play
	{	getinformation();
		State=2;
		P.color(-1);
		showinformation();
	}

	public void mark ()
	// marking
	{	getinformation();
		State=5;
		showinformation();
	}

	public void specialmark (int i)
	// marking
	{	getinformation();
		State=9;
		SpecialMarker=i;
		showinformation();
	}

	public void textmark (String s)
	// marking
	{	getinformation();
		State=10;
		TextMarker=s;
		showinformation();
	}

	public void letter ()
	// letter
	{	getinformation();
		State=6;
		showinformation();
	}

	public void deletestones ()
	// hide stones
	{	getinformation();
		State=7;
		showinformation();
	}

	public void pass ()
	{	if (Pos.haschildren()) return;
		if (GF.blocked() && ((Node)Pos.content()).main()) return;
		if (((Node)Pos.content()).main() && GF.wantsmove())
		{	GF.movepass(); return;
		}
		getinformation();
		P.color(-P.color());
		Node n=new Node(number);
		n.main(Pos);
		Pos.addchild(new Tree(n));
		goforward();
		setlast((Node)Pos.content());
		showinformation();
		copy();
		GF.addcomment("Pass");
	}

	public void black (int i, int j)
	// set a white stone at i,j at the end of the main tree
	{	if (i<0 || j<0 || i>=S || j>=S) return;
		Tree p=History;
		while (p.haschildren()) p=p.firstchild();
		Action a=new Action("B",Field.string(i,j));
		Node n=new Node(((Node)p.content()).number()+1);
		n.main(true);
		n.addaction(a);
		p.addchild(new Tree(n));
		GF.yourmove(Pos!=p);
		if (Pos==p) forward();
		MainColor=-1;
	}

	public void white (int i, int j)
	// set a white stone at i,j at the end of the main tree
	{	if (i<0 || j<0 || i>=S || j>=S) return;
		Tree p=History;
		while (p.haschildren()) p=p.firstchild();
		Action a=new Action("W",Field.string(i,j));
		Node n=new Node(((Node)p.content()).number()+1);
		n.main(true);
		n.addaction(a);
		p.addchild(new Tree(n));
		GF.yourmove(Pos!=p);
		if (Pos==p) forward();
		MainColor=1;
	}

	public void setblack (int i, int j)
	// set a white stone at i,j at the end of the main tree
	{	if (i<0 || j<0 || i>=S || j>=S) return;
		Tree p=History;
		while (p.haschildren()) p=p.firstchild();
		Action a=new Action("AB",Field.string(i,j));
		Node n;
		if (p==History)
		{	Tree newpos;
			p.addchild(newpos=new Tree(n=new Node(1)));
			if (Pos==p) Pos=newpos;
			p=newpos;
			n.main(true);
		}
		n=(Node)p.content();
		n.expandaction(a);
		if (Pos==p)
		{	n.addchange(new Change(i,j,P.color(i,j)));
			P.color(i,j,1); update(i,j);
			copy();
		}
		MainColor=-1;
	}

	public void setwhite (int i, int j)
	// set a white stone at i,j at the end of the main tree
	{	if (i<0 || j<0 || i>=S || j>=S) return;
		Tree p=History;
		while (p.haschildren()) p=p.firstchild();
		Action a=new Action("AW",Field.string(i,j));
		Node n;
		if (p==History)
		{	Tree newpos;
			p.addchild(newpos=new Tree(n=new Node(1)));
			if (Pos==p) Pos=newpos;
			p=newpos;
			n.main(true);
		}
		n=(Node)p.content();
		n.expandaction(a);
		if (Pos==p)
		{	n.addchange(new Change(i,j,P.color(i,j)));
			P.color(i,j,-1); update(i,j);
			copy();
		}
		MainColor=1;
	}

	public void territory (int i, int j)
	{	mark(i,j);
		copy();
	}

	public void handicap (int n)
	{	int h=(S<13)?3:4;
		if (n>5)
		{	setblack(h-1,S/2); setblack(S-h,S/2);
		}
		if (n>7)
		{	setblack(S/2,h-1); setblack(S/2,S-h);
		}
		switch (n)
		{	case 9 :
			case 7 :
			case 5 :
				setblack(S/2,S/2);
			case 8 :
			case 6 :
			case 4 :
				setblack(S-h,S-h);
			case 3 :
				setblack(h-1,h-1);
			case 2 :
				setblack(h-1,S-h);
			case 1 :
				setblack(S-h,h-1);
		}
		MainColor=-1;
	}

	public void setpass ()
	{	Tree p=History;
		while (p.haschildren()) p=p.firstchild();
		Node n=new Node(number);
		n.main(true);
		p.addchild(new Tree(n));
		GF.yourmove(Pos!=p);
		if (Pos==p)
		{	getinformation();
			int c=P.color();
			goforward();
			P.color(-c);
			showinformation();
			GF.addcomment("Pass");
		}
		MainColor=-MainColor;
	}

	public void resume ()
	// Resume playing after marking
	{	getinformation();
		State=1;
		showinformation();
	}

	public void clearmarks ()
	// Clear all marks in the current node
	{	getinformation();
		Node n=(Node)Pos.content();
		undonode(n);
		ListElement la=n.actions(),lan;
		Action a;
		while (la!=null)
		{	a=(Action)la.content();
			lan=la.next();
			if (a.type().equals("M") || a.type().equals("L")
				|| a.type().equals("MA") || a.type().equals("SQ")
				|| a.type().equals("SL") || a.type().equals("CR")
				|| a.type().equals("TR") || a.type().equals("LB"))
			{	n.removeaction(la);
			}
			la=lan;
		}
		setnode(n);
		showinformation();
		copy();
	}

	public void clearremovals ()
	// Clear all marks in the current node
	{	if (Pos.haschildren()) return;
		getinformation();
		Node n=(Node)Pos.content();
		undonode(n);
		ListElement la=n.actions(),lan;
		Action a;
		while (la!=null)
		{	a=(Action)la.content();
			lan=la.next();
			if (a.type().equals("AB") || a.type().equals("AW")
				|| a.type().equals("AE"))
			{	n.removeaction(la);
			}
			la=lan;
		}
		setnode(n);
		showinformation();
		copy();
	}

	Node newtree ()
	{	number=1; Pw=Pb=0;
		Node n=new Node(number);
		n.main(true);
		History=new Tree(n);
		Pos=History;
		P=new Position(S);
		lasti=lastj=-1;
		updateall();
		copy();
		return n;
	}

	boolean deltree ()
	{	newtree();
		return true;
	}

	char readnext (DataInputStream in) throws IOException
	// read a character and ignore blanks, carriage return
	// linefeed and tab
	{	char c=(char)in.readByte();
		while (c=='\r' || c=='\n' || c=='\t' || c==' ')
		{	c=(char)in.readByte();
		}
		return c;
	}

	char readchar (DataInputStream in) throws IOException
	// read a character and ignore carriage return
	{	char c;
		while (true)
		{	c=(char)in.readByte();
			if (c!='\r') return c;
		}
	}

	char readnode (Tree p, DataInputStream in) throws IOException
	// read a node assuming that ; has been found
	// return the character, which did not fit into node properties,
	// usually ;, ( or )
	{	boolean sgf=Global.getParameter("sgfcomments",false);
		char c=readnext(in);
		Action a;
		Node n=new Node(((Node)p.content()).number());
		String s;
		loop: while (true) // read all actions
		{	BufferN=0;
			while (true)
			{	if (c>='A' && c<='Z') Buffer[BufferN++]=c;
					// note only capital letters
				else if (c=='(' || c==';' || c==')') break loop;
					// last property reached
					// BufferN should be 0 then
				else if (c=='[') break;
					// end of porperty type, arguments starting
				else if (c<'a' || c>'z') throw new IOException();
					// this is an error
				c=readnext(in);
			}
			if (BufferN==0) throw new IOException();
			s=new String(Buffer,0,BufferN);
			Dump.println("Command: "+s);
			if (s.equals("L")) a=new LabelAction();
			else if (s.equals("M")) a=new MarkAction();
			else a=new Action(s);
			while (c=='[')
			{	BufferN=0;
				while (true)
				{	c=readchar(in);
					if (c=='\\')
					{	c=readchar(in);
						if (sgf && c=='\n')
						{	if (BufferN>1 && Buffer[BufferN-1]==' ') continue;
							else c=' ';
						}
					}
					else if (c==']') break;
					Buffer[BufferN++]=c;
				}
				c=readnext(in); // prepare next argument
				String s1;
				if (BufferN>0) s1=new String(Buffer,0,BufferN);
				else s1="";
				Dump.println("["+s1+"]");
				if (!expand(a,s1)) a.addargument(s1);
			}
			// no more arguments
			n.addaction(a);
			if (a.type().equals("B") || a.type().equals("W"))
			{	n.number(n.number()+1);
			}
		} // end of actions has been found
		// append node
		n.main(p);
		Tree newp;
		if (((Node)p.content()).actions()==null)
			p.content(n);
		else
		{	p.addchild(newp=new Tree(n));
			p=newp;
			if (p.parent()!=null && p!=p.parent().firstchild())
				((Node)p.content()).number(2);
		}
		return c;
	}

	boolean expand (Action a, String s)
	// Check for the terrible compressed point list and expand into
	// single points
	{	String t=a.type();
		if (!(t.equals("MA") || t.equals("SQ") || t.equals("TR") ||
			 t.equals("CR") || t.equals("AW") || t.equals("AB") ||
			  t.equals("AE") || t.equals("SL"))) return false;
		if (s.length()!=5 || s.charAt(2)!=':') return false;
		String s0=s.substring(0,2),s1=s.substring(3);
		int i0=Field.i(s0),j0=Field.j(s0);
		if (!valid(i0,j0)) return false;
		int i1=Field.i(s1),j1=Field.j(s1);
		if (!valid(i1,j1) || i1<i0 || j1<j0) return false;
		int i,j;
		for (i=i0; i<=i1; i++)
			for (j=j0; j<=j1; j++)
			{	a.addargument(Field.string(i,j));
			}
		return true;
	}

	public void readnodes (Tree p, DataInputStream in) throws IOException
	// read the nodes belonging to a tree.
	// this assumes that ( has been found.
	{	char c=readnext(in);
		while (true)
		{	if (c==';')
			{	c=readnode(p,in);
				if (p.haschildren()) p=p.lastchild();
				continue;
			}
			else if (c=='(')
			{	readnodes(p,in);
			}
			else if (c==')') break;
			c=readnext(in);
		}
	}

	public void load (DataInputStream in)
	// Load a game
	{	Dump.println("Loading SGF file");
		showlast=false;
		update(lasti,lastj);
		showlast=true;
		lasti=lastj=-1;
		newtree();
		boolean linestart=true;
		char c;
		try
		{	while (true) // search for ( at line start
			{	c=(char)in.readByte();
				if (linestart && c=='(') break;
				if (c=='\n') linestart=true;
				else linestart=false;
			}
			readnodes(Pos,in); // read the nodes
		}
		catch (IOException e)
		{	new Message(GF,"Error in file!");
		}
		setnode((Node)Pos.content());
		showinformation();
		copy();
	}

	public void save (PrintWriter o)
	// Save the file to the specified print stream
	// in SGF
	{	getinformation();
		((Node)History.content()).setaction("AP","Jago:1.41",true);
		((Node)History.content()).setaction("SZ",""+S,true);
		((Node)History.content()).setaction("GM","1",true);
		((Node)History.content()).setaction("FF",
			Global.getParameter("puresgf",false)?"4":"1",true);
		printtree(History,o);
	}

	public void printtree (Tree p, PrintWriter o)
	// Print a list of nodes.
	{	o.println("(");
	    while (true)
		{	((Node)p.content()).print(o);
			if (!p.haschildren()) break;
			if (p.lastchild()!=p.firstchild())
			{	ListElement e=p.children().first();
				while (e!=null)
				{	printtree((Tree)e.content(),o);
					e=e.next();
				}
				break;
			}
			p=p.firstchild();
		}
		o.println(")");
	}

	public void active (boolean f) { Active=f; }

	public void setsize (int s)
	{	if (s<5 || s>29) return;
		S=s;
		P=new Position(S);
		number=1;
		Node n=new Node(number);
		n.main(true);
		lasti=lastj=-1;
		History=new Tree(n);
		Pos=History;
		makeimages();
		showinformation();
		copy();
	}

	public int getboardsize ()
	{	return S;
	}

	public boolean score ()
	{	if (Pos.haschildren()) return false;
		getinformation();
		State=8; Removing=true;
		showinformation();
		if (((Node)Pos.content()).main()) return true;
		else return false;
	}

	public boolean done ()
	{	if (Pos.haschildren()) return false;
		clearmarks();
		getinformation();
		int i,j;
		int tb=0,tw=0,sb=0,sw=0;
		P.getterritory();
		for (i=0; i<S; i++)
			for (j=0; j<S; j++)
			{	if (P.territory(i,j)==1 || P.territory(i,j)==-1)
				{	mark(i,j);
					if (P.territory(i,j)>0) tb++;
					else tw++;
				}
				else
				{	if (P.color(i,j)>0) sb++;
					else if (P.color(i,j)<0) sw++;
				}
			}
		new Message(GF,"Chinese count:\nBlack: "+(sb+tb)+", White: "+(sw+tw)+
			"\nJapanese count:\nBlack: "+(Pw+tb)+", White: "+(Pb+tw)
			);
		showinformation();
		copy();
		if (((Node)Pos.content()).main())
		{	GF.result(tb,tw);
			return true;
		}
		else return false;
	}

	public void docount ()
	{	clearmarks();
		getinformation();
		int i,j;
		int tb=0,tw=0,sb=0,sw=0;
		P.getterritory();
		for (i=0; i<S; i++)
			for (j=0; j<S; j++)
			{	if (P.territory(i,j)==1 || P.territory(i,j)==-1)
				{	mark(i,j);
					if (P.territory(i,j)>0) tb++;
					else tw++;
				}
				else
				{	if (P.color(i,j)>0) sb++;
					else if (P.color(i,j)<0) sw++;
				}
			}
		new Message(GF,"Chinese count:\nBlack: "+(sb+tb)+", White: "+(sw+tw)+
			"\nJapanese count:\nBlack: "+(Pw+tb)+", White: "+(Pb+tw)
			);
		showinformation();
		copy();
	}

	public boolean canfinish ()
	{	return (!Pos.haschildren()) && ((Node)Pos.content()).main();
	}

	public void addcomment (String s)
	{	Tree p=History;
		while (p.haschildren()) p=p.firstchild();
		if (Pos==p) getinformation();
		ListElement la=((Node)p.content()).actions();
		Action a;
		String Added="";
		ListElement larg;
		outer: while (true)
		{	while (la!=null)
			{	a=(Action)la.content();
				if (a.type().equals("C"))
				{	larg=a.arguments();
					if (((String)larg.content()).equals(""))
					{	larg.content(s);
						Added=s;
					}
					else
					{	larg.content((String)larg.content()+"\n"+s);
						Added="\n"+s;
					}
					break outer;
				}
				la=la.next();
			}
			((Node)p.content()).addaction(new Action("C",s));
			break;
		}
		if (Pos==p)
		{	Comment.append(Added);
			showinformation();
		}
	}

	public void undo (int n)
	{	varmaindown();
		for (int i=0; i<n; i++)
		{	goback();
			Pos.removeall();
			showinformation();
			copy();
		}
		GF.addcomment("Undo");
	}

	int maincolor ()
	{	return MainColor;
	}

	public void insertnode ()
	{	if (((Node)Pos.content()).main() && GF.wantsmove() &&
			!Pos.haschildren())
				return;
		if (Pos.haschildren()) return;
		Node n=new Node(((Node)Pos.content()).number());
		n.main(Pos);
		Pos.addchild(new Tree(n));
		getinformation();
		Pos=Pos.lastchild();
		setlast(n);
		showinformation();
		copy();
	}

	public void insertvariation ()
	{	if (Pos.parent()==null) return;
		getinformation();
		int c=P.color();
		back();
		Node n=new Node(2);
		Pos.addchild(new Tree(n));
		n.main(Pos);
		Pos=Pos.lastchild();
		setlast(n);
		P.color(-c);
		showinformation();
		copy();
	}

	boolean ismain ()
	{	return ((Node)Pos.content()).main() && !Pos.haschildren();
	}

	Node firstnode ()
	{	return (Node)History.content();
	}

	boolean valid (int i, int j)
	{	return (i>=0 && i<S && j>=0 && j<S);
	}

	public void laterload (String s)
	{	LaterLoad=s;
	}

	public void lastrange (int n)
	{	int l=(((Node)Pos.content()).number());
		Range=(l/n)*n;
		KeepRange=true; updateall(); copy(); KeepRange=false;
	}

	public void clearrange ()
	{	if (Range==-1) return;
		Range=-1; updateall(); copy();
	}

	public void update (Graphics g)
	{	paint(g);
	}

	public void print ()
    {   Position p=new Position(P);
        PrintBoard PB=new PrintBoard(p,Range,GF);
    }

    void setname (String s)
    {   Node n=(Node)Pos.content();
        n.setaction("N",s,true);
        showinformation();
    }

    String getname ()
    {   Node n=(Node)Pos.content();
        return n.getaction("N");
    }

    void gotonext ()
	{	State=1;
		getinformation();
		goforward();
		while (((Node)Pos.content()).getaction("N").equals(""))
		{   if (!Pos.haschildren()) break;
		    goforward();
		}
		showinformation();
		copy();
	}

    void gotoprevious ()
	{	State=1;
		getinformation();
		goback();
		while (((Node)Pos.content()).getaction("N").equals(""))
		{   if (Pos.parent()==null) break;
		    goback();
		}
		showinformation();
		copy();
	}

    void gotonextmain ()
    {   State=1;
        getinformation();
        while (Pos.parent()!=null)
        {   if (Pos.parent().parent()==null)
            {   tovarright(); break;
            }
            goback();
        }
        showinformation();
        copy();
    }

    void gotopreviousmain ()
    {   State=1;
        getinformation();
        while (Pos.parent()!=null)
        {   if (Pos.parent().parent()==null)
            {   tovarleft(); break;
            }
            goback();
        }
        showinformation();
        copy();
    }
}
