import java.io.PrintWriter;
import jamaica.Range;

/**
 * The wrapper class for jamaica.Range
 *
 * @author Hanhua Feng - hf2048@columbia.edu
 * @version $Id: MxRange.java,v 1.13 2003/05/12 23:44:34 hanhua Exp $
 */
class MxRange extends MxDataType {
    Range range;

    MxRange( Range range ) {
        this.range = range;
    }

    public String typename() {
        return "range";
    }

    public MxDataType copy() {
        return new MxRange( range );
    }

    public static MxDataType create( MxDataType v1, MxDataType v2 ) {
        int s = ( null == v1 ? 0 : MxInt.intValue(v1) );

        if ( null != v2 )
        {
            int t = MxInt.intValue(v2);
            if ( t >= 0 )
                return new MxRange( new Range( s, t ) );
            return new MxRange( new Range( s, t, 1 ) );
        }

        return new MxRange( new Range( s, -1, 1 ) );
    }

    public static MxDataType create( MxDataType v1, MxDataType v2, int stride ) {
        if ( v1 instanceof MxInt && v2 instanceof MxInt ) {
            if ( ((MxInt)v2).var <= 0 )
                return v2.error( "invalid range" );
            return new MxRange( 
                new Range( ((MxInt)v1).var, ((MxInt)v2).var, stride ) );
        }

        return v1.error( v2, "cast to range components" );
    }

    public Range getRange( int n ) {
        /* Tricky short-cut: if range is empty, the "number" field stores
         * a reverse count: -1 means n-1, -2 means n-2, and so on.
         */
        if ( range.empty() )
            return new Range( range.first(), n + range.size() );

        return range;
    }

    public void print( PrintWriter w ) {
        if ( name != null )
            w.print( name + " = " );
        w.println( Integer.toString( range.first() ) + ":" 
                   + range.size() + ":" + range.interval() );
    }

}
