#!/usr/bin/env python
"""
Compute XSM Flux in user defined energy band by integrating the input time-resolved
spectrum file and write flux data to output text file. 
It writes out nan for time bins when data is not available.

Output file has three columns, UTC, flux, beFilterFlag

beFilterFlag: 0 - no filter, 1 - filter present, >=10: Mixed filter condition in timebin 
When Be filter is engaged, XSM measures flux only above 2 keV. A flux scaling 
is applied for 1-8 Ang or 1.55-12.4 keV energy range. Otherwise the flux obtained 
with beFilterFlag is not zero for energy ranges below 2 keV will not be correct. 
"""

from astropy.io import fits
import numpy as np
import argparse, os
from datetime import datetime, date, timedelta
import sys

parser = argparse.ArgumentParser(epilog="""
""")
parser.add_argument("spec2file", help="Type-2 (time-resolved) spectrum file to be used for processing", type=str)
parser.add_argument("outfile", help="Output text file name", type=str)
parser.add_argument("Elow", help="Lower energy limit for flux", type=float)
parser.add_argument("Ehigh", help="Higher energy limit for flux", type=float)


args = parser.parse_args()

if(os.path.isfile(args.spec2file)):
	spec2file=args.spec2file
else:
	print("Input file does not exist")
	sys.exit()
	
outfile=args.outfile

if (args.Elow >=1.0) & (args.Elow<=15.0):
	Elow=args.Elow
else:
	print("Elow has to be within 1-15 keV")
	sys.exit()

if (args.Ehigh >=1.0) & (args.Ehigh<=15.0):
    Ehigh=args.Ehigh
else:
	print("Ehigh has to be within 1-15 keV")
	sys.exit()

if (Ehigh <= Elow):
	print("Ehigh can't be <= Elow")
	sys.exit()

dateref=datetime(2017,1,1)

hdu1 = fits.open(spec2file)
hdu=fits.BinTableHDU.from_columns(hdu1[1].columns)

if (float(hdu1[1].header['XSMDASVE'])<2.0):
    print("Input spectrum is generated with XSMDAS Version below 2.0; not generating output flux file") 
    print("Please generate spectrum files with the latest version of XSMDAS with xsmgenspec task")
    print("Generate time-resolved spectrum with commandline options: xsmgenspec genarf=no areascal=yes")
    sys.exit()

if (hdu1[1].header['ONAXASCL']!='YES'):
    print("Input spectrum is not generated with area scaled to on-axis area")
    print("Generate time-resolved spectrum with commandline options: xsmgenspec genarf=no areascal=yes")
    print("Refer to user guide for more information")
    sys.exit()    

data=hdu.data

time = (data['TSTART']+data['TSTOP'])/2.
tbinsize=(data['TSTOP'][0]-data['TSTART'][0])
filtStatus=data['FILT_STATUS']
exposure=data['EXPOSURE']

ns=len(data)
fluxlc = np.zeros(ns)

ene=np.arange(0,512)*0.033+0.5+0.033/2.0 # Midpoint energy of PI bins

kev2erg=1.6021e-9
cgs2si=0.001

startch=int((Elow-0.5)/0.033)
stopch=int((Ehigh-0.5)/0.033)

effarea=np.loadtxt(os.environ.get('xsmdas')+'/scripts/xsm_onaxis_effective_area.txt')
effarea_befilt=np.loadtxt(os.environ.get('xsmdas')+'/scripts/xsm_onaxis_effective_area_befilt.txt')

effarea[:14]=0  # set area below 1 keV to zero
effarea_befilt[:44]=0  # set area below 2 keV to zero for Be filt case

for i in range(0,ns):
    spec = data['COUNTS'][i]/data['EXPOSURE'][i]
    tbin=data['TSTOP'][i]-data['TSTART'][i]
    if filtStatus[i]==2:
        area=effarea_befilt
    elif filtStatus[i]==0:
        area=effarea
    else:
        openfrac=float(filtStatus[i]-10)/tbin
        area=effarea*openfrac+effarea_befilt*(1-openfrac)
        
    ind=np.where(area!=0)
    spec_ene = spec*ene
    spec_ene[ind] = spec_ene[ind]/area[ind]
    spec_ene[np.where(area==0)]=np.nan
    fluxlc[i] = np.nansum(spec_ene[startch:stopch])*kev2erg*cgs2si

## Select only bins with atleast half exposure and without mixed filter position having no clean number of openTbins
ind=((exposure  > max(exposure)/2.0) & (filtStatus!=10))
time=time[ind]
fluxlc=fluxlc[ind]
exposure=exposure[ind]
filtStatus=filtStatus[ind]

nbins=int(86400.0/tbinsize)

tday0=int(time[0]/86400.0)*86400.0
t0=(time[0]-int((time[0]-tday0)/tbinsize)*tbinsize)
alltime=np.arange(0,nbins)*tbinsize+t0
allflux=np.empty(nbins)
allflag=np.zeros(nbins)

allflux[:]=np.nan

allutc=[(dateref+timedelta(seconds=t)).strftime("%Y-%m-%dT%H:%M:%S") for t in alltime]

for i,t in enumerate(time):
    tbin=int((t-tday0)/tbinsize)
    allflux[tbin]=fluxlc[i]
    allflag[tbin]=filtStatus[i]

## Scaling for flux for beWind observations only for 1.55-12.4 keV or 1-8 Ang energy range
beInd=(allflag==2)

if (len(beInd)!=0):
    allflag[beInd]=1
    if ((Elow==1.55)&(Ehigh==12.4)):
        allflux[beInd]=10.0**(0.85391952*np.log10(allflux[beInd])-0.39749446)
        print("Approximate flux scaling applied for observations with Be window")
    elif (Elow<2.0):
        print("Time bins with XSM observations with Be filter are present, where flux above 2 keV are measured")
        print("Flux in these time bins will not be accurate - it provides only measurements from 2 keV above")
        print("Approximate flux scaling is avaiable for 1-8 Ang or 1.55 - 12.4 keV band")
        print("Run 'xsmcomputeflux specfile fluxfile 1.55 12.4' to obtain that")

np.savetxt(outfile,np.c_[allutc,allflux,allflag],fmt="%s")
    
