Index: ErmapperProvider.java
===================================================================
--- ErmapperProvider.java	(revision 4180)
+++ ErmapperProvider.java	(revision 4181)
@@ -27,8 +27,13 @@
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileReader;
+import java.net.URI;
+import java.net.URISyntaxException;
 
 import org.cresques.cts.ICoordTrans;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import org.gvsig.fmap.dal.DALFileLocator;
 import org.gvsig.fmap.dal.DALLocator;
 import org.gvsig.fmap.dal.DataStore;
@@ -39,6 +44,7 @@
 import org.gvsig.fmap.dal.coverage.exception.BandAccessException;
 import org.gvsig.fmap.dal.coverage.exception.FileNotOpenException;
 import org.gvsig.fmap.dal.coverage.exception.InvalidSetViewException;
+import org.gvsig.fmap.dal.coverage.exception.InvalidSourceException;
 import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
 import org.gvsig.fmap.dal.coverage.exception.ParsingException;
 import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
@@ -46,6 +52,7 @@
 import org.gvsig.fmap.dal.coverage.store.parameter.RasterDataParameters;
 import org.gvsig.fmap.dal.coverage.store.parameter.RasterFileStoreParameters;
 import org.gvsig.fmap.dal.coverage.store.props.Transparency;
+import org.gvsig.fmap.dal.exception.OpenException;
 import org.gvsig.fmap.dal.spi.DataManagerProviderServices;
 import org.gvsig.fmap.dal.spi.DataStoreProviderServices;
 import org.gvsig.metadata.MetadataLocator;
@@ -70,741 +77,816 @@
 import com.ermapper.ecw.JNCSFileNotOpenException;
 import com.ermapper.ecw.JNCSInvalidSetViewException;
 import com.ermapper.ecw.JNCSProgressiveUpdate;
+
 /**
  * Driver de Ecw
  *
  * @author Nacho Brodin (nachobrodin@gmail.com)
  */
 public class ErmapperProvider extends AbstractRasterProvider implements JNCSProgressiveUpdate {
-	//private static final Logger           logger                   = LoggerFactory.getLogger(ErmapperProvider.class);
-	public static String                  NAME                     = "Ermapper Store";
-	public static String                  DESCRIPTION              = "Ermapper Raster file";
-	public static final String            METADATA_DEFINITION_NAME = "ErmapperStore";
-	private JNCSFile 				      file                     = null;
-	protected Transparency  		      fileTransparency         = null;
-	private Extent                        viewRequest              = null;
-	private DataStoreColorInterpretation  colorInterpr             = null;
-	private boolean                       open                     = false;
-	protected static String[]             formatList               = null;
-	
-	public static void register() {
-		RasterLocator.getManager().getProviderServices().registerFileProvidersTiled(ErmapperProvider.class);
-		registerFormats();
-		
-		DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
-		if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
-			dataman.registerStoreProvider(NAME,
-					ErmapperProvider.class, 
-					ErmapperDataParameters.class);
-		}
-		
-		if(DALFileLocator.getFilesystemServerExplorerManager() != null)
-			DALFileLocator.getFilesystemServerExplorerManager().registerProvider(
-					NAME, 
-					DESCRIPTION,
-					ErmapperFilesystemServerExplorer.class);
-		
-	    dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
-	}
-	
-	private static void registerFormats() {
-		formatList      = new String[] {
-				"ecw", 
-				"jp2"};
-		for (int i = 0; i < formatList.length; i++) 
-			RasterLocator.getManager().getProviderServices().addFormat(formatList[i], ErmapperProvider.class);
-	}
-	
-	public String[] getFormatList() {
-		return formatList;
-	}
-	
-	/**
-	 * Returns true if the extension is supported and false if doesn't
-	 * @param ext
-	 * @return
-	 */
-	public boolean isExtensionSupported(String ext) {
-		if(ext.indexOf(".") != -1)
-			ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
-		for (int i = 0; i < formatList.length; i++) {
-			if(formatList[i].compareTo(ext) == 0)
-				return true;
-		}
-		return false;
-	}
-	
-	/**
-	 * Mandatory constructor to instantiate an empty provider
-	 */
-	public ErmapperProvider() {
-	}
-	
-	/**
-	 * Constructor. Abre el dataset.
-	 * @param proj Proyección
-	 * @param fName Nombre del fichero ecw
-	 * @throws NotSupportedExtensionException
-	 */
-	public ErmapperProvider(String params) throws NotSupportedExtensionException {
-		super(params);
-		if(params instanceof String) {
-			ErmapperDataParameters p = new ErmapperDataParameters();
-			p.setURI((String)params);
-			super.init(p, null, ToolsLocator.getDynObjectManager()
-					.createDynObject(
-							MetadataLocator.getMetadataManager().getDefinition(
-									DataStore.METADATA_DEFINITION_NAME)));
-			init(p, null);
-		}
-	}
-	
-	public ErmapperProvider(ErmapperDataParameters params,
-			DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
-		super(params, storeServices, ToolsLocator.getDynObjectManager()
-				.createDynObject(
-						MetadataLocator.getMetadataManager().getDefinition(
-								DataStore.METADATA_DEFINITION_NAME)));
-		init(params, storeServices);
-	}
 
