// Point.java
// $Id: Point.java,v 1.5 1996/08/18 19:18:29 anto Exp $
// (c) COPYRIGHT MIT and INRIA, 1996.
// Please first read the full copyright statement in file COPYRIGHT.html


package w3c.jigsaw.map;

import java.io.*;
import java.util.*;

class Point {
    public int x;
    public int y;

    public Point()
    {
	x=y=0;
    }

    public Point(int x, int y) {
	this.x = x ;
	this.y = y ;
    }
    
    public String toString()
    {
	return new String("("+x+","+y+")");
    }

    public int distanceSquared(Point p)
    {
	int deltaX = x-p.x;
	int deltaY = y-p.y;
	return deltaX*deltaX + deltaY*deltaY;
    }

    public void pickle(DataOutputStream out)
	throws IOException
    {
	out.writeInt(x);
	out.writeInt(y);
    }
    
    public void unpickle(DataInputStream in)
	throws IOException
    {
	x = in.readInt();
	y = in.readInt();
    }

    // Will always throw exception on failure
    public static Point parseNCSA(String line)
	throws MapException
    {
	try {
	    StringTokenizer strtok = new StringTokenizer(line,",");
	    Point result = new Point();
	    result.x = Integer.parseInt(strtok.nextToken());
	    result.y = Integer.parseInt(strtok.nextToken());
	    if(strtok.hasMoreTokens())
		throw new MapException("only 2D points are supported: " +
				       line);

	    return result;

	} catch(NumberFormatException e) {
	    throw new MapException("coordinate parse error: " + line);
	} catch(NoSuchElementException e) {
	    throw new MapException("coordinate parse error: " + line);
	}
    }

    // Returns null if line doesn't contain a W3C point
    public static Point parseW3C(String line)
    {
	line = line.trim();
	int length = line.length();

	try {
	    if(line.charAt(0) != '(' ||
	       line.charAt(length-1) != ')')
		return null;

	    // beware of endIndex in String.substring() !!
	    StringTokenizer strtok = new StringTokenizer(line.substring(1,length-1),
							 ",");
	    Point result = new Point();
	    result.x = Integer.parseInt(strtok.nextToken());
	    result.y = Integer.parseInt(strtok.nextToken());
	    if(strtok.hasMoreTokens())
		throw new MapException("only 2D points are supported: " +
				       line);

	    return result;

	} catch(NumberFormatException e) {
	    throw new MapException("coordinate parse error: " + line);
	} catch(NoSuchElementException e) {
	    throw new MapException("coordinate parse error: " + line);
	} catch(StringIndexOutOfBoundsException e) {
	    throw new MapException("coordinate parse error: " + line);
	}
    }
}	
						     

