// (C)2007 Attila Kovacs <attila@submm.caltech.edu>

//package crush.util;

import java.text.*;

public class WeightedPoint implements Comparable<WeightedPoint> {
	public double value = 0.0, weight = 0.0;

	public WeightedPoint() {}

	public WeightedPoint(WeightedPoint template) {
		super();
		set(template);
	}

	public WeightedPoint(double x, double w) { 
		value = x;
		weight = w;
	}

	public int compareTo(WeightedPoint point) throws ClassCastException {
		return Double.compare(value, point.value);
	}

	public void noData() { 
		value = 0.0;
		weight = 0.0;
	}

	public boolean isNaN() { return isNaN(this); }

	public static boolean isNaN(WeightedPoint point) { 
		return Double.isNaN(point.value) || point.weight == 0.0;
	}

	public final void exact() { weight = Double.POSITIVE_INFINITY; }

	public final boolean isExact() { return Double.isInfinite(weight); }

	public void set(WeightedPoint x) {
		value = x.value;
		weight = x.weight;
	}

	public final double significance() { return Math.abs(value) * Math.sqrt(weight); }
	
	public void add(WeightedPoint x) {
		value += x.value;
		weight = 1.0 / (1.0/weight + 1.0/x.weight);
	}
	
	public void subtract(WeightedPoint x) {
		value -= x.value;
		weight = 1.0 / (1.0/weight + 1.0/x.weight);
	}
	
	public void average(WeightedPoint x) {
		value = weight * value + x.weight * x.value;
		weight += x.weight;
		if(weight > 0.0) value /= weight;		
	}

	public final void scale(double x) {
		value *= x;
		weight /= x*x;
	}

	public void math(char op, WeightedPoint x) throws IllegalArgumentException {
		switch(op) {
		case '+' : add(x); break;
		case '-' : subtract(x); break;
		default: throw new IllegalArgumentException("Illegal Operation: " + op);
		}
	}

	public static WeightedPoint math(WeightedPoint a, char op, WeightedPoint b) {
		WeightedPoint result = new WeightedPoint(a);
		result.math(op, b);
		return result;
	}

	public void math(char op, double x) throws IllegalArgumentException {
		switch(op) {
		case '+' : value += x; break;
		case '-' : value -= x; break;
		case '*' : value *= x; weight /= x*x; break;
		case '/' : value /= x; weight *= x*x; break;
		default: throw new IllegalArgumentException("Illegal Operation: " + op);
		}
	}

	public static WeightedPoint math(WeightedPoint a, char op, double b) {
		WeightedPoint result = new WeightedPoint(a);
		result.math(op, b);
		return result;
	}

	public final static WeightedPoint NaN = new WeightedPoint(0.0, 0.0);

	public String toString() {
		return value + " +- " + Math.sqrt(1.0 / weight); 
	}

	public String toString(DecimalFormat df) {
		return df.format(value) + " +- " + df.format(Math.sqrt(1.0 / weight)); 
	}

}