-	/**
-	 * Abre el dataset.
-	 * @param proj Proyección
-	 * @param fName Nombre del fichero ecw
-	 * @throws NotSupportedExtensionException
-	 */
-	public void init (AbstractRasterDataParameters params,
-			DataStoreProviderServices storeServices) throws NotSupportedExtensionException {
-		setParam(storeServices, params);
-		if (!((RasterFileStoreParameters)param).getFile().exists() && !((RasterDataParameters)param).getURI().startsWith("ecwp:"))
-			throw new NotSupportedExtensionException("Extension not supported");
+    private static final Logger logger = LoggerFactory.getLogger(ErmapperProvider.class);
+    public static String NAME = "Ermapper Store";
+    public static String DESCRIPTION = "Ermapper Raster file";
+    public static final String METADATA_DEFINITION_NAME = "ErmapperStore";
+    private JNCSFile file = null;
+    protected Transparency fileTransparency = null;
+    private Extent viewRequest = null;
+    private DataStoreColorInterpretation colorInterpr = null;
+    private boolean open = false;
+    protected static String[] formatList = null;
 
-		try {
-			file = new JNCSFile(((RasterDataParameters)param).getURI(), false);
-		} catch (JNCSException e1) {
-			throw new NotSupportedExtensionException("Error loading the ecw file", e1);
-		}
-		
-		/*
-		 * TODO: Leer proyecciones ECW
-		 * 
-		 wktProjection = null;//getWKTFromEcw_csFile(file.projection);
-		if(wktProjection != null && wktProjection != "") {
-			try {
-				proj = RasterLocator.getManager().getCRSUtils().convertWktToIProjection(wktProjection);
-			} catch (Exception e) {
-				logger.info("Error reading WKT from the raster provider", e);
-			}
-		}*/
-		
-		load();
-		bandCount = file.numBands;
+    public static void register() {
+        RasterLocator.getManager().getProviderServices().registerFileProvidersTiled(ErmapperProvider.class);
+        registerFormats();
 
-		int[] dt = new int[bandCount];
-		for (int i = 0; i < bandCount; i++)
-			dt[i] = Buffer.TYPE_BYTE;
-		setDataType(dt);
+        DataManagerProviderServices dataman = (DataManagerProviderServices) DALLocator.getDataManager();
+        if (dataman != null && !dataman.getStoreProviders().contains(NAME)) {
+            dataman.registerStoreProvider(NAME, ErmapperProvider.class, ErmapperDataParameters.class);
+        }
 
-		super.init();
+        if (DALFileLocator.getFilesystemServerExplorerManager() != null)
+            DALFileLocator.getFilesystemServerExplorerManager().registerProvider(NAME, DESCRIPTION,
+                ErmapperFilesystemServerExplorer.class);
 
-		try {
-			loadFromRmf(getRmfBlocksManager());
-		} catch (ParsingException e) {
-			//No lee desde rmf
-		}
-		open = true;
-	}
-	
-	@SuppressWarnings("unused")
-	private String getWKTFromEcw_csFile(String identifier) {
-		File file = new File("./");
-		file = new File(file.getAbsoluteFile() + File.separator + "data" + File.separator + "gdal" + File.separator + "ecw_cs.wkt");
-		if(file.exists()) {
-			FileReader fr = null;
-			BufferedReader br = null;
-			try {
-				fr = new FileReader(file);
-				br = new BufferedReader(fr);
+        dataman.registerStoreFactory(NAME, DefaultStoreFactory.class);
+    }
 
-				String line;
-				while((line = br.readLine()) != null) {
-					if(line.startsWith(identifier + ",")) {
-						int index = line.indexOf(",") + 1;
-						return line.substring(index);
-					}
-				}
-			} catch(Exception e){
-				return null;
-			} finally {
-				try {                   
-					if(fr != null) 
-						fr.close();                   
-				} catch (Exception e2){
-					e2.printStackTrace();
-				}
-			}
-		}
-		return null;
-	}
+    private static void registerFormats() {
+        formatList = new String[] { "ecw", "jp2" };
+        for (int i = 0; i < formatList.length; i++)
+            RasterLocator.getManager().getProviderServices().addFormat(formatList[i], ErmapperProvider.class);
+    }
 
-	public RasterProvider load() {
-		ownTransformation = new AffineTransform(file.cellIncrementX, 0, 0, file.cellIncrementY, file.originX, file.originY);
-		externalTransformation = (AffineTransform) ownTransformation.clone();
-		return this;
-	}
-	
-	public boolean isOpen() {
-		return open;
-	}
+    public String[] getFormatList() {
+        return formatList;
+    }
 
-	public void close() {
-		if(file != null) {
-			open = false;
-			//Cuando se abren varios datastores del mismo fichero y se cierra uno de ellos se cierra la aplicación en el siguiente dibujado
-			//Se debería buscar una solución ya que en los PrepareLayer se abre y cierra para hacer comprobaciones.
-			//file.close(false);
-			file = null;
-		}
-	}
+    /**
+     * Returns true if the extension is supported and false if doesn't
+     *
+     * @param ext
+     * @return
+     */
+    public boolean isExtensionSupported(String ext) {
+        if (ext.indexOf(".") != -1)
+            ext = ext.substring(ext.lastIndexOf(".") + 1, ext.length());
+        for (int i = 0; i < formatList.length; i++) {
+            if (formatList[i].compareTo(ext) == 0)
+                return true;
+        }
+        return false;
+    }
 
-	public Transparency getTransparency() {
-		if(fileTransparency == null)
-			fileTransparency = new DataStoreTransparency(getColorInterpretation());
-		return fileTransparency;
-	}
+    /**
+     * Mandatory constructor to instantiate an empty provider
+     */
+    public ErmapperProvider() {
+    }
 
