# A quick hack to fake a *.table file for SERC-I data from the bycd.all
# file in use by USNO internally.

import math
import time

from gavo.base import coords
from gavo import utils


def makeCatEntry(ignoredCodes, usnoCode, pathJunk, obsCode, rawEpoch, rawTime,
		rawRA, rawDec, emulsion, filter, exposure, ha):
	plateNumber = int(usnoCode[2:])
	yr, _, _, _, _, _, _, doy, _ = time.strptime(rawEpoch, "%d%b%Y")
	julianYear = yr+doy/365.25
	_, _, _, hr, min, _, _, _, _ = time.strptime(rawTime, "%H:%M")
	floatHour = hr+min/60.
	ra1950 = utils.hmsToDeg(rawRA, "")
	de1950 = utils.dmsToDeg(rawDec, "")
#	if usnoCode[:2]!="xn":  # SERC-I taken for POSS-II N, leave these
#		if de1950>0.3:
#			return
	if usnoCode[:2] in ignoredCodes:
		return
	ra2000, de2000 = coords.convertSys(ra1950, de1950, "B1950", "J2000")
	ra1950 *= math.pi/180
	de1950 *= math.pi/180
	ra2000 *= math.pi/180
	de2000 *= math.pi/180
	if emulsion=="IVN":
		return ("%(plateNumber)04d  "
			"%(obsCode)7s "
			"%(julianYear)9.4f "
			"%(floatHour)5.2f "
			"%(ra1950)8.6f "
			"%(de1950)+9.6f "
			"%(ra2000)8.6f "
			"%(de2000)+9.6f "
			"%(emulsion)-5s "
			"%(filter)-6s "
			"%(exposure)4s "
			"%(ha)5s                                        "
			"%(usnoCode)s"
		)%locals()


def makeSERCI():
	print """SERC-I
	Plate log hacked at ARI for USNO-B import.
	Origin of data: bycd.all file provided by Dave Monet
	File generated by $gavoroot/inputs/usnob/bin/bycd2table.py

	Field Plate   Date      Time  RA (B1950)     DEC RA  (J2000)    DEC Type  Filt    Exp H.A.   limits"""

	for ln in open("bycd.all"):
		tableLn = makeCatEntry(["si",  "xn"], *ln.split())
		if tableLn:
			print tableLn


def makePOSSIIExt():
	"""these are xn....-entries in bycd.all that are mapped to H in usno-b.

	These got appended to POSSII.table.
	"""
	print """POSS-II plates from SERC.
	Append this to POSSII-plates.

	Field Plate   Date      Time  RA (B1950)     DEC RA  (J2000)    DEC Type  Filt    Exp H.A.   limits"""

	for ln in open("bycd.all"):
		tableLn = makeCatEntry(["si", "sn", "an"], *ln.split())
		if tableLn:
			print tableLn


if __name__=="__main__":
	makeSERCI()
