pro euvi_rot_loop,x,y,z,xrot,yrot,zrot
;+
; Project     : STEREO
;
; Name        : EUVI_ROT_LOOP 
;
; Category    : 3D Geometry 
;
; Explanation : This routine rotates an loop from image coordinates (x,y,z)
;	        into a loop coordinate system (xrot,yrot,zrot), with
;	        xrot aligned along loop baseline and zrot begin the vertical
;	        direction to solar surface, intersecting loop midpoint.
;		All coordinates in units of solar radii
;
; Syntax      : IDL> euvi_rot_loop,x,y,z,xrot,yrot,zrot 
;
; Inputs      : x	= array of x-coordinates of loop
;               y	= array of y-coordinates of loop
;               z	= array of z-coordinates of loop
;
; Outputs     : xrot	= array of x-coordinates in loop system
;               yrot	= array of y-coordinates in loop system
;               zrot	= array of z-coordinates in loop system
;
; History     : Jan 27, 2009, Version 1 written by Markus J. Aschwanden
;
; Contact     : aschwanden@lmsal.com
;-

;midpoint baseline
n	=n_elements(x)
x0	=(x(0)+x(n-1))/2.
y0	=(y(0)+y(n-1))/2.
z0	=(z(0)+z(n-1))/2.

;inclination angle
r	=sqrt(x^2+y^2+z^2)
hmax    =max(r-1.,im)                             ;hmax
xh      =x(im)
yh      =y(im)
zh      =z(im)
radius  =sqrt((xh-x0)^2+(yh-y0)^2+(zh-z0)^2)    ;loop radius
theta   =(180./!pi)*acos(hmax/radius)           ;loop inclination

;first rotation
dy	=(y(0)-y0)
dx	=(x(0)-x0)
d	=sqrt(dx^2+dy^2)
cosa	=dx/d
sina	=dy/d
xx	= (x-x0)*cosa+(y-y0)*sina
yy	=-(x-x0)*sina+(y-y0)*cosa
zz	= (z-z0)
alpha	=(180./!pi)*acos(cosa)

;second rotation
dz	=zz(n-1)-zz(0)
dx	=xx(n-1)-xx(0)
d	=sqrt(dx^2+dz^2)
cosb	=dx/d
sinb	=dz/d
xxx	= xx*cosb+zz*sinb 
yyy	= yy
zzz	=-xx*sinb+zz*cosb
beta	=(180./!pi)*asin(sinb)

;third rotation
ymax	=max(abs(yyy),im)	;corrected Dec 12, 2008 (for negative yyy)
if (im ne 0) then begin
 dy	=yyy(im)-yyy(0)
 dz	=zzz(im)-zzz(0)
 d	=sqrt(dy^2+dz^2)
 sinc	=dz/d
 cosc	=dy/d
 xrot	=xxx
 yrot	= yyy*cosc+zzz*sinc
 zrot	=-yyy*sinc+zzz*cosc
 gamma	=(180./!pi)*asin(sinc)
endif
if (im eq 0) then begin          ;no rotation (precludes sinc=NAN, cosc=NAN) 
 xrot	=xxx
 yrot	=yyy
 zrot	=zzz
endif
end
