package hw01;

public class Fraction {
	
	private int whole;
	private int num;
	private int den;
	
	

	public Fraction(int whole, int num, int den) {
		this.whole = whole;
		this.num = num;
		this.den = den;
		normalize();
	}

	private void normalize() {
		// Make sure denominator is positive
		if (num<0 && den<0) {
			num=-num;
			den=-den;
		}
		if (num>=0 && den<0) {
			num=-num;
			den=-den;
		}
		assert(den>0);
		
		// Make sure numerator is less than denominator
		while(Math.abs(num)>=den) {
			if (num<0) {
				num+=den;
				whole--;
			} else {
				num-=den;
				whole++;				
			}
		}
		assert(num<den);
		
		// Make sure numerator and whole number have the same sign
		while (num<0 && whole>0) {
			whole--;
			num = num + den;
		}
		while(num>0 && whole<0) {
			whole++;
			num = num - den;
		}
		if (whole<0) assert(num<0);
		else assert(num>=0);
		
		// Make sure fraction is in simplest terms
		int div=gcd(num,den);
		num = num/div;
		den = den/div;
		assert(gcd(num,den)==1);
	
	}

	private static int gcd(int a,int b) {
		if (a==0) return b;
		if (b==0) return a;
		if (a<0) a=-a;
		if (b<0) b=-b;
		if (a>b) return gcd(a-b,b);
		else return gcd(a,b-a);
	}
	
	public String toString() {
		String answer="";
		if (whole!=0) answer += whole;
		if (num==0) return answer;
		if (whole!=0) answer +=" ";
		if (num>=0 || whole==0) answer +=num;
		else answer += (-num);
		answer += "/" + den;
		return answer;
	}

	public static void main(String[] args) {
		System.out.println("Fraction(0,1,2) expect: 1/2, got: " + new Fraction(0,1,2).toString());
		System.out.println("Fraction(0,9,6) expect: 1 1/2, got: " + new Fraction(0,9,6).toString());
		System.out.println("Fraction(3,1,-2) expect: 2 1/2, got: " + new Fraction(3,1,-2).toString());
		System.out.println("Fraction(0,1,-2) expect: -1/2, got: " + new Fraction(0,1,-2).toString());
	}

}
