#! python
""" Code to select entries
    
Context : SRP
Module  : SRPTNGPAOLOSelectCoord
Author  : Stefano Covino
Date    : 13/02/2017
E-mail  : stefano.covino@brera.inaf.it
URL:    : http://www.merate.mi.astro.it/utenti/covino
Purpose : Derive instrumental Q and U Stokes parameters

Usage   : SRPTNGPAOLOSelectCoord [-h] -c coord coord -f file -o file [-q quad]
                              [-t tol] [-v] [--version]
            -c X, Y coordinates to search for (pixel)
            -f Input PAOLO FITS file
            -o Output FITS file
            -q Quadrant with sources
            -t Tolerance for matching (pixel)
    
History : (29/09/2012) First version.
        : (30/01/2014) Check on data existence.
        : (13/02/2017) Python3 porting.
"""

__version__ = '0.1.2'


import argparse, math, sys
import atpy, numpy
import SRPTNG.PAOLO as STP
from SRP.SRPMath.CartesianDistance import CartesianDistance



parser = argparse.ArgumentParser()
parser.add_argument("-c", "--coords", action="store", type=float, nargs=2, help="X, Y coordinates to search for (pixel)", required=True, metavar='coord')
parser.add_argument("-f", "--fitsfile", action="store", help="Input PAOLO FITS  file", required=True, metavar='file')
parser.add_argument("-o", "--outfile", action="store", help="Output FITS file", required=True, metavar='file')
parser.add_argument("-q", "--quad", action="store", type=int, default=1, choices=(1,2,3,4), help="Quadrant with sources", metavar='quad')
parser.add_argument("-t", "--tol", action="store", type=float, default=2.5, help="Tolerance for matching (pixel)", metavar='tol')
parser.add_argument("-v", "--verbose", action="store_true", help="Fully describe operations")
parser.add_argument("--version", action="version", version=__version__)
options = parser.parse_args()


#
try:
    tphot = atpy.Table(options.fitsfile, type='fits')
except IOError:
    parser.error("Invalid input PAOLO FITS file.")
if options.verbose:
    print("Input PAOLO FITS file: %s" % options.fitsfile)
#
if options.verbose:
    print("Coordinates to search for: %.3f %.3f" % (options.coords[0], options.coords[1]))
#
if options.verbose:
    print("Tolerance for matching: %.3f" % options.tol)
#
if options.verbose:
    print("Quadrant with sources: %d" % options.quad)
#
quad = "%d" % options.quad
goodrw = []
for i in range(len(tphot)):
    try:
        if 'X'+'_'+quad in tphot.columns.keys and 'Y'+'_'+quad in tphot.columns.keys:
            if CartesianDistance((options.coords[0],options.coords[1]),(tphot[STP.X+'_'+quad][i],tphot[STP.Y+'_'+quad][i])) <= options.tol:
                goodrw.append(i)
        elif 'X' in tphot.columns.keys and 'Y' in tphot.columns.keys:
            if CartesianDistance((options.coords[0],options.coords[1]),(tphot[STP.X][i],tphot[STP.Y][i])) <= options.tol:
                goodrw.append(i)
    except ValueError:
        parser.error("Quadrant %s data not found in file %s." % (quad, options.fitsfile))
#
tnew = tphot.rows(goodrw)
#
tnew.write(options.outfile,type='fits',overwrite=True)
if options.verbose:
    print("Results saved in file %s with %d entries" % (options.outfile, len(tnew)))
else:
    print("%d %s" % (len(tnew), options.outfile))
#
