package crushtools;

import java.io.FileOutputStream;
import java.io.PrintWriter;


import jnum.Util;
import jnum.math.Vector2D;
import nom.tam.fits.BasicHDU;
import nom.tam.fits.ImageHDU;
import nom.tam.fits.Fits;

public class ChopNodReg {
    double[][] Q, U, F;
    String fileName;
    int sizeX, sizeY;
      
    public static void main(String[] args) {
        ChopNodReg cp = new ChopNodReg();
        
        try {
            cp.read(args[0]);
            cp.writeVectors(0.06, 2);
        }
        catch(Exception e) { e.printStackTrace(); }
    }
    
    public void read(String fileName) throws Exception {
        this.fileName = fileName;
        
        Fits fits = new Fits(fileName);
        BasicHDU<?>[] hdu = fits.read();
       
     
        double[][] q = (double[][]) ((ImageHDU) hdu[2]).getData().getData();
        double[][] u = (double[][]) ((ImageHDU) hdu[4]).getData().getData();
        double[][] f = (double[][]) ((ImageHDU) hdu[8]).getData().getData();
         
        sizeY = q.length;
        sizeX = q[0].length;
     
        Q = new double[sizeX][sizeY];
        U = new double[sizeX][sizeY];
        F = new double[sizeX][sizeY];
     
        for(int i=sizeX; --i >= 0; ) for(int j=sizeY; --j >= 0; ) {
            Q[i][j] = q[j][i];
            U[i][j] = u[j][i];
            F[i][j] = 0.01 * f[j][i];
        }
        
        fits.close();
        
        System.err.println("read " + sizeX + "x" + sizeY);
    }
    
    
    
    public void writeVectors(double maxPol, int sampling) throws Exception {
          
        String regFileName = fileName + ".reg";
        PrintWriter out = new PrintWriter(new FileOutputStream(regFileName));
            
        for(int i = 0; i < sizeX; i += sampling) for(int j=0; j < sizeY; j += sampling) {
            if(Double.isNaN(Q[i][j])) continue;
            if(Double.isNaN(U[i][j])) continue;
            if(Double.isNaN(F[i][j])) continue;
         
            double angle = 0.5 * Math.atan2(U[i][j], Q[i][j]);
            
            double l = (F[i][j] / maxPol);
            if(l > 1.0) l = 1.0;
            if(l < 0.0) l = 0.0;
            else l *= sampling * Math.sqrt(2.0);
            
            Vector2D d = new Vector2D(l, 0);
            d.scale(0.5);
            d.rotate(angle + 0.5 * Math.PI);

            out.println("physical;line " + Util.f2.format((i-d.x())) + " " + Util.f2.format((j-d.y())) + " " +
                    Util.f2.format((i+d.x())) + " " + Util.f2.format((j+d.y())) + " # color=white");
           
        }
          
        out.close();
        System.err.println(" Written " + regFileName);
        
    }
    
}
