""" Code to compute flux density

Context : SRP
Module  : SRPPLFluxDensity.py
Version : 1.0.2
Author  : Stefano Covino
Date    : 29/11/2012
E-mail  : stefano.covino@brera.inaf.it
URL:    : http://www.merate.mi.astro.it/~covino
Purpose : Compute the flux density assuming a power-law spectrum

Usage   : SRPPLFluxDensity [-d arg1] [-e arg2 arg3] -f arg4 [-h] [-s arg5] [-v]
            -d Output flux density (keV)
            -e Energy limits min max (keV)
            -f Integrated flux (erg/cm2 s)
            -s Spectral slope


History : (02/07/2008) First version.
        : (10/09/2011) Better cosmetics.
        : (29/11/2012) Better help message.

"""


import sys, math
from optparse import OptionParser
import SRP.SRPConstants as SRPConstants


keV2erg = 1.6021765e-09
h = 6.62606876e-27
ergcm2sHz2Jy = 1e23

def integ (emin,emax,totflux,vu=1.0,slope=-1.0):
        vmax = emax*keV2erg/h
        vmin = emin*keV2erg/h
        if slope == -1:
                N = totflux/math.log(vmax/vmin)
        else:
                N = totflux/((vmax**(slope+1)-vmin**(slope+1))/(slope+1))
        vuHz = vu*keV2erg/h
        return ergcm2sHz2Jy*N*vuHz**slope



parser = OptionParser(usage="usage: %prog [-d arg1] [-e arg2 arg3] -f arg4 [-h] [-s arg5] [-v]", version="%prog 1.0.2")
parser.add_option("-d", "--density", action="store", nargs=1, default=1.0, type="float", dest="density", help="Output flux density (keV)")
parser.add_option("-e", "--energy", action="store", nargs=2, type="float", default=(0.3,10.0), dest="energy", help="Energy limits min max (keV)")
parser.add_option("-f", "--flux", action="store", nargs=1, type="float", dest="flux", help="Integrated flux (erg/cm2 s)")
parser.add_option("-s", "--slope", action="store", nargs=1, default=-1.0, type="float", dest="slope", help="Spectral slope (signed)")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Fully describe operations")
(options, args) = parser.parse_args()

if options.density <= 0.0 or options.energy[0] >= options.energy[1] or options.energy[0] <= 0.0 or options.flux <= 0.0:
        parser.print_help()
        sys.exit(SRPConstants.SRPExitFailure)
        
if options.verbose:
        print "Integrated flux       : %g erg/cm2 s" % options.flux
        print "Energy limits         : %g, %g keV" % (options.energy[0], options.energy[1])
        print "Spectral slope        : %f" % options.slope
        print "Flux density at %g keV: %g Jy" % (options.density, integ(options.energy[0],options.energy[1],options.flux,options.density,options.slope))         
else:
        print "%g %g %g %f %g %g" % (options.flux, options.energy[0], options.energy[1], options.slope, options.density, integ(options.energy[0],options.energy[1],options.flux,options.density,options.slope))
        

        
