package real;

public class RealLine {
	// always normalized
	public double A, B, C;
	
	public RealLine(double a, double b, double c) {
		A = a; B = b; C = c;
		normalize();
	}
	
	public RealLine(RealSegment s) {
		// (q - p) rotated 90 degrees
		A = s.p[0].y - s.p[1].y;
		B = s.p[1].x - s.p[0].x;
		C = A*s.p[0].x + B*s.p[0].y;
		normalize();
	}
	
	void normalize() {
	
		double r, d;
		if (Math.abs(A) > Math.abs(B)) {
			d = B/A;
			r = Math.abs(A)*Math.sqrt(1 + d*d);
		} else {
			d = A/B;
			r = Math.abs(B)*Math.sqrt(1 + d*d);
		}
		A /= r; B /= r; C /= r;
	}
	
	public RealPoint intersectionWith(RealLine ell) {
		// A0*x + B0*y = C0 and Ax + By = C
		double a, b, c, a0, b0, c0;
		double x, y;
		if (Math.abs(A) > Math.abs(B)) {
			a = 1; b = B/A; c = C/A;
			b0 = ell.B - ell.A*b;
			c0 = ell.C - ell.A*c;
			if (b0 != 0.0) {
				// there is a unique intersection point
				y = c0/b0;
				x = c - b*y;
				return(new RealPoint(x, y));
				
			} else return(null);
		} else {
			a = A/B; b = 1; c = C/B;
			a0 = ell.A - ell.B*a;
			c0 = ell.C - ell.B*c;
			if (a0 != 0.0) {
				// there is a unique intersection point
				x = c0/a0;
				y = c - a*x;
				return(new RealPoint(x, y));
				
			} else return(null);
		}
	}
	
	public String toString() {
		String s = new String();
		s = s + ("" + A + ":" + B + ":" + C);
		return(s);
	}
}