import java.io.*;
import java.text.*;
import java.util.*;


public class MapHistogram {
    static String version = "18 August 2004";
    static double binres = 1.0;
    static String fileName;

    public static void main(String[] args) {
	versionInfo();
	if(args.length == 0) usage();
	
	for(int k=0; k < args.length-1; k++) option(args[k]);
	    	

	try {
	    ReducedData map = new ReducedData(args[args.length-1]);

	    double min = map.getMin(map.s2n);
	    double max = map.getMax(map.s2n);

	    int bins = (int) Math.ceil((max - min) / binres);

	    int[] count = new int[bins];

	    for(int i=0; i<map.sizeX; i++) for(int j=0; j<map.sizeY; j++) if(map.flag[i][j] == 0) {
		int bin = (int) Math.floor((map.s2n[i][j] - min) / binres);		
		count[bin]++;
	    }
	    
	    if(fileName == null) fileName = Crush.workPath + "histogram-" + map.sourceName + ".dat"; 
	    File file = new File(fileName);
	    if(file.exists()) file.delete();
	    RandomAccessFile out = new RandomAccessFile(file, "rw");
	    
	    out.writeBytes("# histogram for " + map.fileName + "\n");
	    out.writeBytes("# bin resolution is " + binres + " sigma");
	    out.writeBytes("# bin#\tvalue\tcount#");
	    out.writeBytes("# ----\t-----\t------");
	    
	    DecimalFormat df = new DecimalFormat("0.00");
	    
	    for(int i=0; i<bins; i++) out.writeBytes((i+1) + "\t" + df.format(min + (i+0.5)*binres) + "\t" + count[i] + "\n");
	    
	    out.close();

	    System.out.println("Written Histogram to " + fileName);
	}
	catch(Exception e) {}	
    }

     public static boolean option(String optionString) {
	StringTokenizer tokens = new StringTokenizer(optionString, "=");

	String key = tokens.nextToken();

	if(key.equalsIgnoreCase("-bin")) binres = Double.parseDouble(tokens.nextToken());
	if(key.equalsIgnoreCase("-out")) fileName = tokens.nextToken();
	else if(key.equalsIgnoreCase("-help")) usage();
	else return false;

	return true;    
    }

    public static void versionInfo() {
	System.out.println("histogram -- Histogram Generation Utility for SHARC2 maps.");
	System.out.println("             Author: Attila Kovacs <attila@submm.caltech.edu>");
	System.out.println("             Version: " + version);
	System.out.println();
    }

    public static void usage() {
	System.out.println("usage: histogram [options] <filename>");
	System.out.println();
	System.out.println("options:");
	System.out.println();
	System.out.println("    -bin=      Set the bin size in sigma units. (" + binres + ")");
	System.out.println("    -out=      Set the output file's name.");	
	System.out.println("    -help      Provides this help screen.");
	System.out.println();
	
	System.exit(0);
    }
}
