#!/usr/bin/env python

"""Cross-match 2MASS Point Source Catalog to Tycho-2 within 5 arcsec radius.

The 2MASS J, H and K-band magnitude columns are added to the Tycho-2 catalog.

The Tycho-2 catalog was generated by the script tycho2-galaxies.py.

The 2MASS catalog with selected columns is obtained from 
http://vizier.u-strasbg.fr/viz-bin/VizieR?-source=II/246 with no cuts except
cuts on DEC (DEC>-25) and galactic latitudes (|b|>10).

"""
import os
import numpy as np
import fitsio
from astropy.table import Table
import match_coord

tycho2_path = 'tycho2.kd.fits'
twomass_path = '2mass_psc.fits'
outfile = 'tycho2-isgalaxyflag-2mass.kd.fits'

search_radius = 5. # arcsec

tycho2 = Table.read(tycho2_path, hdu=1)
twomass = Table.read(twomass_path)

# Cross-match the two catalogs
# If there are multiple matches within the search radius, only the nearest match is kept
idx_twomass, idx_tycho2, d2d, _, _ = match_coord.match_coord(twomass['RAJ2000'], twomass['DEJ2000'], 
    tycho2['RA'], tycho2['DEC'], search_radius=search_radius, plot_q=True)

tycho2 = tycho2.copy()
tycho2['Jmag'] = 99.*np.ones(len(tycho2), dtype=np.float32)
tycho2['Hmag'] = 99.*np.ones(len(tycho2), dtype=np.float32)
tycho2['Kmag'] = 99.*np.ones(len(tycho2), dtype=np.float32)

tycho2['Jmag'][idx_tycho2] = twomass['Jmag'][idx_twomass]
tycho2['Hmag'][idx_tycho2] = twomass['Hmag'][idx_twomass]
tycho2['Kmag'][idx_tycho2] = twomass['Kmag'][idx_twomass]

tycho2.write(outfile)

ff = fitsio.FITS(tycho2_path)
for ii in range(5):
    fitsio.write(outfile, ff[ii+2].read())


