#!/usr/bin/python3

# Update telescope pointing from guide image center coordinate status file

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

# History 
#   2017-09-25 1.0 First code 

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

if len(sys.argv) == 1:
  telcoordsfp = open("/usr/local/observatory/status/guidecoords", 'r')
  telcoordstext = telcoordsfp.readlines()
  for line in telcoordstext:
    try:
      entry = line.strip().split()
      rahr = float(entry[0])
      decdeg = float(entry[1]) 
    except:
      radeg = 0.
      decdeg = 0.
else:
  print (" ")
  print ("Reads system /usr/local/observatory/status/guidecoords.")
  print ("Use guide_update_center.py first for highest accuracy.")
  print ("Updates telescope pointing.")
  sys.exit ("No argument is required.")
  




print ("\n")
print ("Updating  telescope pointing to field center")
print ("\n")

# Clear the offsets in use in the event they are active

telcmd = 'xpaset -p tel offset clear' 
Popen(telcmd, shell=True, stdout=PIPE).wait()


# Turn off offset corrections

telcmd = 'xpaset -p tel offset off' 
Popen(telcmd, shell=True, stdout=PIPE).wait()

# Clear the offsets in use again to reset to defaults

telcmd = 'xpaset -p tel offset clear' 
Popen(telcmd, shell=True, stdout=PIPE).wait()

# Set the target to the measured field center

telcmd = 'xpaset -p tel target %10.5f %10.5f' % (rahr, decdeg)
Popen(telcmd, shell=True, stdout=PIPE).wait()


# Turn on offsets

telcmd = 'xpaset -p tel offset on' 
Popen(telcmd, shell=True, stdout=PIPE).wait()


# Set offsets to the target  

telcmd = 'xpaset -p tel offset target' 
Popen(telcmd, shell=True, stdout=PIPE).wait()

# The telescope now knows its own field center

print ("\n")
print ("Updated telescope pointing to ")
print ("RA [hr]: %10.5f" % rahr)
print ("Declination [deg]: %10.5f" % decdeg)
print ("\n")



exit()
  
