#! python
""" Code to merge tables
    
Context : SRP
Module  : SRPTNGPAOLOMergeTables
Author  : Stefano Covino
Date    : 18/05/2017
E-mail  : stefano.covino@brera.inaf.it
URL:    : http://www.merate.mi.astro.it/utenti/covino
Purpose : Merge PAOLO tables.

Usage   : SRPTNGPAOLOMergeTables [-h] -f [file [file ...]] -o file [-v]
            -f Input FITS file(s)
            -o Output FITS file
    
History : (23/02/2012) First version.
        : (02/08/2012) Minor bugs.
        : (27/09/2013) Update for the latest atpy release.
        : (01/04/2015) Porting to astropy
        : (13/02/2017) Python3 porting.
        : (14/02/2017) Minor bug.
        : (18/05/2017) Minor update.
"""

__version__ = '1.0.3'


import argparse
from astropy.io import fits
from SRPFITS.Fits.FitsTabsAppend import FitsTabsAppend



parser = argparse.ArgumentParser()
parser.add_argument("-f", "--fitsfile", action="store", nargs='*', help="Input FITS file(s)", required=True, metavar='file')
parser.add_argument("-o", "--outfile", action="store", help="Output FITS file", required=True, metavar='file')
parser.add_argument("-v", "--verbose", action="store_true", help="Fully describe operations")
parser.add_argument("--version", action="version", version=__version__)
options = parser.parse_args()


#
for fl in enumerate(options.fitsfile):
    try:
        t = fits.open(fl[1])
    except IOError:
        parser.error("Invalid input FITS file: %s." % fl[1])
    if options.verbose:
        print("Opening input FITS file: %s" % fl[1])
    #
    if fl[0] == 0:
        tf = t[1]
    elif fl[0] != 0:
        tf = FitsTabsAppend(tf,t[1])
        if tf == None:
            parser.error("Table %s not compatible." % fl[1])
#
tf.writeto(options.outfile, overwrite=True)
if options.verbose:
    print("Results saved in file %s with %d entries" % (options.outfile, tf.data.shape[0]))
else:
    print("%d %s" % (tf.data.shape[0], options.outfile))
#
