/*
 * $Id: Ex3b.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.dataio.ProductWriter;
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 is based on {@link org.esa.beam.basics.Ex3a} and additionally shows how to
 * <ol>
 * <li>write a product "skeleton" excluding pixel data in BEAM-DIMAP format</li>
 * <li>compute new pixel values and write band data line-wise</li>
 * <li>close product I/O and dispose the product object</li>
 * </ol>
 */
public class Ex3b {
    /**
     * 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_ex3b", "EX3B", w, h);

        // create a new band and add it to the product
        Band band = new Band("band_ex3b", ProductData.TYPE_FLOAT32, w, h);
        product.addBand(band);

        // write the product "skeleton" excluding pixel data in BEAM-DIMAP format
        String filePath = product.getName() + ".dim";
        String formatName = "BEAM-DIMAP";
        ProductWriter productWriter = ProductIO.getProductWriter(formatName);
        product.setProductWriter(productWriter);
        try {
            productWriter.writeProductNodes(product, filePath);
        } catch (IOException e) {
            System.err.printf("Error: failed to write product to %s: %s\n", filePath, e.getMessage());
            System.exit(1);
        }

        float[] pixels = new float[w];
        try {
            for (int y = 0; y < h; y++) {
                for (int x = 0; x < w; x++) {
                    pixels[x] = Ex3a.computePixelValue(x, y, w, h);
                }
                band.writePixels(0, y, w, 1, pixels);
            }
        } catch (IOException e) {
            System.err.printf("Error: failed to write pixel data to %s: %s\n", filePath, e.getMessage());
            System.exit(1);
        }

        product.dispose();
    }
}

