/* Generated by Together */
package org.mbari.seepsearch.tools;

import org.mbari.seepsearch.grid.*;
import java.io.*;

public class BufferGrid {
    public static void main(String[] args) {

		// args[0] = ingrid
        // args[1] = outgid
        // args[2] = bufferSize
        // args[3] = minAcceptableZ

        int bufferSize = Integer.parseInt(args[2]);
        int minAcceptableZ = Integer.parseInt(args[3]);

        AsciiRasterGridReader gridFile = new AsciiRasterGridReader(args[0]);
		try {
			gridFile.read();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
        catch (GridException e) {
			e.printStackTrace();
        }

        RasterGrid grid = gridFile.getGrid();
        double[] x = grid.getX();
        double[] y = grid.getY();
        float[][] z = grid.getZ();

        int numRows = y.length;
        int numCols = x.length;

		AsciiNullGridReader newGridFile = new AsciiNullGridReader(args[0]);
		try {
			newGridFile.read();
        }
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (GridException e) {
			e.printStackTrace();
        }

        RasterGrid newGrid = newGridFile.getGrid();
		float[][] newZ = newGrid.getZ();

		for (int row = 0;row < numRows ;row++) {
            for (int col = 0; col < numCols; col++) {
				if (z[row][col] >= minAcceptableZ) {
					for(int r = -bufferSize; r <= bufferSize; r++) {
						int ir = row + r;
                        if (ir >= 0 && ir < numRows) {
							for(int c = -bufferSize; c <= bufferSize; c++) {
								int ic = col + c;
                                if (ic >= 0 && ic < numCols) {
									newZ[ir][ic] = z[row][col] + newZ[ir][ic];
                                }
							}
                        }
                    }
                }
            }
        }

/*        try {
            newGrid.setZ(newZ);
        }
        catch (GridException e) {
            e.printStackTrace();   
        }*/
        
        AsciiRasterGridWriter writer = new AsciiRasterGridWriter(args[1]);
		try {
			writer.write(newGrid, 0, 8);
        }
		catch (IOException e) {
			e.printStackTrace();
		}

    } // end main
}


/*


                        if ir >= 0 and ir < numRows and ic >= 0 and ic < numCols:
                            newZ[ir][ic] = z[row][col] + newZ[ir][ic]
                        
    writer = AsciiRasterGridWriter(newGridFilename)
    newGrid.setZ(newZ)
    writer.write(newGrid, 0, 8)
 */