""" Code to match pair of coordinates.

Context : SRP
Module  : SRPHistogram.py
Version : 1.2.1
Author  : Stefano Covino
Date    : 01/09/2011
E-mail  : stefano.covino@rera.inaf.it
URL:    : http://www.merate.mi.astro.it/utenti/covino
Purpose : Create an histogram from a set of data.

Usage   : SRPHistogram -c arg1 [-h] [-j arg2] -o arg3 -t arg4 [-v]
            -b Bin data [i.e. min max bin_size]
            -c Column for histogram
            -j Number of header lines to skip
            -o Output file
            -t Table containing data to extract


History : (04/02/2005) First version.
        : (23/05/2005) Better bin limit computation.
        : (20/06/2010) Cumulative hitogram added.
        : (01/09/2011) Better cosmetics.
"""


import string, os
from optparse import OptionParser
import SRP.SRPConstants as SRPConstants
import SRP.SRPFiles as SRPFiles
import SRP.stats as stats



parser = OptionParser(usage="usage: %prog -c arg1 [-h] [-j arg2] -o arg3 -t arg4 [-v]", version="%prog 1.2.1")
parser.add_option("-b", "--bindata", action="store", nargs=3, type="float", dest="bind", help="Bin data [i.e. min max bin_size]")
parser.add_option("-c", "--columns", action="store", type="int", dest="col", help="Column for histogram")
parser.add_option("-j", "--jump", action="store", nargs=1, type="int", dest="jump", default=1, help="Number of header lines to skip")
parser.add_option("-o", "--out", action="store", nargs=1, type="string", dest="outf", help="Output file.")
parser.add_option("-t", "--table", action="store", nargs=1, type="string", dest="table", help="Table containing data to extract")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Fully describe operations")
(options, args) = parser.parse_args()


if options.table and options.col and options.outf:
        # Session name
        sname = SRPFiles.getSRPSessionName()
	if options.verbose:
		print "Session name %s retrieved." % sname
        # Opne file
	f1 = SRPFiles.SRPFile(SRPConstants.SRPLocalDir,options.table,SRPFiles.ReadMode)
	f1.SRPOpenFile()
	if options.verbose:
		print "Opening %s file." % options.table
	if f1.f == None:
		parser.error("Error in input file %s." % options.table)
        # Check header jump
	if options.jump < 0:
		parser.error("Header lines to jump %d must be positive." % options.jump)
        # Check column to process
        if options.col <= 0:
                parser.error("Column number %d should be positive." % ii) 
        # Check bin data
        if (options.bind[1] <= options.bind[0]) or (options.bind[2] <= 0):
                parser.error("Histogram maximum %g should be larger than minimum %g or bin size %g should be positive." % (options.bind[1], options.bind[0], options.bind[2]))
        nbin = (options.bind[1]-options.bind[0])/options.bind[2]
        if nbin <= 1:
                parser.error("Histogram requires at least one bin.")
        # Read file
	try:
		dt1 = f1.SRPReadTotFile()
	except:
		parser.error("Error in reading from file %s." % options.ref)
	f1.SRPCloseFile()
	if options.verbose:
		print "Read %d entries." % len(dt1)
	ddt1 = []
        if options.jump <> 0:
	       for i in range(options.jump,len(dt1)):
		      ddt1.append(dt1[i])
        else:
                ddt1 = dt1
	if options.verbose:
		print "Selected %d entries." % len(ddt1)
        del dt1
        # Extract columns
	l1 = []
	for i in range(len(ddt1)):
		try:
			inp = string.split(ddt1[i])
		except:
			parser.error("Problem in extracting data from file %s." % options.table)
                if len(inp) > 0:
                        try:
                                l1.append(float(inp[options.col-1]))
                        except IndexError: 
                                parser.error("Problem with column %d." % options.col)
        # Compute histogram
        if options.verbose:
                print "Histogram creation..."
        if nbin-int(nbin) > 0:
                fnbin = int(nbin) + 1
        else:
                fnbin = int(nbin)
        if options.verbose:
                print "Minimum: %g, Maximum: %g, Nr. bins: %d, real bin size: %g." % (options.bind[0], options.bind[1], fnbin, (options.bind[1]-options.bind[0])/fnbin)
        tot = len(l1)
        bdata = stats.histogram(l1, fnbin, (options.bind[0],options.bind[1]))
        l1o = ''
        minb = bdata[1] - bdata[2]/2.0
        parztot = 0.0
        for i in bdata[0]:
                minb = minb + bdata[2]
                parztot = parztot + i
                l1o = l1o + "%g %g %d %g %s" % (minb, bdata[2], i, 100.0*parztot/(tot-bdata[3]), os.linesep)
        # Write output 
	if options.verbose:
		print "Output %s creation." % (sname+options.outf)
	o1 = SRPFiles.SRPFile(SRPConstants.SRPLocalDir,sname+options.outf,SRPFiles.WriteMode)
	o1.SRPOpenFile()
	o1.SRPWriteFile(l1o)
	o1.SRPCloseFile()
        if options.verbose:
                print "End of job."
else:
	parser.print_help()

