# Licensed under a 2-clause BSD style license - see LICENSE.rst

"""
WCS-related utilities
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from astropy import units as u
from astropy.coordinates import UnitSphericalRepresentation
from astropy.wcs.utils import wcs_to_celestial_frame

__all__ = ['convert_world_coordinates']


def convert_world_coordinates(xw_in, yw_in, wcs_in, wcs_out):

    # Find input/output frames
    frame_in = wcs_to_celestial_frame(wcs_in)
    frame_out = wcs_to_celestial_frame(wcs_out)

    xw_in_unit = u.Unit(wcs_in.wcs.cunit[0])
    yw_in_unit = u.Unit(wcs_in.wcs.cunit[1])

    data = UnitSphericalRepresentation(xw_in * xw_in_unit,
                                       yw_in * yw_in_unit)

    coords_in = frame_in.realize_frame(data)
    coords_out = coords_in.transform_to(frame_out)

    xw_unit_out = u.Unit(wcs_out.wcs.cunit[0])
    yw_unit_out = u.Unit(wcs_out.wcs.cunit[1])

    xw_out = coords_out.spherical.lon.to(xw_unit_out).value
    yw_out = coords_out.spherical.lat.to(yw_unit_out).value

    return xw_out, yw_out


@@ -342,16 +342,44 @@
 al_frame
+%0Afrom astropy.wcs import WCS
 %0A%0A__all_
@@ -480,86 +480,682 @@
 t):%0A
-%0A    # Find input/output frames%0A    frame_in = wcs_to_celestial_frame(wcs_in)%0A
+    %22%22%22%0A    Convert world coordinates from an input frame to an output frame.%0A%0A    Parameters%0A    ----------%0A    xw_in, yw_in : %60~numpy.ndarray%60%0A        The input coordinates to convert%0A    wcs_in, wcs_out : tuple or %60~astropy.wcs.WCS%60%0A        The input and output frames, which can be passed either as a tuple of%0A        %60%60(frame, x_unit, y_unit)%60%60 or as a %60~astropy.wcs.WCS%60 instance.%0A    %22%22%22%0A%0A    if isinstance(wcs_in, WCS):%0A        frame_in = wcs_to_celestial_frame(wcs_in)%0A        xw_in_unit = u.Unit(wcs_in.wcs.cunit%5B0%5D)%0A        yw_in_unit = u.Unit(wcs_in.wcs.cunit%5B1%5D)%0A    else:%0A        frame_in, xw_in_unit, yw_in_unit = wcs_in%0A%0A    if isinstance(wcs_out, WCS):%0A    
     
@@ -1198,26 +1198,30 @@
 cs_out)%0A
-%0A
+    
     xw_
-in
+out
 _unit = 
@@ -1223,34 +1223,35 @@
 it = u.Unit(wcs_
-in
+out
 .wcs.cunit%5B0%5D)%0A 
@@ -1249,29 +1249,34 @@
 nit%5B0%5D)%0A    
-yw_in
+    yw_out
 _unit = u.Un
@@ -1274,34 +1274,35 @@
 it = u.Unit(wcs_
-in
+out
 .wcs.cunit%5B1%5D)%0A%0A
@@ -1295,24 +1295,88 @@
 cs.cunit%5B1%5D)
+%0A    else:%0A        frame_out, xw_out_unit, yw_out_unit = wcs_out
 %0A%0A    data =
@@ -1585,103 +1585,8 @@
 t)%0A%0A
-    xw_unit_out = u.Unit(wcs_out.wcs.cunit%5B0%5D)%0A    yw_unit_out = u.Unit(wcs_out.wcs.cunit%5B1%5D)%0A%0A
     
@@ -1625,23 +1625,23 @@
 n.to(xw_
-unit_ou
+out_uni
 t).value
@@ -1689,15 +1689,15 @@
 (yw_
-unit_ou
+out_uni
 t).v
@@ -1724,13 +1724,12 @@
 out, yw_out%0A
-%0A

Generalize convert_world_coordinates