# Utility functions that act on AIPS datasets.
# Stephen Bourke, NUI Galway, JIVE.

import aips_data_atts, ast_utils
import math

def shift_asec(dataset, ra, dec):
        """Returns the ra, dec shifts in arc-seconds to the specified position."""
        ra_0, dec_0 = aips_data_atts.ra(dataset), aips_data_atts.dec(dataset)
        return ast_utils.shift_asec(ra, dec, ra_0, dec_0)

def pixel_pos_deg(dataset, pixel=(0,0)):
        """Returns the position of the pixel specified.
        Result is in [hours, degrees]"""
        def newpos(ra0, dec0, l, m):
                # From AIPS NEWPOS
                sins = l*l + m*m
                cos0 = math.cos(dec0)
                sin0 = math.sin(dec0)
                coss = math.sqrt(1.0 - sins)
                dt = sin0 * coss + cos0 * m
                dect = math.asin(dt)
                rat = cos0 * coss - sin0 * m
                rat = math.atan2(l, rat) + ra0
                return rat, dect

        refpix_x, refpix_y = aips_data_atts.ref_pixel(dataset)
        pixinc_x, pixinc_y = aips_data_atts.pixel_inc_deg(dataset)
        refpix_ra = aips_data_atts.ra_deg(dataset)
        refpix_dec = aips_data_atts.dec(dataset)
        x,y = pixel

        # From AIPS COPIXEL
        dx = (x - refpix_x ) * pixinc_x
        dy = (y - refpix_y ) * pixinc_y

        a = refpix_ra
        b = refpix_dec

        dx, dy, a, b = [math.radians(x) for x in (dx, dy, a, b)]
        ra, dec = [math.degrees(x) for x in newpos(a, b, dx, dy)]
        ra = ra/15

        return ra, dec