#!/usr/bin/python3

from astropy.coordinates import SkyCoord,FK4,Galactic,ICRS,FK5
import astropy.units as u
import re
import sys

RegHex = re.compile("^(\d+)h(\d+)m([\d.]+)s +([-+\d]+)d(\d+)m([\d.]+)s$")

def __dec_to_hex(csys):
    mo = RegHex.match(csys.to_string('hmsdms'))
    if mo is None:
        sys.stderr.write("****ERROR format : {0}\n".format(csys.to_string('hmsdms')))
        sys.exit(1)
    return ("{0:2s}:{1:2s}:{2:05.2f}".format(mo.group(1), mo.group(2), float(mo.group(3))),
            "{0:2s}:{1:2s}:{2:04.1f}".format(mo.group(4), mo.group(5), float(mo.group(6))))

    #return re.sub(r"([hdm])", ":", csys.to_string('hmsdms')).replace("s","")

def convert_30m_coord(filename):
    """add ICRS column"""
    count=0
    with open(filename, "r") as fd:
        for line in fd:
            count += 1
            if count % 100000 == 0: 
                sys.stderr.write("....convert {0} records\n".format(count))

            csys = line[21:28]
            ra = line[38:49] #"HH MM SS.SS"
            de = line[55:66]

            if csys.find("J2000")>-1:
                if line[46] != '.': line = line[:46]+"."+line[47:]
                if line[64] != '.': line = line[:64]+"."+line[65:]
                print (line.rstrip())

            elif csys.find("B1950")>-1:
                csysicrs = SkyCoord([ra+" "+de], unit=(u.hourangle,u.deg), frame=FK4)
                (ra, de) = __dec_to_hex(csysicrs.transform_to(ICRS)[0])
                print ("{0}{1:11s}{2:6s}{3:12s}{4:s}".format(line[:38], ra, " ", de, line[67:].rstrip()))

            elif csys.find("GA")>-1:
                csysicrs = SkyCoord([ra+" "+de], unit=(u.deg,u.deg), frame=Galactic)
                (ra, de) = __dec_to_hex(csysicrs.transform_to(ICRS)[0])
                print ("{0}{1:11s}{2:6s}{3:12s}{4:s}".format(line[:38], ra, " ", de, line[67:].rstrip()).replace(" GA ", " G  "))
                
            else:
                print (line.rstrip())
            

if __name__ == "__main__":
    if len(sys.argv) < 2: 
        sys.stderr.write("****requires the 30m file name\n")
        sys.exit(1)
     
    convert_30m_coord(sys.argv[1])
