/*
 * This class will split a HEALPix image.
 */
package skyview.survey;

import java.io.FileOutputStream;
import nom.tam.fits.BasicHDU;
import nom.tam.fits.BinaryTable;
import nom.tam.fits.Fits;
import nom.tam.fits.Header;
import nom.tam.util.BufferedDataOutputStream;

/**
 *
 * @author tmcglynn
 */
public class HealPixSplitter {
    
    public static void main(String[] args) throws Exception {
        String infile = args[0];
        String outstem = args[1];
        int pow = 0;
        if (args.length > 2) {
            pow = Integer.parseInt(args[2]);
        }
        outstem = outstem+"_"+pow;
        
        int tiles = 12*(int)Math.pow(2,2*pow);
        System.out.println("Breaking single HEALPix file "+infile+" into "+tiles+" tiles "+outstem+".n");
        System.out.println("Header information saved as .hdr0 and .hdr1");
        
        Fits f = new Fits(infile);
        BufferedDataOutputStream bds = new BufferedDataOutputStream(new FileOutputStream(outstem+".hdr0"));
        BasicHDU hdu = f.readHDU();
        hdu.getHeader().write(bds);
        bds.close();
        
        hdu = f.readHDU();
        Header h = hdu.getHeader();
        int npix = h.getIntValue("NAXIS2");
        int len  = h.getIntValue("NAXIS1");
        
        System.out.println("Number of pixels: "+npix);
        System.out.println("Number of bytes per pixel:"+len);
        System.out.println("Tile size in bytes:"+ (long)npix*len/tiles);
        
        
        bds = new BufferedDataOutputStream(new FileOutputStream(outstem+".hdr1"));
        h.write(bds);
        bds.close();
        
        int szTile = npix/tiles;
        

        int offset = 0;        
        for (int i=0; i<tiles; i += 1) {
            System.out.println("   Processing tile "+i);
            bds = new BufferedDataOutputStream(new FileOutputStream(outstem+"."+i));
            BinaryTable bt = (BinaryTable) hdu.getData();
            for (int p=0; p<szTile; p += 1) {
                Object[] o = bt.getRow(offset);
                bds.writeArray(o);
                offset += 1;
            }
            bds.close();
        }
    }
}
