#!/usr/bin/python3

# Fast astrometry on a CDK20 image with Apogee U16 camera
# Outputs to stdout and does not update status files
# Requires hard-coded tmp directory:  see line 57

# Copyright (c) 2017 John Kielkopf and Rhodes Hart        
# kielkopf@louisville.edu                                                  
#                                                                          
#                                                                          
# Date: May 19, 2017                                                  
# Version: 1.1                                                          
#                                                                          
# This file is part of XmCCD and XmTel for the CDK20                                             

# History 
#   2017-02-24  1.0 First code optimized for CDK20S guide feedback
#   2017-05-14  1.1 Python 3 version for CDK20N
#   2017-05-19  1.1 Parse hr:min:sec to get precise degrees


import sys
from subprocess import Popen, PIPE
import string
import time
import math
import re

if len(sys.argv) == 2:
  telcoordsfp = open("/usr/local/observatory/status/telcoords", 'r')
  telcoordstext = telcoordsfp.readlines()
  for line in telcoordstext:
    try:
      entry = line.strip().split()
      rahr = float(entry[0])
      radeg = 15.*rahr
      decdeg = float(entry[1]) 
    except:
      radeg = 0.
      decdeg = 0.
elif len(sys.argv) == 4:
  rahr = float(sys.argv[2])
  radeg = 15.*rahr
  decdeg = float(sys.argv[3])
else:
  print (" ")
  print ("Usage with decimal coordinate hints: guide_fast_solve.py image.fits [rahr decdeg]")
  print ("Reads system /usr/local/observatory/status/telcoords unless given hints")
  sys.exit("Shows the field center")  

# Talk to astrometry and find coordinates
# Requires temporary working file directory /home/observer/data/tmp

file_name = sys.argv[1]

astrometry = "/usr/local/astrometry/bin/solve-field  --no-plots  -z 2" \
  " --dir /home/observer/data/tmp/" \
  " --scale-units arcsecperpix --scale-low 0.39 --scale-high 0.41" \
  " --radius 1.0 --ra %f --dec %f"  \
  " --overwrite --new-fits none  %s" % (radeg, decdeg, file_name)


p1 = Popen( astrometry , shell=True, stdout=PIPE)
p1.wait()
output = str(p1.communicate()[0], 'utf-8')


# Parse stdout in phases

scratch, center = output.split("Dec D:M:S) = (",1)

ratxt = center.split()[0]
dectxt = center.split()[1]
rotationtxt = center.split()[13]

rahr =  re.findall(r"[-+]?\d*\.\d+|\d+",ratxt.split(":")[0])
ramin = re.findall(r"[-+]?\d*\.\d+|\d+",ratxt.split(":")[1])
rasec = re.findall(r"[-+]?\d*\.\d+|\d+",ratxt.split(":")[2])

decdeg = re.findall(r"[-+]?\d*\.\d+|\d+",dectxt.split(":")[0])
decmin =  re.findall(r"[-+]?\d*\.\d+|\d+",dectxt.split(":")[1])
decsec =  re.findall(r"[-+]?\d*\.\d+|\d+",dectxt.split(":")[2])

rotation = re.findall(r"[-+]?\d*\.\d+|\d+",rotationtxt)

decsign = 1.
if ( float(decdeg[0]) < 0. ):
  decsign = -1.
  
ra = (float(rahr[0]) + float(ramin[0])/60. + float(rasec[0])/3600.)
dec = decsign*(abs(float(decdeg[0])) + float(decmin[0])/60. + float(decsec[0])/3600.)
rot = float(rotation[0])

print ("RA [hr]: %10.5f" % ra)
print ("Declination [deg]: %10.5f" % dec)
print ("Field rotation [deg]: %5.3f" % rot)

exit()
  
