package skyview.process;

import java.util.HashMap;
import java.util.Map;
import skyview.survey.Image;
import skyview.survey.Subset;
import skyview.geometry.Sampler;
import skyview.geometry.DepthSampler;
import skyview.geometry.Converter;
import skyview.geometry.TransformationException;
import skyview.executive.Settings;

import nom.tam.fits.Header;

/** A mosaicker is an object which creates
 *  a new image from a set of input images.
 */
public class SubsetMosaicker extends Mosaicker {
    
    /** Get the name of this component */
    public String getName() {
	return "SubsetMosaicker";
    }
    
    private int tileX = 1024;
    private int tileY = 1024;
    
    /** Get a description of this component */
    public String getDescription() {
	return "Mosaic in subsets";
    }
    
    /** Populate the pixel values of the output mosaic.  Note that
     *  the output image is assumed to be created prior
     *  to the mosaic call since its WCS will have been
     *  used extensively.
     *  This version splits the output image into a bunch of subimages and
     *  generates the output image in pieces.
     *  @param input  An array of input images.
     *  @param output The image whose data is to be filled.
     *  @param osource An integer array giving the source image to be used
     *                for the output pixels.  Note that depending upon
     *                the mosaicker used, source may be dimensioned as either
     *                nx*ny or (nx+1)*(ny+1).
     *  @param samp   The sampler to be used to sample the input images.
     *  @param dSampler  The sampler (if any) in the energy dimension.
     */
    public void process(Image[] input, Image output, int[] osource, 
		        Sampler samp, DepthSampler dSampler)  {
	
	
	try {
	    tileX = Integer.parseInt(Settings.get("SubsetX", "1024"));
	    tileY = Integer.parseInt(Settings.get("SubsetY", "1024"));
	} catch (Exception e) {
	    System.err.println("Ignored invalid Subset[XY] values");	    
	}
	
	Image[] subsets;
	int[][] osrcs;
        
	try {
	    subsets = Subset.split(output, tileX, tileY);
	    osrcs   = Subset.split(output, osource, tileX, tileY);
	} catch (Exception e) {
	    
	    System.err.println("SubsetMosaicker unable to split tiles. Error: "+e);
	    e.printStackTrace(System.err);
	    System.err.println("Proceeding without tiling");
	    subsets = new Image[]{output};
	    
	    osrcs = new int[1][];
	    osrcs[0] = osource;
	}
	
        Map<String, Integer> usedImageCounts = new HashMap<String,Integer>();
	for (int i=0; i<subsets.length; i += 1) {
            
	    System.err.println("SubsetMosaicker processing subset: " + i);
	    super.process(input, subsets[i], osrcs[i], samp, dSampler);
            // Note that the process method in the main Mosaicker will
            // update the _usedImages setting each time it is called. 
            
	}	
    }    
}
    
