""" Code to do computations on columns
Context : SRP.GW
Module  : SRPGWCalc
Author  : Stefano Covino
Date    : 02/03/2017
E-mail  : stefano.covino@brera.inaf.it
URL:    : http://www.merate.mi.astro.it/utenti/covino
Purpose : Do computations on columns

usage: SRPGWCalc [-h] -c calc [-d] -i inputfile -o outfile [-v] [--version]

optional arguments:
  -h, --help            show this help message and exit
  -c calc, --calc calc  Computation to be execjuted
  -d, --debug           Debug information
  -i inputfile, --inputfile inputfile
                        Input table
  -o outfile, --outfile outfile
                        Output table
  -v, --verbose         Fully describe operations
  --version             show program's version number and exit


History : (31/10/2015) First version.
        : (02/03/2017) Update.
"""

__version__ = '1.0.1'


import argparse, os
import numpy
from astropy.table import Table
import SRPGW as GW
from SRPGW.GetCommandStr import GetCommandStr




parser = argparse.ArgumentParser()
parser.add_argument("-c", "--calc", action="store", help="Computation to be execjuted", required=True, metavar='calc')
parser.add_argument("-d", "--debug", action="store_true", help="Debug information")
parser.add_argument("-i", "--inputfile", action="store", help="Input table", required=True, metavar='inputfile')
parser.add_argument("-o", "--outfile", action="store", help="Output table", required=True, metavar='outfile')
parser.add_argument("-v", "--verbose", action="store_true", help="Fully describe operations")
parser.add_argument("--version", action="version", version=__version__)
options = parser.parse_args()


#
if options.inputfile and options.calc:
    #
    if not os.path.isfile(options.inputfile):
        parser.error ("Input file list does not exist.")
    #
    if options.verbose:
        print ("Reading table ", options.inputfile)
    dt = Table.read(options.inputfile, format='ascii.ecsv')
    #
    opstr = GetCommandStr(options.calc,dt.columns.keys(),'dt')
    if options.debug:
        print("Requested operation: ", opstr)
    try:
        exec(opstr)
    except NameError:
        parser.error("Column not existent.")
    except SyntaxError:
        parser.error("Syntax error.")
    #
    dt.write(options.outfile,format='ascii.ecsv', overwrite=True)
    if options.verbose:
        print ("Table %s with %d entries saved." % (options.outfile, len(dt)))
    else:
        print (options.outfile, len(dt))
else:
    parser.print_help()
#