/* packxe2.c -- create an xe2 record from star data */
/*
Copyright 2000, Steve VanDevender <stevev@hexadecimal.uoregon.edu>
Permission is granted to redistribute source code for this program if
and only if all of the following conditions are met:

1.  This copyright notice must not be removed or modified.
2.  Any changes you make to this source code must be documented.
3.  Binary versions must be distributed with complete source code.
4.  No money will be charged for distribution of binaries or source code.
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "packxe2.h"

/* If you can't figure out what goes in an xe2 record from the code
   below, see E. C. Downey's comment at the top of
   xephem-3.4/GUI/xephem/xe2.c */
int packxe2(struct xe2data *in, unsigned char *xe2)
{
	unsigned long conv;
	
	xe2[0] = ((in->typecode & 7) << 3) + (in->namecode & 7);
	if (in->namecode == TYCHO2) {
		/* magic happens */
		xe2[1] = in->num2 >> 8;
		xe2[2] = in->num2;
		xe2[3] = in->num1 >> 6;
		xe2[4] = ((in->num1 & 0x3f) << 2) + (in->num3 & 3);
	}
	else {
		/* just pack the catalog number */
		xe2[1] = in->num1 >> 24;
		xe2[2] = in->num1 >> 16;
		xe2[3] = in->num1 >> 8;
		xe2[4] = in->num1;
	}
	if (in->ra < 0.0 || in->ra >= 24.0) {
		fprintf(stderr, "RA out of range: %g\n", in->ra);
		return 0;
	}
	conv = (in->ra / 24.0) * 16777216L;
	xe2[5] = conv >> 16;
	xe2[6] = conv >> 8;
	xe2[7] = conv;
	if (in->dec < -90.0 || in->dec > 90.0) {
		fprintf(stderr, "Dec out of range: %g\n", in->dec);
		return 0;
	}
	conv = ((in->dec + 90.0) / 180.0) * 16777215L;
	xe2[8] = conv >> 16;
	xe2[9] = conv >> 8;
	xe2[10] = conv;
	if (in->mag < -2.0 || in->mag > 17.0) {
		fprintf(stderr, "Mag out of range: %g\n", in->mag);
		return 0;
	}
	conv = (in->mag + 2.0) / 19.0 * 255;
	xe2[11] = conv;
	xe2[12] = in->sc[0];
	xe2[13] = in->sc[1];
	if (in->pmra < -16384.0 || in->pmra > 16383.5) {
		fprintf(stderr, "pmRA out of range: %g\n", in->pmra);
		return 0;
	}
	conv = (2.0 * in->pmra) + 32768;
	xe2[14] = conv >> 8;
	xe2[15] = conv;
	if (in->pmdec < -16384.0 || in->pmdec > 16383.5) {
		fprintf(stderr, "pmDec out of range: %g\n", in->pmdec);
		return 0;
	}
	conv = (2.0 * in->pmdec) + 32768;
	xe2[16] = conv >> 8;
	xe2[17] = conv;
	return 1; /* phew */
}


