package introspection;

@Exercice(1)
public class ConcreteFraction implements Fraction {
	private int n=0;
	private int d=1;
	
	public ConcreteFraction(int num, int denom){
		n=num; d=denom;
	}
	
	public ConcreteFraction(int num){
		n=num;
	}
	
	public ConcreteFraction(){
		//empty
	}
	
	private static int gcd(int a, int b){
		if(a<0) a=-a;
		if(b<0) b=-b;
		if(b==0) return a;
		while(a!=0){
			int c=a;
			a=b%a;
			b=c;
		}
		return b;
	}
	
	private void reduce(){
		int g=gcd(n,d);
		if(d<0){ d=-d; n=-n; }
		if(g!=0){
			d/=g; n/=g;
		}
			
	}
	
	@Override
	public Fraction addTo(Fraction f) {
		ConcreteFraction r=new ConcreteFraction(n*f.getDenominator() + f.getNumerator()*d,
									 d*f.getDenominator());
		r.reduce();
		return r;
		
	}

	@Override
	public Fraction divBy(Fraction f) {
		return multTo(f.inverse());
	}

	@Override
	public int getDenominator() {
		return d;
	}

	@Override
	public int getNumerator() {
		return n;
	}

	@Override
	public Fraction inverse() {
		ConcreteFraction r=new ConcreteFraction(d,n);
		return r;
	}

	@Override
	public Fraction multTo(Fraction f) {
		ConcreteFraction r=new ConcreteFraction(n*f.getNumerator(), d*f.getDenominator());
		r.reduce();
		return r;
	}

	@Override
	public void setDenominator(int d) {
		this.d = d;
	}

	@Override
	public void setNumerator(int n) {
		this.n = n;
	}

	@Override
	public Fraction subTo(Fraction f) {
		return addTo(f.opposite());
	}
	@Override
	public Fraction opposite() {
		ConcreteFraction r=new ConcreteFraction(-n,d);
		return r;
	}
	@Override
	public String toString(){
		return (""+n+"/"+d);
	}
}
