#!/usr/bin/python

# * guide 
#
#   * Use ds9 to centroid on a selected region near a guide star
#   * Read the reference and guide positions
#   * Issue corrections to tel through CDK700 PWI server
#   * Assumes camera orientation is approximately aligned with HA and Dec
#   * Set orientation options below

# Copyright (c) 2011-2015 John Kielkopf and Karen Collins        
# kielkopf@louisville.edu                                                  
#                                                                          
#                                                                          
# Date: October 11, 2015                                                    
# Version: 1.3                                                            
#                                                                          
# This file is part of XmCCD                                              


# red is reference
# select green to track
# command line: xpaget ds9 regions
# command line: xpaget ds9 regions selected
# command line: xpaset -p ds9 regions centroid

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

if len(sys.argv) == 1:
  angle = 0.
elif len(sys.argv) == 2:
  angle = -1.*math.radians(float(sys.argv[1]))
else:
  print " "
  print "Usage: guide.py [position_angle]"
  sys.exit("Guides on a ds9 image")  

# Set these flags as appropriate for camera orientation
#
#   * By default right ascension is x and declination is y on ds9
#   * By default north is up and west is to the right

# Typical default values
#
# CDK700 looking west
# ds9 display Zoom->Invert x and Rotate 0
#
# sign_x = 1
# sign_y = 1
# swap_xy = 0
#
#   * sign_y  is + if declination increases as pixel index increases
#   * sign_x  is + if right ascension increases as pixel index increases
#   * swap_xy  is 0 if right ascension is along x and declination is along y at 0 degrees position angle  
#   * swap_xy  is 1 if right ascension is along y and declination is along x at 0 degrees position angle
#
# Assign values based on implementation
# Swap flag depends on rotation of the camera with respect to altitude/azimuth

print math.degrees(angle)

gain = 1.1
arcsecperpix= 0.401
sign_x  = -1
sign_y = 1
swap_xy = 0

# Talk to ds9 and find the reference and guide star coordinates

p1 = Popen('xpaset -p ds9 regions centroid', shell=True, stdout=PIPE)
p1.wait()
p2 = Popen('xpaget ds9 regions', shell=True, stdout=PIPE)
p2.wait()
output = p2.communicate()[0]

# Parse stdout in phases

scratch, circles = output.split("circle(",1)

circle1, circle2 = circles.split("circle(",1)

# print circle1, "\n", circle2

circlered = circle2
if "color=red" in circle1:
  circleref = circle1
  circlestar = circle2
else:
  circleref = circle2
  circlestar = circle1

# print "reference: ", circleref
# print "star: " , circlestar 

ref = circleref.split(",")
star = circlestar.split(",")

# print  ref[0], ref[1]
# print star[0],star[1]

ref_x = float(ref[0])
ref_y = float(ref[1])
star_x = float(star[0])
star_y = float(star[1])

print ref_x, ref_y
print star_x, star_y

# Calculate the pointing error
# Positive value for star at larger x or y than reference

del_x = star_x - ref_x
del_y = star_y - ref_y

print del_x, del_y
 
# Interpret the (x,y) error as an (ra,dec) error with correct sign
 
if (swap_xy == 0):
  del_x = sign_x*del_x
  del_y = sign_y*del_y
else:
  del_x = sign_y*del_y
  del_y = sign_x*del_x
    
del_ra = gain*arcsecperpix*(del_x*math.cos(angle) - del_y*math.sin(angle))
del_dec = gain*arcsecperpix*(del_x*math.sin(angle) + del_y*math.cos(angle))

print "delta ra (arcsec): ", del_ra 
print "delta dec (arcsec): ", del_dec  

guidedeccmd = 'curl "http://192.168.10.90?device=mount&cmd=move&incrementdec=%d" ' % (del_dec,) 
Popen(guidedeccmd, shell=True, stdout=PIPE).wait()
guideracmd = 'curl "http://192.168.10.90?device=mount&cmd=move&incrementra=%d" ' % (del_ra,) 
Popen(guideracmd, shell=True, stdout=PIPE).wait()
  
exit()