-	public double getWidth() {
-		return file.width;
-	}
+    /**
+     * Constructor. Abre el dataset.
+     *
+     * @param proj
+     *            Proyección
+     * @param fName
+     *            Nombre del fichero ecw
+     * @throws NotSupportedExtensionException
+     * @throws OpenException
+     * @deprecated use {@link #ErmapperProvider(URI)}, this constructor will be removed in gvSIG 2.5
+     */
+    public ErmapperProvider(String params) throws NotSupportedExtensionException, OpenException {
+        super(params);
+        logger.info("Deprecated use of ErmapperProvider constructor");
+        if (params instanceof String) {
+            ErmapperDataParameters p = new ErmapperDataParameters();
+            try {
+                p.setURI(new URI((String) params));
+            } catch (URISyntaxException e) {
+                throw new OpenException("Can't create URI from" + (String) params, e);
+            }
+            super.init(
+                p,
+                null,
+                ToolsLocator.getDynObjectManager().createDynObject(
+                    MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
+            init(p, null);
+        }
+    }
 
-	public double getHeight() {
-		return file.height;
-	}
+    /**
+     * Constructor. Abre el dataset.
+     *
+     * @param proj
+     *            Proyección
+     * @param uri
+     *            uri del fichero ecw
+     * @throws NotSupportedExtensionException
+     */
+    public ErmapperProvider(URI uri) throws NotSupportedExtensionException {
+        super(uri);
+        ErmapperDataParameters p = new ErmapperDataParameters();
+        p.setURI(uri);
+        super.init(
+            p,
+            null,
+            ToolsLocator.getDynObjectManager().createDynObject(
+                MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
+        init(p, null);
+    }
 
-	public Extent getView() {
-		return viewRequest;
-	}
+    public ErmapperProvider(ErmapperDataParameters params, DataStoreProviderServices storeServices)
+        throws NotSupportedExtensionException {
+        super(params, storeServices, ToolsLocator.getDynObjectManager().createDynObject(
+            MetadataLocator.getMetadataManager().getDefinition(DataStore.METADATA_DEFINITION_NAME)));
+        init(params, storeServices);
+    }
 
-	public void setView(Extent e) {
-		viewRequest = new ExtentImpl(e);
-	}
-	
-	@Override
-	public void loadBuffer(SpiRasterQuery query)
-			throws ProcessInterruptedException, RasterDriverException {
-		setView(transformExternalGeorefToOwnGeoref(query.getAdjustedRequestBoundingBox()));
-		int bufWidth = query.getAdjustedBufWidth();
-		int bufHeight = query.getAdjustedBufHeight();
-		int[] stpBuffer = new int[]{0, 0 , bufWidth, bufHeight};
-		loadBuffer(viewRequest, 
-				bufWidth, 
-				bufHeight, 
-				query.getBufferForProviders(), 
-				query.getBandList(), 
-				stpBuffer, 
-				query.getTaskStatus());
-	}
-	
-	/**
-	 * Converts coordinates from the external transformation to the own transformation.
-	 * This is useful when the user assigns a transformation or the own raster has one
-	 * in the rmf file. Ecw need this function because the data window are requested to 
-	 * the library in world coordinates.
-	 * @param ext
-	 * @return
-	 */
-	private Extent transformExternalGeorefToOwnGeoref(Extent ext) {
-		if(externalTransformation.equals(ownTransformation))
-			return ext;
-		
-		Point2D ul = ext.getUL();
-		Point2D lr = ext.getLR();
-		
-		Point2D p1 = new Point2D.Double();
-		Point2D p2 = new Point2D.Double();
-		
-		try {
-			externalTransformation.inverseTransform(ul, p1);
-		} catch (NoninvertibleTransformException e) {
-			e.printStackTrace();
-		}
-		ownTransformation.transform(p1, p1);
-		
-		try {
-			externalTransformation.inverseTransform(lr, p2);
-		} catch (NoninvertibleTransformException e) {
-			e.printStackTrace();
-		}
-		ownTransformation.transform(p2, p2);
-		
-		return RasterLocator.getManager().getDataStructFactory().createExtent(p1, p2);
-	}
+    /**
+     * Abre el dataset.
+     *
+     * @param proj
+     *            Proyección
+     * @param fName
+     *            Nombre del fichero ecw
+     * @throws NotSupportedExtensionException
+     */
+    public void init(AbstractRasterDataParameters params, DataStoreProviderServices storeServices)
+        throws NotSupportedExtensionException {
+        setParam(storeServices, params);
+        if (!((RasterFileStoreParameters) param).getFile().exists()
+            && !("ecwp".equalsIgnoreCase(((RasterDataParameters) param).getURI().getScheme()))) {
+            throw new NotSupportedExtensionException("Extension not supported");
+        }
 
-	/**
-	 * Carga el buffer con las bandas RGB del raster con los parámetros especificados de extensión
-	 * y tamaño de buffer. El problema de ecw es que solo podemos leer 3 bandas de una vez ya que solo disponemos
-	 * de una llamada readLineRGBA. Para leer más bandas tendremos que hacer multiples llamadas a setView para leer
-	 * 3 cada vez.
-	 *
-	 * Si por ejemplo tenemos un ecw de 6 bandas [0, 1, 2, 3, 4, 5] y queremos cargar un buffer con el siguiente orden
-	 * [0, -, 2, -, 4, -] La variable readBandsFromECW hará la llamada a setView con los valores [0, 2, 4, 0, 0, 0]. La
-	 * función drawRGB será la encargada de hacer el switch para obtener [0, -, 2, -, 4, -].
-	 *
-	 * Bug#1: Si se dispone de un ecw de más de tres bandas podemos llamar a setView con readBandsFromECW con el orden
-	 * que queramos, por ejemplo [3, 2, 5, 1, 0] pero para ecw de 3 bandas la llamada con las bandas cambiadas no
-	 * hace caso. El caso de readBandsFromECW = [2, 0, 1] será tomado siempre como [0, 1, 2].
-	 *
-	 * @param selectedExtent Extensión seleccionada
-	 * @param bufWidth Ancho de buffer
-	 * @param bufHeight Alto de buffer
-	 * @param rasterBuf Buffer de datos
-	 */
-	private void loadBuffer(Extent selectedExtent, 
-			int bufWidth, 
-			int bufHeight, 
-			Buffer rasterBuf, 
-			BandList bandList, 
-			int[] stpBuffer,
-			TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
-		try {
-			RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
-			
-			int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
-			
-			for(int i = 0; i < readBandsFromECW.length; i ++) {
-				readBandsFromECW[i] = i;
-			}
+        try {
+            String stringPath = ((RasterFileStoreParameters) param).getFile().getPath();
+            file = new JNCSFile(stringPath, false);
+        } catch (JNCSException e1) {
+            throw new NotSupportedExtensionException("Error loading the ecw file", e1);
+        }
 
-			if(task.getEvent() != null)
-				task.manageEvent(task.getEvent());
-			if(status != null && status.isCancelled())
-				return;
+        /*
+         * TODO: Leer proyecciones ECW
+         *
+         * wktProjection = null;//getWKTFromEcw_csFile(file.projection);
+         * if(wktProjection != null && wktProjection != "") {
+         * try {
+         * proj =
+         * RasterLocator.getManager().getCRSUtils().convertWktToIProjection
+         * (wktProjection);
+         * } catch (Exception e) {
+         * logger.info("Error reading WKT from the raster provider", e);
+         * }
+         * }
+         */
 
-			if(bufWidth > Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX)))
-				bufWidth = (int)Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX));
-			if(bufHeight > Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY)))
-				bufHeight = (int)Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY));
-			file.setView(file.numBands, readBandsFromECW, selectedExtent.minX(), selectedExtent.maxY(), selectedExtent.maxX(), selectedExtent.minY(), bufWidth, bufHeight);
-			
-			//Escribimos el raster sobre un Buffer
-			int[] pRGBArray = new int[bufWidth];
-			drawRGB2(rasterBuf, pRGBArray, bandList, status);
+        load();
+        bandCount = file.numBands;
 
-		}catch(JNCSInvalidSetViewException exc){
-			throw new RasterDriverException("Error setting coords");
-		}catch (JNCSFileNotOpenException e) {
-			throw new RasterDriverException("Error opening file");
-		}catch (JNCSException ex) {
-			throw new RasterDriverException("Error reading data");
-		}
+        int[] dt = new int[bandCount];
+        for (int i = 0; i < bandCount; i++)
+            dt[i] = Buffer.TYPE_BYTE;
+        setDataType(dt);
 
-	}
-	
-	private void drawRGB2(
-			Buffer rasterBuf, 
-			int[] pRGBArray, 
-			BandList bandList, 
-			TaskStatus status) throws JNCSException, ProcessInterruptedException {
-		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
-		int[] drawableBands = null;
-		
-		for (int line = 0; line < rasterBuf.getHeight(); line++) {
-			try {
-				file.readLineRGBA(pRGBArray);
-				for(int col = 0; col < pRGBArray.length; col ++) {
-					drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 0);
-					if(drawableBands != null) {
-						for (int i = 0; i < drawableBands.length; i++) {
-							if(drawableBands[i] != -1)
-								rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x00ff0000) >> 16));							
-						}
-					}
-					drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 1);
-					if(drawableBands != null) {
-						for (int i = 0; i < drawableBands.length; i++) {
-							if(drawableBands[i] != -1)
-								rasterBuf.setElem(line, col, drawableBands[i], (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
-						}
-					}
-					drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider(), 2);
-					if(drawableBands != null) {
-						for (int i = 0; i < drawableBands.length; i++) {
-							if(drawableBands[i] != -1)
-								rasterBuf.setElem(line, col, drawableBands[i], (byte)(pRGBArray[col] & 0x000000ff));
-						}
-					}
-				}
-			} catch (JNCSException exc) {
-			}
-			if(task.getEvent() != null)
-				task.manageEvent(task.getEvent());
-			if(status != null && status.isCancelled())
-				return;
-		}
-		return;
-	}
+        super.init();
 
