#!/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 INDI
#   * Assumes camera orientation is approximately aligned with HA and Dec
#   * Set orientation options below

# Copyright (c) 2011-2012 John Kielkopf and Karen Collins        
# kielkopf@louisville.edu                                                  
#                                                                          
#                                                                          
# Date: April 12, 2012                                                      
# Version: 1.0                                                             
#                                                                          
# This file is part of XmCCD                                              
#                                                                          
# XmCCD is free software: you can redistribute it and/or modify           
# it under the terms of the GNU General Public License as published by     
# the Free Software Foundation, either version 3 of the License, or        
# (at your option) any later version.                                      
#                                                                          
# XmCCD is distributed in the hope that it will be useful,                
# but WITHOUT ANY WARRANTY; without even the implied warranty of           
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            
# GNU General Public License for more details.                             



# 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


# 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
#
# CDK20N looking west
# ds9 display Zoom->Invert x and Rotate 0
#
# sign_ra = 1
# sign_dec = 1
# swap_xy = 0
#
# CDK20N looking east
# ds9 display Zoom->Invert x and Rotate 180
#
# sign_ra  = -1
# sign_dec = -1
# swap_xy = 0
#
#   * sign_dec is + if declination     increases as pixel index increases
#   * sign_ra  is + if right ascension increases as pixel index increases
#   * swap_xy  is 0 if right ascension is along x and declination is along y  
#   * swap_xy  is 1 if right ascension is along y and declination is along x 
#
# Assign values based on implementation
# Note these will change with a German equatorial after a meridian flip
# Swap flag depends on rotation of the camera

sign_ra  = -1
sign_dec = -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 = int(star_x - ref_x)
del_y = int(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 == 1):
  ddec = sign_dec*del_x
  dra = sign_ra*del_y
else:
  ddec = sign_dec*del_y
  dra = sign_ra*del_x
    
# print ddec, dha  

# Use INDI to issue a step command
# Telescope software should already be in guide state
# Toggling these commands on will step the pointing one pixel

# tel.slew.north=Off
# tel.slew.south=Off
# tel.slew.east=Off
# tel.slew.west=Off

rasteps = abs(1.5*dra)
decsteps = abs(1.5*ddec)

print "delta ra: ", dra 
print "delta dec: ", ddec  

if (ddec > 0):
  # Guide star appears to be north of the reference
  n = 0
  while (n < decsteps):
    Popen('setINDI tel.slew.north=On', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    Popen('setINDI tel.slew.north=Off', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    n = n + 1
elif (ddec < 0):
  # Guide star appears to be south of the reference
  n = 0
  while (n < decsteps):
    Popen('setINDI tel.slew.south=On', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    Popen('setINDI tel.slew.south=Off', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    n = n + 1      
else:
  pass  

if (dra > 0):
  # Guide star appears to be east of the reference
  n = 0
  while (n < rasteps):
    Popen('setINDI tel.slew.east=On', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    Popen('setINDI tel.slew.east=Off', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    n = n + 1
elif (ddec < 0):
  # Guide star appears to be west of the reference
  n = 0
  while (n < rasteps):
    Popen('setINDI tel.slew.west=On', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    Popen('setINDI tel.slew.west=Off', shell=True, stdout=PIPE).wait()
    time.sleep(.5)
    n = n + 1      
else:
  pass  


exit()
