 /*
 * @(#) WindowLevel.java 1.0 00/9/27
 * Copyright (c) 2000 Larry Rodrigues
 */

package com.vistech.jai.render;
import java.awt.image.*;
import java.io.*;
import com.vistech.jai.render.*;
import javax.media.jai.*;

/** Implements the Window/Level feature using the JAI API.
  * @version 1.0  27 Sep 2000
  * @author Lawrence Rodrigues
  **/
public class JAIWindowLevel{
   protected int minValue =0;
   protected int maxValue =255;
   protected int MIN_SCREEN_VALUE = 0;
   protected int MAX_SCREEN_VALUE = 255;
   protected int LUT_SIZE = 256;
   protected int lutSize = LUT_SIZE;
   protected int window, level;
   protected PlanarImage image;
   protected JAIImageCanvas imageCanvas;


   public JAIWindowLevel(PlanarImage image, JAIImageCanvas imageCanvas) {
      this.image = image;
      this.imageCanvas = imageCanvas;
   }

   public void setLUTSize(int size) {
      if(size <=0) return;
      lutSize = size;
   }

   public int getLUTSize(){return lutSize;}

   public void setWindow(int win) { window = win;}
   public void setLevel(int lev) {level = lev; }

   public void setWindowLevel(int win, int lev) {
      LookupTableJAI blut = createLookupTable(win, lev);
      RenderedOp op = JAI.create("lookup",image, blut);
      imageCanvas.setImage(op);
      window = win;
      level = lev;
   }

   protected LookupTableJAI createLookupTable(int win, int lev) {
      int windowStart= lev-win/2;
      int windowEnd  = lev+win/2;
      if(windowStart <=0) windowStart =0;
      if(windowEnd > lutSize) windowEnd = lutSize;
      byte lut[] = new byte[lutSize];
      double windowMappingRatio =
                 (MAX_SCREEN_VALUE-MIN_SCREEN_VALUE)/(double)(win);
      for(int i=0;i<windowStart;i++) {
          lut[i] = (byte)MIN_SCREEN_VALUE;
      }
      for(int i = windowStart; i< windowEnd; i++) {
          lut[i] = (byte)((i-windowStart)* windowMappingRatio);
      }
      for(int i = windowEnd; i< lutSize; i++) {
          lut[i] = (byte)MAX_SCREEN_VALUE;
      }
      return  new LookupTableJAI(lut,0);
   }
}