-	@SuppressWarnings("unused")
-	private void drawRGB(Buffer rasterBuf, int[] pRGBArray, int[] readBands, BandList bandList, RasterTask task) throws JNCSException, ProcessInterruptedException {
-		int bandR = readBands[0];
-		int bandG = (readBands.length > 1) ? readBands[1] : -1;
-		int bandB = (readBands.length > 2) ? readBands[2] : -1;
+        try {
+            loadFromRmf(getRmfBlocksManager());
+        } catch (ParsingException e) {
+            // No lee desde rmf
+        }
+        open = true;
+    }
 
-		//********* caso especial que resuelve Bug#1 **********************
-		if(file.numBands == 3 && bandList.getDrawableBandsCount() < 3) {
-			for(int i = 0; i < 3; i ++) {
-				int[] b = bandList.getBand(i).getBufferBandListToDraw();
-				if(b != null){
-					bandG = 1; bandR = 0; bandB = 2;
-				}
-			}
-		}
-		if(file.numBands == 3 && bandR == bandG && bandG == bandB) { //caso especial que resuelve Bug#1
-			for(int i = 0; i < 3; i ++) {
-				int[] b = bandList.getBand(i).getBufferBandListToDraw();
-				if(b != null) {
-					if(i == 0) {
-						for (int line = 0; line < rasterBuf.getHeight(); line++) {
-							try {
-								file.readLineRGBA(pRGBArray);
-								for(int col = 0; col < pRGBArray.length; col ++) {
-									rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
-									rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
-									rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
-								}
-							} catch (JNCSException exc) {
-							}
-						}
-						return;
-					}
-					if(i == 1) {
-						for (int line = 0; line < rasterBuf.getHeight(); line++) {
-							try {
-								file.readLineRGBA(pRGBArray);
-								for(int col = 0; col < pRGBArray.length; col ++) {
-									rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
-									rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
-									rasterBuf.setElem(line, col, bandB, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
-								}
-							} catch (JNCSException exc) {
-							}
-						}
-						return;
-					}
-					if(i == 2) {
-						for (int line = 0; line < rasterBuf.getHeight(); line++) {
-							try {
-								file.readLineRGBA(pRGBArray);
-								for(int col = 0; col < pRGBArray.length; col ++) {
-									rasterBuf.setElem(line, col, bandR, (byte)(pRGBArray[col] & 0x000000ff));
-									rasterBuf.setElem(line, col, bandG, (byte)(pRGBArray[col] & 0x000000ff));
-									rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
-								}
-							} catch (JNCSException exc) {
-							}
-						}
-						return;
-					}
-				}
-				if(task.getEvent() != null)
-					task.manageEvent(task.getEvent());
-			}
+    @SuppressWarnings("unused")
+    private String getWKTFromEcw_csFile(String identifier) {
+        File file = new File("./");
+        file =
+            new File(file.getAbsoluteFile() + File.separator + "data" + File.separator + "gdal" + File.separator
+                + "ecw_cs.wkt");
+        if (file.exists()) {
+            FileReader fr = null;
+            BufferedReader br = null;
+            try {
+                fr = new FileReader(file);
+                br = new BufferedReader(fr);
 
-		}
-		//********* END caso especial que resuelve Bug#1 **********************
+                String line;
+                while ((line = br.readLine()) != null) {
+                    if (line.startsWith(identifier + ",")) {
+                        int index = line.indexOf(",") + 1;
+                        return line.substring(index);
+                    }
+                }
+            } catch (Exception e) {
+                return null;
+            } finally {
+                try {
+                    if (fr != null)
+                        fr.close();
+                } catch (Exception e2) {
+                    e2.printStackTrace();
+                }
+            }
+        }
+        return null;
+    }
 
-		if(bandR >= 0 && bandG >= 0 && bandB >= 0) {
-			for (int line = 0; line < rasterBuf.getHeight(); line++) {
-				try {
-					file.readLineRGBA(pRGBArray);
-					for(int col = 0; col < pRGBArray.length; col ++) {
-						rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
-						rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
-						rasterBuf.setElem(line, col, bandB, (byte)(pRGBArray[col] & 0x000000ff));
-					}
-				} catch (JNCSException exc) {
-				}
-			}
-			return;
-		}
+    public RasterProvider load() {
+        ownTransformation =
+            new AffineTransform(file.cellIncrementX, 0, 0, file.cellIncrementY, file.originX, file.originY);
+        externalTransformation = (AffineTransform) ownTransformation.clone();
+        return this;
+    }
 
-		if(task.getEvent() != null)
-			task.manageEvent(task.getEvent());
+    public boolean isOpen() {
+        return open;
+    }
 
-		if(bandR >= 0 && bandG >= 0) {
-			for (int line = 0; line < rasterBuf.getHeight(); line++) {
-				try {
-					file.readLineRGBA(pRGBArray);
-					for(int col = 0; col < pRGBArray.length; col ++) {
-						rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
-						rasterBuf.setElem(line, col, bandG, (byte)((pRGBArray[col] & 0x0000ff00) >> 8));
-					}
-				} catch (JNCSException exc) {
-				}
-			}
-			return;
-		}
+    public void close() {
+        if (file != null) {
+            open = false;
+            // Cuando se abren varios datastores del mismo fichero y se cierra
+            // uno de ellos se cierra la aplicación en el siguiente dibujado
+            // Se debería buscar una solución ya que en los PrepareLayer se abre
+            // y cierra para hacer comprobaciones.
+            // file.close(false);
+            file = null;
+        }
+    }
 
-		if(task.getEvent() != null)
-			task.manageEvent(task.getEvent());
+    public Transparency getTransparency() {
+        if (fileTransparency == null)
+            fileTransparency = new DataStoreTransparency(getColorInterpretation());
+        return fileTransparency;
+    }
 
-		if(bandR >= 0){
-			for (int line = 0; line < rasterBuf.getHeight(); line++) {
-				try {
-					file.readLineRGBA(pRGBArray);
-					for(int col = 0; col < pRGBArray.length; col ++)
-						rasterBuf.setElem(line, col, bandR, (byte)((pRGBArray[col] & 0x00ff0000) >> 16));
-				} catch (JNCSException exc) {
-				}
-			}
-			return;
-		}
+    public double getWidth() {
+        return file.width;
+    }
 
-		if(task.getEvent() != null)
-			task.manageEvent(task.getEvent());
+    public double getHeight() {
+        return file.height;
+    }
 
-	}
+    public Extent getView() {
+        return viewRequest;
+    }
 
-	public void reProject(ICoordTrans rp) {
-	}
+    public void setView(Extent e) {
+        viewRequest = new ExtentImpl(e);
+    }
 
