 

if __name__ == '__main__':
    """
    """
# insert reference catalog into db
import glob, numpy
import atpy, sys
import psycopg2
import psycopg2.extras
from psycopg2.extensions import adapt, register_adapter, AsIs
from astropy.coordinates import SkyCoord
import astropy.units as u


filecatref = "./img_20130109_001427_2_10.0s_c1_calib.cat"

# Reads FITS_1.0 binary table
tbl = atpy.Table(filecatref,type='fits')

if len(tbl) > 0:
  # Filter only those objects with positive SExtractor FLUX_AUTO
  tbl2 = tbl.where(tbl['FLUX_AUTO'] > 0)
  
  # Add SNR column to tbl2 table
  tbl2.add_column('SNR', numpy.array(tbl2['FLUX_AUTO'] / tbl2['FLUXERR_AUTO'], dtype='>f4'))

  # Add OBJECT column to tbl2 table
  object_ = []
  c = SkyCoord(ra=tbl2['ALPHAWIN_J2000']*u.degree, dec=tbl2['DELTAWIN_J2000']*u.degree, frame='icrs')
  c1 = c.to_string('hmsdms',sep='',fields=3,precision=2,alwayssign=True,pad=True)
  object_ = [str('J'.join(obj.split('+', 1)).replace(' ','').replace('.','')) for obj in c1]
  tbl2.add_column('OBJECT', numpy.array(object_))

  # Define targets into numpy.array
  targets = numpy.array([tbl2['NUMBER'],tbl2['OBJECT'],tbl2['ALPHAWIN_J2000'],tbl2['DELTAWIN_J2000'],tbl2['SNR'],tbl2['ELONGATION'],tbl2['FWHM_IMAGE'],tbl2['FLAGS']])
  
  # Connect to an existing database
  conn_string = "host='127.0.0.1' dbname='catalogs' user='postgres' password='passwd'"
  conn = psycopg2.connect(conn_string)
  conn.set_client_encoding('UTF8')

  # Cause all results strings to be returned as Unicode strings
  psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
  psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)

  # These python numpy data types must be registered in order to get the insert working
  register_adapter(numpy.int16, AsIs)
  register_adapter(numpy.int32, AsIs)
  register_adapter(numpy.float32, AsIs)
  
  cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

  args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in targets)
  cur.execute("""INSERT INTO referencecat VALUES """ + args_str) 

  # Make the changes to the database persistent
  conn.commit()

  # Close communication with the database   
  cur.close()
  conn.close()
