/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package skyview.process.imagefinder;

import skyview.survey.Image;

/**
 * 
 * @author tmcglynn
 */
public class LocalBorder extends Border {
    
    /** Find the best image for each output pixel.
     * 
     * 
     * 
     * @param input An array of images that may be sampled to get the output image.
     * @param output The output image.  In this routine we are interested in its
     *        geometry, not its data.
     * @return An index array which for each pixel in the output image
     *         gives the best image to sample.  Note that this has dimension
     *         int[nx*ny] where nx changes most rapidly.  The values of the index
     *         array can be:
     *         <ul>
     *           <li>  &gt;= 0: The pixel is best indexed with the given image.
     *           <li>  -1: [internal] The best image for this pixel has not yet been determined.
     *           <li>  -2: This pixel is not on any of the input images.
     *           <li>  -3: This pixel does not represent a physical coordinate.
     *           <li>  -4: [in other methods] this pixel has already been processed.
     *         </ul>
     */
    public int[] findImages(Image[] input, Image output) {
        // Don't allow any non-local images.
        System.err.println("Initial request");
        int[] data = super.findImages(input, output);
        int loopCount = 1;
        while (unvalidatedImages(data, input)) {
            System.err.println("Running findimages for loop:"+loopCount);
            data = super.findImages(input, output);
            loopCount += 1;
        }
        return data;
    }
    private boolean unvalidatedImages(int[] data, Image[] input) {
        boolean unvalidated = false;
        boolean[] done = new boolean[input.length];
        for (int i=0; i<data.length; i += 1) {
            int img = data[i];
            if (img >= 0 && !done[img]) {
                boolean isValid = input[img].valid();
                if (!isValid) {
                    unvalidated = true;
                    System.err.println("Validating:"+img);
                    input[img].validate();
                    done[img] = true;
                }
            }
        }
        return unvalidated;
    }     
}