-	public int getBlockSize() {
-		return 0;
-	}
+    @Override
+    public void loadBuffer(SpiRasterQuery query) throws ProcessInterruptedException, RasterDriverException {
+        setView(transformExternalGeorefToOwnGeoref(query.getAdjustedRequestBoundingBox()));
+        int bufWidth = query.getAdjustedBufWidth();
+        int bufHeight = query.getAdjustedBufHeight();
+        int[] stpBuffer = new int[] { 0, 0, bufWidth, bufHeight };
+        loadBuffer(viewRequest, bufWidth, bufHeight, query.getBufferForProviders(), query.getBandList(), stpBuffer,
+            query.getTaskStatus());
+    }
 
-	public Object readCompleteLine(int line, int band) throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
-		if(line < 0 || line >= file.height || band < 0 || band >= getBandCount())
-			throw new InvalidSetViewException("Request out of grid");
+    /**
+     * Converts coordinates from the external transformation to the own
+     * transformation.
+     * This is useful when the user assigns a transformation or the own raster
+     * has one
+     * in the rmf file. Ecw need this function because the data window are
+     * requested to
+     * the library in world coordinates.
+     *
+     * @param ext
+     * @return
+     */
+    private Extent transformExternalGeorefToOwnGeoref(Extent ext) {
+        if (externalTransformation.equals(ownTransformation))
+            return ext;
 
-		Point2D begin = rasterToWorld(new Point2D.Double(0, line));
-		Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
-		int[] readBandsFromECW = new int[file.numBands];
-		if(file.numBands <= 3) {
-			for(int i = 0; i < file.numBands; i++)
-				readBandsFromECW[i] = i;
-		} else {
-			readBandsFromECW[0] = band;
-		}
+        Point2D ul = ext.getUL();
+        Point2D lr = ext.getLR();
 
-		Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
+        Point2D p1 = new Point2D.Double();
+        Point2D p2 = new Point2D.Double();
 
-		try {
-			int[] value = new int[file.width];
-			file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, 1);
-			file.readLineRGBA(value);
+        try {
+            externalTransformation.inverseTransform(ul, p1);
+        } catch (NoninvertibleTransformException e) {
+            e.printStackTrace();
+        }
+        ownTransformation.transform(p1, p1);
 
-			if(file.numBands <= 3) {
-				switch(getDataType()[0]) {
-				case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
-										switch(band) {
-										case 0: for(int i = 0; i < file.width; i ++)
-													b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
-												break;
-										case 1: for(int i = 0; i < file.width; i ++)
-													b[i] = (byte)(((value[i] & 0x0000ff00) >> 8) & 0xff);
-												break;
-										case 2: for(int i = 0; i < file.width; i ++)
-													b[i] = (byte)((value[i] & 0x000000ff) & 0xff);
-												break;
-										}
-										return b;
-				}
-			}else {
-				switch(getDataType()[0]) {
-				case Buffer.TYPE_BYTE: byte[] b = new byte[file.width];
-										for(int i = 0; i < file.width; i ++)
-											b[i] = (byte)(((value[i] & 0x00ff0000) >> 16) & 0xff);
-										break;
-				}
-			}
-			//TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
-		} catch (JNCSFileNotOpenException e1) {
-			throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
-		} catch (JNCSInvalidSetViewException e1) {
-			throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
-		} catch (JNCSException e1) {
-			throw new RasterDriverException("Error la lectura de datos ecw");
-		}
+        try {
+            externalTransformation.inverseTransform(lr, p2);
+        } catch (NoninvertibleTransformException e) {
+            e.printStackTrace();
+        }
+        ownTransformation.transform(p2, p2);
 
-		return null;
-	}
+        return RasterLocator.getManager().getDataStructFactory().createExtent(p1, p2);
+    }
 
-	public Object readBlock(int pos, int blockHeight, double scale) throws InvalidSetViewException, FileNotOpenException, RasterDriverException, ProcessInterruptedException {
-		RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
-		if(pos < 0)
-			throw new InvalidSetViewException("Request out of grid");
+    /**
+     * Carga el buffer con las bandas RGB del raster con los parámetros
+     * especificados de extensión
+     * y tamaño de buffer. El problema de ecw es que solo podemos leer 3 bandas
+     * de una vez ya que solo disponemos
+     * de una llamada readLineRGBA. Para leer más bandas tendremos que hacer
+     * multiples llamadas a setView para leer
+     * 3 cada vez.
+     *
+     * Si por ejemplo tenemos un ecw de 6 bandas [0, 1, 2, 3, 4, 5] y queremos
+     * cargar un buffer con el siguiente orden
+     * [0, -, 2, -, 4, -] La variable readBandsFromECW hará la llamada a setView
+     * con los valores [0, 2, 4, 0, 0, 0]. La
+     * función drawRGB será la encargada de hacer el switch para obtener [0, -,
+     * 2, -, 4, -].
+     *
+     * Bug#1: Si se dispone de un ecw de más de tres bandas podemos llamar a
+     * setView con readBandsFromECW con el orden
+     * que queramos, por ejemplo [3, 2, 5, 1, 0] pero para ecw de 3 bandas la
+     * llamada con las bandas cambiadas no
+     * hace caso. El caso de readBandsFromECW = [2, 0, 1] será tomado siempre
+     * como [0, 1, 2].
+     *
+     * @param selectedExtent
+     *            Extensión seleccionada
+     * @param bufWidth
+     *            Ancho de buffer
+     * @param bufHeight
+     *            Alto de buffer
+     * @param rasterBuf
+     *            Buffer de datos
+     */
+    private void loadBuffer(Extent selectedExtent, int bufWidth, int bufHeight, Buffer rasterBuf, BandList bandList,
+        int[] stpBuffer, TaskStatus status) throws ProcessInterruptedException, RasterDriverException {
+        try {
+            RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
 
-		if((pos + blockHeight) > file.height)
-			blockHeight = Math.abs(file.height - pos);
+            int[] readBandsFromECW = new int[Math.max(file.numBands, 3)];
 
-		Point2D begin = rasterToWorld(new Point2D.Double(0, pos));
-		Point2D end = rasterToWorld(new Point2D.Double(file.width, pos + blockHeight));
-		int[] readBandsFromECW = new int[file.numBands];
+            for (int i = 0; i < readBandsFromECW.length; i++) {
+                readBandsFromECW[i] = i;
+            }
 
-		for(int i = 0; i < file.numBands; i++)
-			readBandsFromECW[i] = i;
+            if (task.getEvent() != null)
+                task.manageEvent(task.getEvent());
+            if (status != null && status.isCancelled())
+                return;
 
-		byte[][][] buf = new byte[file.numBands][blockHeight][file.width];
-		Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
-		e = rasterUtil.calculateAdjustedView(getExtent(), e);
+            if (bufWidth > Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX)))
+                bufWidth = (int) Math.round(Math.abs(selectedExtent.width() / file.cellIncrementX));
+            if (bufHeight > Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY)))
+                bufHeight = (int) Math.round(Math.abs(selectedExtent.height() / file.cellIncrementY));
+            file.setView(file.numBands, readBandsFromECW, selectedExtent.minX(), selectedExtent.maxY(),
+                selectedExtent.maxX(), selectedExtent.minY(), bufWidth, bufHeight);
 
