/* Copyright (c) Oracle Corporation 1999. All Rights Reserved. */

import java.sql.SQLException;
import oracle.sql.CustomDatum;
import oracle.sql.CustomDatumFactory;
import oracle.sql.Datum;
import oracle.sql.STRUCT;
import oracle.jpub.runtime.MutableStruct;
import sqlj.runtime.ConnectionContext;
import java.sql.Connection;

public class MyRationalC extends JPubRationalC
                      implements CustomDatum, CustomDatumFactory
{
  /* _SQL_NAME inherited from JPubRationalC */

  /* _SQL_TYPECODE inherited from JPubRationalC */

  /* _ctx inherited from JPubRationalC */

  /* _sqlType inherited from JPubRationalC */ 

  /* _factory inherited from JPubRationalC */

  /* _struct inherited from JPubRationalC */

  static final MyRationalC _MyRationalCFactory = new MyRationalC();
  public static CustomDatumFactory getFactory()
  {
    return _MyRationalCFactory;
  }

  /* constructors */
  public MyRationalC()
  { 
    super();
  }

  public MyRationalC(int numerator, int denominator)
  throws SQLException
  {
    super();
    setNumerator(numerator);
    setDenominator(denominator);
  }

  /* CustomDatum interface */
  /* toDatum() inherited from JPubRationalC */

  /* CustomDatumFactory interface */
  public CustomDatum create(Datum d, int sqlType) throws SQLException
  {
    if (d == null) return null;
    MyRationalC o = new MyRationalC();
    o._struct = new MutableStruct((STRUCT) d, _sqlType, _factory);
    return o;
  }

  /* shallow copy method inherited from JPubRationalC */

  /* accessor methods inherited from JPubRationalC */

  /* additional methods not in base class */
  public String toString()
  {
    try
    {
       return getNumerator() + "/" + getDenominator();
    }
    catch (SQLException e)
    {
       return null;
    }
  }

  public float toReal() throws SQLException 
  {
    return ((float) getNumerator())/getDenominator();
  }

  public static int gcd(int x, int y)
  {
    if (x < y)
      return gcd(y, x);

    if (x % y == 0)
      return y;

    return gcd (y, x / y);
  }

  public void normalize() throws SQLException
  {
    int n = getNumerator();
    int d = getDenominator();

    int g = gcd(n, d);
    setNumerator(n/g);
    setDenominator(d/g); 
  }

  public MyRationalC plus(MyRationalC x) throws SQLException
  {
    return new MyRationalC(
      getNumerator() * x.getDenominator() +
      x.getNumerator() * getDenominator(), 
      getDenominator() * x.getDenominator());
  }
}
