/*
 * $Id: Ex2.java,v 1.1.1.1 2005/09/23 20:24:11 norman Exp $
 *
 * Copyright (c) 2005 by Brockmann Consult GmbH. All right reserved.
 * http://www.brockmann-consult.de
 */
package org.esa.beam.basics;

import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.util.logging.BeamLogManager;

import java.io.IOException;

/**
 * This exercise shows how to
 * <ol>
 * <li>obtain a <code>Product</code> object from a file path</li>
 * <li>use the <code>ProductIO</code> class to open a data product and perform naive I/O error handling</li>
 * <li>query the <code>Product</code>'s bands</li>
 * <li>get a specific band</li>
 * <li>read a rectangular region of pixels from this band</li>
 * <li>dump pixels values to the console</li>
 * <li>close product I/O and dispose the product object</li>
 * </ol>
 */
public class Ex2 {
    /**
     * The program entry point.
     *
     * @param args must be of length 1. <code>args[0]</code> contains the product file path
     */
    public static void main(String[] args) {
        // get rid of the console logging
        BeamLogManager.removeRootLoggerHandlers();

        String filePath = args[0];
        Product product = Ex1.readProduct(filePath);

//        // query the product's bands
//        Band[] bands = product.getBands();
//        for (int i = 0; i < bands.length; i++) {
//            Band band = bands[i];
//            System.out.printf("bands[%d] = %s\n", i, band);
//        }

        // get a specific band
        String bandName = "reflec_6";
        Band band = product.getBand(bandName);
        if (band == null) {
            System.err.printf("Error: band '%s' not found in product '%s'\n",
                              bandName, product.getName());
            System.exit(1);
        }

        // read a rectangular region of pixels from this band
        int x0 = 200;
        int y0 = 40;
        int w = 4;
        int h = 2;
        float[] pixels = new float[w * h];
        try {
            band.readPixels(x0, y0, w, h, pixels);
        } catch (IOException e) {
            System.err.printf("Error: failed to read from band '%s'\n", band.getName());
            System.exit(1);
        }

        // dump pixels values to the console
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                // compute buffer index
                int i = y * w + x;
                // get pixel value
                float pixel = pixels[i];
                // output pixel value
                System.out.printf("%s(x=%d, y=%d) = %f\n",
                                  band.getName(), x0 + x, y0 + y, pixel);
            }
        }

        // close product I/O and dispose the product object
        product.dispose();
    }
}




