/** This class is so far the only implemtation of the ColorTransformer interface. 
 * @author B.Düring
 * @author S.Holst
*/
public class LinearColorTransform
    implements ColorTransformer
{
  double start;
  double end;
  /**
   * The Constructor
   * @param beginning the smallest value to be mapped
   * @param ending the larges value to be mappedd
   * @throws RuntimeException if start>=ending   */
    public LinearColorTransform(double beginning, double ending)
    {
        start = 0.0D;
        end = 1.0D;
        if(beginning >= ending)
        {
            throw new RuntimeException(" end>start is required!");
        } else
        {
            start = beginning;
            end = ending;
            return;
        }
    }

    /** The actual mapping for one pixel
     * @param d value at the pixel
     * @return color value for that pixel
     */
    public final int toColor(double d)
    {
        if(d > end)
            d = end;
        else
        if(d < start)
            d = start;
        double d1 = (d - start) / (end - start);
        int i = (int)(d1 * 1024D);
        int j = 0;
        int k = 0;
        int l = 0;
        switch(i / 256)
        {
        case 0: // '\0'
            l = 255;
            k = i;
            break;

        case 1: // '\001'
            k = 255;
            l = 255 - i % 256;
            break;

        case 2: // '\002'
            k = 255;
            j = i % 256;
            break;

        case 3: // '\003'
            j = 255;
            k = 255 - i % 256;
            break;

        case 4: // '\004'
            j = 255;
            break;
        }
        return 0xff000000 | j << 16 | k << 8 | l;
    }

    /** Mapping for 2D-arrays 
     */
    public Object toColor(Object obj)
    {
        if(obj instanceof double[][])
        {
            int i = ((double[][])obj).length;
            int ai[][] = new int[i][];
            for(int j = 0; j < i; j++)
                ai[j] = toColor(((double[][])obj)[j]);

            return ai;
        } else
        {
            return toColor((double[])obj);
        }
    }

    /** Mapping for 1D-arrays
     */
    private int[] toColor(double ad[])
    {
        int ai[] = new int[ad.length];
        for(int i = 0; i < ad.length; i++)
            ai[i] = toColor(ad[i]);

        return ai;
    }

}
