#include <math.h>
#include "wcs.h"
#include "tmat.h" 

#define FRDMIN  ( 180.0 * 60.0 / M_PI )

void calc_xy( double alpha_c, double delta_c, double alpha, double delta, double *wcs_x, double *wcs_y )
{ 
	double	theta1, dx, dy ; 
	double	x[3], y[3], r[9] ;
	double  eps = 1.0e-10 ;
/*
	float	xp, yp ; 
	int	lw, symbol ;
	float	ch ; 
*/ 

/* Transform coordinates */ 

	txexyz( alpha, delta, x ) ; 
	rotmat( 3, alpha_c + M_PI/2.0, r ) ; 
	mult0( r, x, y ) ;
	rotmat( 1, M_PI/2.0 - delta_c, r ) ; 
	mult0( r, y, x ) ;
	theta1 = adist( alpha_c, delta_c, alpha, delta ) ; 
/* 
	printf( "theta1 = %12.9f\n", theta1*FRDEG ) ;  
	printf( "x = %12.9f y = %12.9f z = %12.9f \n", x[0], x[1], x[2] ) ;  
*/ 
	if ( theta1 >= eps ) { 
		x[0] = x[0] / cos( theta1 ) ; 
		x[1] = x[1] / cos( theta1 ) ; 
		x[2] = x[2] / cos( theta1 ) ; 
	} 
	else { 
		x[0] = 0.0 ; 
		x[1] = 0.0 ; 
		x[2] = 1.0 ; 
	} 

/* 
	printf( "x = %12.9f y = %12.9f z = %12.9f \n", x[0], x[1], x[2] ) ;  
*/ 
	dx = FRDMIN * x[0] ; 
	dy = FRDMIN * x[1] ; 

	if ( theta1 > M_PI/2.0 ) { 
		dx = 5400.0 ; 
		dy = 5400.0 ; 
	} 

	*wcs_x = dx ; 
	*wcs_y = dy ; 

/* 
	return 0 ; 
*/ 
}

double adist( double alpha1, double delta1, double alpha2, double delta2 ) 
{ 
	double	x1, y1, z1, x2, y2, z2 ; 
	double	cos_theta, theta ; 
	double	eps = 1.0e-15 ; 

	x1 = cos( delta1 ) * cos( alpha1 ) ; 
	y1 = cos( delta1 ) * sin( alpha1 ) ; 
	z1 = sin( delta1 ) ; 
	x2 = cos( delta2 ) * cos( alpha2 ) ; 
	y2 = cos( delta2 ) * sin( alpha2 ) ; 
	z2 = sin( delta2 ) ; 
	cos_theta = x1 * x2 + y1 * y2 + z1 * z2 ; 
	if ( fabs( 1.0 - cos_theta ) <= eps ) { 
		theta = 0.0 ; 
	} 
	else { 
		theta = acos( cos_theta ) ; 
	} 

	return theta ; 
} 

