""" Code to merge tables
    
Context : SRP
Module  : SRPTNGPAOLOMergeTables
Author  : Stefano Covino
Date    : 27/09/2013
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.
"""

__version__ = '0.1.2'


import argparse
import atpy



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 = atpy.Table(fl[1], type='fits')
    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
        tf.table_name = options.outfile
    elif fl[0] != 0:
        try:
            tf.append(t)
        except (ValueError, TypeError):
            parser.error("Table %s not compatible." % fl[1])
#
tf.write(options.outfile,type='fits',overwrite=True)
if options.verbose:
    print "Results saved in file %s with %d entries" % (options.outfile, len(tf))
else:
    print "%d %s" % (len(tf), options.outfile)
#
