/* Interval
 * Developed during lecture 3/27 - 4/3
 */

public class Interval {

  private double base;   // low end
  private double range;  // interval width
  public final static double maxWidth=5;

  public Interval(double base, double r) {
    this.base = base;
    range = Math.min(r,maxWidth);
  }

  public Interval() {}

  public Interval(double base) {
    this.base = base;
    range = maxWidth;
  }

  // Get high end of Interval
  public double getEnd() { return base+range; }

  // Expand Interval width by a factor of f
  public void expand(double f) { range*=f; }

  // Check whether self (current object itself) is in Interval i
  public boolean isIn(Interval i) {
    return  base>=i.base && getEnd()<=i.getEnd();
  }

  // Return overlapped Interval between Intervals a and b
  public static Interval overlap(Interval a, Interval b) {
    Interval olap;      // overlapped interval
    double left, right; // olap’s left & right

    left = Math.max(a.base,b.base);           // new left is rightmost of old lefts
    right = Math.min(a.getEnd(),b.getEnd());  // new right is leftmost of old rights
    if ( (right-left)<=0 )                    // no overlap if new right < new left
      olap = null;
    else
      olap = new Interval(left, right-left);

    return olap;
  }

  // String representation of Interval object:  [base,base+range]
  public String toString() {
    return "[" + base + "," + getEnd() + "]";
  } 	

  // Test Harness
  // Write "client code" to test the methods in class Interval
  public static void main(String[] args) {
    Interval i1 = new Interval();
    System.out.println(i1);  // should print [0,0]
    Interval i2 = new Interval(2);
    System.out.println(i2);  // should print [2,7]
    Interval i3 = new Interval(3,100);
    System.out.println(i3);  // should print [3,8]
    System.out.println(overlap(i2,i3));  //should print [3,7]
 
    // ... other tests ...
  }

}