-		try {
-			int[] value = new int[file.width];
-			file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, blockHeight);
+            // Escribimos el raster sobre un Buffer
+            int[] pRGBArray = new int[bufWidth];
+            drawRGB2(rasterBuf, pRGBArray, bandList, status);
 
-			if(file.numBands <= 3) {
-				for (int row = 0; row < blockHeight; row++) {
-					file.readLineRGBA(value);
-					switch(getDataType()[0]) {
-					case Buffer.TYPE_BYTE:
-						if(buf.length >= 3) {
-							for(int col = 0; col < file.width; col ++) {
-								buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
-								buf[1][row][col] = (byte)(((value[col] & 0x0000ff00) >> 8) & 0xff);
-								buf[2][row][col] = (byte)((value[col] & 0x000000ff) & 0xff);
-							}
-						} else { //Si es monobanda solo se usa cualquiera uno de los tres valores
-							for(int col = 0; col < file.width; col ++) {
-								buf[0][row][col] = (byte)(((value[col] & 0x00ff0000) >> 16) & 0xff);
-							}
-						}
-						break;
-					}
-				}
+        } catch (JNCSInvalidSetViewException exc) {
+            throw new RasterDriverException("Error setting coords");
+        } catch (JNCSFileNotOpenException e) {
+            throw new RasterDriverException("Error opening file");
+        } catch (JNCSException ex) {
+            throw new RasterDriverException("Error reading data");
+        }
 
-				if(task.getEvent() != null)
-					task.manageEvent(task.getEvent());
+    }
 
-			} else {
-				//TODO: FUNCIONALIDAD: file.numBands > 3
-			}
+    private void drawRGB2(Buffer rasterBuf, int[] pRGBArray, BandList bandList, TaskStatus status)
+        throws JNCSException, ProcessInterruptedException {
+        RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
+        int[] drawableBands = null;
 
-			//TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
-		} catch (JNCSFileNotOpenException e1) {
-			throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
-		} catch (JNCSInvalidSetViewException e1) {
-			throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
-		} catch (JNCSException e1) {
-			throw new RasterDriverException("Error la lectura de datos ecw");
-		}
+        for (int line = 0; line < rasterBuf.getHeight(); line++) {
+            try {
+                file.readLineRGBA(pRGBArray);
+                for (int col = 0; col < pRGBArray.length; col++) {
+                    drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider().getPath(), 0);
+                    if (drawableBands != null) {
+                        for (int i = 0; i < drawableBands.length; i++) {
+                            if (drawableBands[i] != -1)
+                                rasterBuf.setElem(line, col, drawableBands[i],
+                                    (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
+                        }
+                    }
+                    drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider().getPath(), 1);
+                    if (drawableBands != null) {
+                        for (int i = 0; i < drawableBands.length; i++) {
+                            if (drawableBands[i] != -1)
+                                rasterBuf.setElem(line, col, drawableBands[i],
+                                    (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
+                        }
+                    }
+                    drawableBands = bandList.getBufferBandToDraw(getURIOfFirstProvider().getPath(), 2);
+                    if (drawableBands != null) {
+                        for (int i = 0; i < drawableBands.length; i++) {
+                            if (drawableBands[i] != -1)
+                                rasterBuf.setElem(line, col, drawableBands[i], (byte) (pRGBArray[col] & 0x000000ff));
+                        }
+                    }
+                }
+            } catch (JNCSException exc) {
+            }
+            if (task.getEvent() != null)
+                task.manageEvent(task.getEvent());
+            if (status != null && status.isCancelled())
+                return;
+        }
+        return;
+    }
 
-		return buf;
-	}
+    @SuppressWarnings("unused")
+    private void drawRGB(Buffer rasterBuf, int[] pRGBArray, int[] readBands, BandList bandList, RasterTask task)
+        throws JNCSException, ProcessInterruptedException {
+        int bandR = readBands[0];
+        int bandG = (readBands.length > 1) ? readBands[1] : -1;
+        int bandB = (readBands.length > 2) ? readBands[2] : -1;
 
-	public Object getData(int x, int y, int band)throws InvalidSetViewException, FileNotOpenException, RasterDriverException {
-		if(x < 0 || y < 0 || x >= file.width || y >= file.height)
-			throw new InvalidSetViewException("Request out of grid");
+        // ********* caso especial que resuelve Bug#1 **********************
+        if (file.numBands == 3 && bandList.getDrawableBandsCount() < 3) {
+            for (int i = 0; i < 3; i++) {
+                int[] b = bandList.getBand(i).getBufferBandListToDraw();
+                if (b != null) {
+                    bandG = 1;
+                    bandR = 0;
+                    bandB = 2;
+                }
+            }
+        }
+        if (file.numBands == 3 && bandR == bandG && bandG == bandB) { // caso
+                                                                      // especial
+                                                                      // que
+                                                                      // resuelve
+                                                                      // Bug#1
+            for (int i = 0; i < 3; i++) {
+                int[] b = bandList.getBand(i).getBufferBandListToDraw();
+                if (b != null) {
+                    if (i == 0) {
+                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
+                            try {
+                                file.readLineRGBA(pRGBArray);
+                                for (int col = 0; col < pRGBArray.length; col++) {
+                                    rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
+                                    rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
+                                    rasterBuf.setElem(line, col, bandB, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
+                                }
+                            } catch (JNCSException exc) {
+                            }
+                        }
+                        return;
+                    }
+                    if (i == 1) {
+                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
+                            try {
+                                file.readLineRGBA(pRGBArray);
+                                for (int col = 0; col < pRGBArray.length; col++) {
+                                    rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
+                                    rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
+                                    rasterBuf.setElem(line, col, bandB, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
+                                }
+                            } catch (JNCSException exc) {
+                            }
+                        }
+                        return;
+                    }
+                    if (i == 2) {
+                        for (int line = 0; line < rasterBuf.getHeight(); line++) {
+                            try {
+                                file.readLineRGBA(pRGBArray);
+                                for (int col = 0; col < pRGBArray.length; col++) {
+                                    rasterBuf.setElem(line, col, bandR, (byte) (pRGBArray[col] & 0x000000ff));
+                                    rasterBuf.setElem(line, col, bandG, (byte) (pRGBArray[col] & 0x000000ff));
+                                    rasterBuf.setElem(line, col, bandB, (byte) (pRGBArray[col] & 0x000000ff));
+                                }
+                            } catch (JNCSException exc) {
+                            }
+                        }
+                        return;
+                    }
+                }
+                if (task.getEvent() != null)
+                    task.manageEvent(task.getEvent());
+            }
 
-		Point2D begin = new Point2D.Double(x, y);
-		Point2D end = new Point2D.Double(x + 1, y + 1);
+        }
+        // ********* END caso especial que resuelve Bug#1 **********************
 
-		ownTransformation.transform(begin, begin);
-		ownTransformation.transform(end, end);
+        if (bandR >= 0 && bandG >= 0 && bandB >= 0) {
+            for (int line = 0; line < rasterBuf.getHeight(); line++) {
+                try {
+                    file.readLineRGBA(pRGBArray);
+                    for (int col = 0; col < pRGBArray.length; col++) {
+                        rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
+                        rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
+                        rasterBuf.setElem(line, col, bandB, (byte) (pRGBArray[col] & 0x000000ff));
+                    }
+                } catch (JNCSException exc) {
+                }
+            }
+            return;
+        }
 
-		int[] readBandsFromECW = new int[file.numBands];
-		if(file.numBands <= 3){
-			for(int i = 0; i < file.numBands; i++)
-				readBandsFromECW[i] = i;
-		}else{
-			readBandsFromECW[0] = band;
-		}
+        if (task.getEvent() != null)
+            task.manageEvent(task.getEvent());
 
-		Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
-		try {
-			int[] value = new int[1];
-			file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), 1, 1);
-			file.readLineRGBA(value);
-			if(file.numBands <= 3){
-				switch(band){
-				case 0: return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
-				case 1: return new Integer((((value[0] & 0x0000ff00) >> 8) & 0xffffffff));
-				case 2: return new Integer((((value[0] & 0x000000ff)) & 0xffffffff));
-				}
-			}
-			return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
-		} catch (JNCSFileNotOpenException e1) {
-			throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
-		} catch (JNCSInvalidSetViewException e1) {
-			throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
-		} catch (JNCSException e1) {
-			throw new RasterDriverException("Error reading ecw data");
-		}
-	}
+        if (bandR >= 0 && bandG >= 0) {
+            for (int line = 0; line < rasterBuf.getHeight(); line++) {
+                try {
+                    file.readLineRGBA(pRGBArray);
+                    for (int col = 0; col < pRGBArray.length; col++) {
+                        rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
+                        rasterBuf.setElem(line, col, bandG, (byte) ((pRGBArray[col] & 0x0000ff00) >> 8));
+                    }
+                } catch (JNCSException exc) {
+                }
+            }
+            return;
+        }
 
