/*
 * $Id: Ex3a.java,v 1.2 2005/09/25 21:31:48 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.dataio.ProductIO;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.util.logging.BeamLogManager;

import java.io.IOException;

/**
 * This exercise shows how to
 * <ol>
 * <li>create a new <code>Product</code> object</li>
 * <li>create a new band and add it to the product</li>
 * <li>set the band's raster data with computed pixel values</li>
 * <li>write the data product as BEAM-DIMAP format</li>
 * <li>close product I/O and dispose the product object</li>
 * </ol>
 */
public class Ex3a {
    /**
     * The program entry point.
     *
     * @param args not used
     */
    public static void main(String[] args) {
        // get rid of the console logging
        BeamLogManager.removeRootLoggerHandlers();

        // create a new product object
        int w = 512;
        int h = 512;
        Product product = new Product("product_ex3a", "EX3A", w, h);

        // create a new band and add it to the product
        Band band = new Band("band_ex3a", ProductData.TYPE_FLOAT32, w, h);
        product.addBand(band);

        // compute new pixel values
        float[] pixels = new float[w * h];
        for (int y = 0; y < h; y++) {
            for (int x = 0; x < w; x++) {
                // compute buffer index
                int i = y * w + x;
                // compute and assign the output pixel value
                pixels[i] = computePixelValue(x, y, w, h);
            }
        }

        // set the band's raster data with computed pixel values
        ProductData rasterData = ProductData.createInstance(pixels);
        band.setRasterData(rasterData);

        // write the data product as BEAM-DIMAP format
        String filePath = product.getName() + ".dim";
        String formatName = "BEAM-DIMAP";
        try {
            ProductIO.writeProduct(product, filePath, formatName);
        } catch (IOException e) {
            System.err.printf("Error: failed to write product to %s: %s\n", filePath, e.getMessage());
            System.exit(1);
        }

        // close product I/O and dispose the product object
        product.dispose();
    }

    public static float computePixelValue(int x, int y, int w, int h) {
        return (float) Math.sin(15.0 * (x * x + y * y) / w / h);
    }
}