-	public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
-	}
+        if (task.getEvent() != null)
+            task.manageEvent(task.getEvent());
 
-	public void refreshUpdate(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
-	}
+        if (bandR >= 0) {
+            for (int line = 0; line < rasterBuf.getHeight(); line++) {
+                try {
+                    file.readLineRGBA(pRGBArray);
+                    for (int col = 0; col < pRGBArray.length; col++)
+                        rasterBuf.setElem(line, col, bandR, (byte) ((pRGBArray[col] & 0x00ff0000) >> 16));
+                } catch (JNCSException exc) {
+                }
+            }
+            return;
+        }
 
-	public DataStoreColorInterpretation getColorInterpretation() {
-		if(colorInterpr == null) {
-			colorInterpr = new DataStoreColorInterpretation();
-			colorInterpr.initColorInterpretation(getBandCount());
-			if(getBandCount() == 1)
-				colorInterpr = DataStoreColorInterpretation.createGrayInterpretation();
-			if(getBandCount() == 3) {
-				colorInterpr =  DataStoreColorInterpretation.createRGBInterpretation();
-			}
-			if(getBandCount() >= 4) {
-				colorInterpr = DataStoreColorInterpretation.createRGBAInterpretation();
-			}
-		}
-		return colorInterpr;
-	}
+        if (task.getEvent() != null)
+            task.manageEvent(task.getEvent());
 
-	public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
-		if(band >= getBandCount())
-			throw new BandAccessException("Wrong band");
-		return 0;
-	}
+    }
 
-	public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
-		if (band >= getBandCount())
-			throw new BandAccessException("Wrong band");
-		return 0;
-	}
+    public void reProject(ICoordTrans rp) {
+    }
 
-	public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
-		if (band >= getBandCount())
-			throw new BandAccessException("Wrong band");
-		return 0;
-	}
+    public int getBlockSize() {
+        return 0;
+    }
 
-	public boolean isOverviewsSupported() {
-		return false;
-	}
+    public Object readCompleteLine(int line, int band) throws InvalidSetViewException, FileNotOpenException,
+        RasterDriverException {
+        if (line < 0 || line >= file.height || band < 0 || band >= getBandCount())
+            throw new InvalidSetViewException("Request out of grid");
 
-	
-	public String getStringProjection() throws RasterDriverException{
-		return file.projection;
-	}
+        Point2D begin = rasterToWorld(new Point2D.Double(0, line));
+        Point2D end = rasterToWorld(new Point2D.Double(file.width, line + 1));
+        int[] readBandsFromECW = new int[file.numBands];
+        if (file.numBands <= 3) {
+            for (int i = 0; i < file.numBands; i++)
+                readBandsFromECW[i] = i;
+        } else {
+            readBandsFromECW[0] = band;
+        }
 
-	public String getWktProjection() {
-		return null;
-	}
-	
-	public String getProviderName() {
-		return NAME;
-	}
-	
-	public void setStatus(RasterProvider provider) {
-		if(provider instanceof ErmapperProvider) {
-			//Not implemented yet
-		}
-	}
-	
-	public boolean isSupersamplingSupported() {
-		return false;
-	}
-	
-	public TileServer getTileServer() {
-		if(tileServer == null) {
-			DefaultRasterStore store = new DefaultRasterStore();
-			store.setProvider(this);
-			tileServer = new FileTileServer(store);
-		}
-		return tileServer;
-	}
-}
\ No newline at end of file
+        Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
+
+        try {
+            int[] value = new int[file.width];
+            file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width, 1);
+            file.readLineRGBA(value);
+
+            if (file.numBands <= 3) {
+                switch (getDataType()[0]) {
+                case Buffer.TYPE_BYTE:
+                    byte[] b = new byte[file.width];
+                    switch (band) {
+                    case 0:
+                        for (int i = 0; i < file.width; i++)
+                            b[i] = (byte) (((value[i] & 0x00ff0000) >> 16) & 0xff);
+                        break;
+                    case 1:
+                        for (int i = 0; i < file.width; i++)
+                            b[i] = (byte) (((value[i] & 0x0000ff00) >> 8) & 0xff);
+                        break;
+                    case 2:
+                        for (int i = 0; i < file.width; i++)
+                            b[i] = (byte) ((value[i] & 0x000000ff) & 0xff);
+                        break;
+                    }
+                    return b;
+                }
+            } else {
+                switch (getDataType()[0]) {
+                case Buffer.TYPE_BYTE:
+                    byte[] b = new byte[file.width];
+                    for (int i = 0; i < file.width; i++)
+                        b[i] = (byte) (((value[i] & 0x00ff0000) >> 16) & 0xff);
+                    break;
+                }
+            }
+            // TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
+        } catch (JNCSFileNotOpenException e1) {
+            throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
+        } catch (JNCSInvalidSetViewException e1) {
+            throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
+        } catch (JNCSException e1) {
+            throw new RasterDriverException("Error la lectura de datos ecw");
+        }
+
+        return null;
+    }
+
+    public Object readBlock(int pos, int blockHeight, double scale) throws InvalidSetViewException,
+        FileNotOpenException, RasterDriverException, ProcessInterruptedException {
+        RasterTask task = RasterTaskQueue.get(Thread.currentThread().getId() + "");
+        if (pos < 0)
+            throw new InvalidSetViewException("Request out of grid");
+
+        if ((pos + blockHeight) > file.height)
+            blockHeight = Math.abs(file.height - pos);
+
+        Point2D begin = rasterToWorld(new Point2D.Double(0, pos));
+        Point2D end = rasterToWorld(new Point2D.Double(file.width, pos + blockHeight));
+        int[] readBandsFromECW = new int[file.numBands];
+
+        for (int i = 0; i < file.numBands; i++)
+            readBandsFromECW[i] = i;
+
+        byte[][][] buf = new byte[file.numBands][blockHeight][file.width];
+        Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
+        e = rasterUtil.calculateAdjustedView(getExtent(), e);
+
+        try {
+            int[] value = new int[file.width];
+            file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), file.width,
+                blockHeight);
+
+            if (file.numBands <= 3) {
+                for (int row = 0; row < blockHeight; row++) {
+                    file.readLineRGBA(value);
+                    switch (getDataType()[0]) {
+                    case Buffer.TYPE_BYTE:
+                        if (buf.length >= 3) {
+                            for (int col = 0; col < file.width; col++) {
+                                buf[0][row][col] = (byte) (((value[col] & 0x00ff0000) >> 16) & 0xff);
+                                buf[1][row][col] = (byte) (((value[col] & 0x0000ff00) >> 8) & 0xff);
+                                buf[2][row][col] = (byte) ((value[col] & 0x000000ff) & 0xff);
+                            }
+                        } else { // Si es monobanda solo se usa cualquiera uno
+                                 // de los tres valores
+                            for (int col = 0; col < file.width; col++) {
+                                buf[0][row][col] = (byte) (((value[col] & 0x00ff0000) >> 16) & 0xff);
+                            }
+                        }
+                        break;
+                    }
+                }
+
+                if (task.getEvent() != null)
+                    task.manageEvent(task.getEvent());
+
+            } else {
+                // TODO: FUNCIONALIDAD: file.numBands > 3
+            }
+
+            // TODO: FUNCIONALIDAD: Ecw con otro tipo de dato != Byte
+        } catch (JNCSFileNotOpenException e1) {
+            throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
+        } catch (JNCSInvalidSetViewException e1) {
+            throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
+        } catch (JNCSException e1) {
+            throw new RasterDriverException("Error la lectura de datos ecw");
+        }
+
+        return buf;
+    }
+
+    public Object getData(int x, int y, int band) throws InvalidSetViewException, FileNotOpenException,
+        RasterDriverException {
+        if (x < 0 || y < 0 || x >= file.width || y >= file.height)
+            throw new InvalidSetViewException("Request out of grid");
+
+        Point2D begin = new Point2D.Double(x, y);
+        Point2D end = new Point2D.Double(x + 1, y + 1);
+
+        ownTransformation.transform(begin, begin);
+        ownTransformation.transform(end, end);
+
+        int[] readBandsFromECW = new int[file.numBands];
+        if (file.numBands <= 3) {
+            for (int i = 0; i < file.numBands; i++)
+                readBandsFromECW[i] = i;
+        } else {
+            readBandsFromECW[0] = band;
+        }
+
+        Extent e = new ExtentImpl(begin.getX(), begin.getY(), end.getX(), end.getY());
+        try {
+            int[] value = new int[1];
+            file.setView(file.numBands, readBandsFromECW, e.minX(), e.maxY(), e.maxX(), e.minY(), 1, 1);
+            file.readLineRGBA(value);
+            if (file.numBands <= 3) {
+                switch (band) {
+                case 0:
+                    return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
+                case 1:
+                    return new Integer((((value[0] & 0x0000ff00) >> 8) & 0xffffffff));
+                case 2:
+                    return new Integer((((value[0] & 0x000000ff)) & 0xffffffff));
+                }
+            }
+            return new Integer((((value[0] & 0x00ff0000) >> 16) & 0xffffffff));
+        } catch (JNCSFileNotOpenException e1) {
+            throw new FileNotOpenException("Error en jecw: JNCSFileNotOpenException");
+        } catch (JNCSInvalidSetViewException e1) {
+            throw new FileNotOpenException("Error en jecw: JNCSInvalidSetViewException");
+        } catch (JNCSException e1) {
+            throw new RasterDriverException("Error reading ecw data");
+        }
+    }
+
+    public void refreshUpdate(int arg0, int arg1, double arg2, double arg3, double arg4, double arg5) {
+    }
+
+    public void refreshUpdate(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) {
+    }
+
+    public DataStoreColorInterpretation getColorInterpretation() {
+        if (colorInterpr == null) {
+            colorInterpr = new DataStoreColorInterpretation();
+            colorInterpr.initColorInterpretation(getBandCount());
+            if (getBandCount() == 1)
+                colorInterpr = DataStoreColorInterpretation.createGrayInterpretation();
+            if (getBandCount() == 3) {
+                colorInterpr = DataStoreColorInterpretation.createRGBInterpretation();
+            }
+            if (getBandCount() >= 4) {
+                colorInterpr = DataStoreColorInterpretation.createRGBAInterpretation();
+            }
+        }
+        return colorInterpr;
+    }
+
+    public int getOverviewCount(int band) throws BandAccessException, RasterDriverException {
+        if (band >= getBandCount())
+            throw new BandAccessException("Wrong band");
+        return 0;
+    }
+
+    public int getOverviewWidth(int band, int overview) throws BandAccessException, RasterDriverException {
+        if (band >= getBandCount())
+            throw new BandAccessException("Wrong band");
+        return 0;
+    }
+
+    public int getOverviewHeight(int band, int overview) throws BandAccessException, RasterDriverException {
+        if (band >= getBandCount())
+            throw new BandAccessException("Wrong band");
+        return 0;
+    }
+
+    public boolean isOverviewsSupported() {
+        return false;
+    }
+
+    public String getStringProjection() throws RasterDriverException {
+        return file.projection;
+    }
+
+    public String getWktProjection() {
+        return null;
+    }
+
+    public String getProviderName() {
+        return NAME;
+    }
+
+    public void setStatus(RasterProvider provider) {
+        if (provider instanceof ErmapperProvider) {
+            // Not implemented yet
+        }
+    }
+
+    public boolean isSupersamplingSupported() {
+        return false;
+    }
+
+    public TileServer getTileServer() {
+        if (tileServer == null) {
+            DefaultRasterStore store = new DefaultRasterStore();
+            store.setProvider(this);
+            tileServer = new FileTileServer(store);
+        }
+        return tileServer;
+    }
+
+    public void addFile(File file) throws InvalidSourceException {
+        // Do nothing
+    }
+
+    public void removeFile(File file) {
+        // Do nothing
+    }
+
+}
