/* ppmxe2.c -- process PPM catalog data into an xe2 file */
/*
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 "readcat.h"
#include "packxe2.h"

unsigned char ppmxe2[470000][XE2SIZE]; /* urp */

/* helper function for qsort, compares xe2 record declination field */
static int sortxe2(unsigned char *e1, unsigned char *e2)
{
	if (e1[8] > e2[8]) return 1;
	if (e1[8] < e2[8]) return -1;
	if (e1[9] > e2[9]) return 1;
	if (e1[9] < e2[9]) return -1;
	if (e1[10] > e2[10]) return 1;
	if (e1[10] < e2[10]) return -1;
	return 0;
}

int main(int argc, char *argv[])
{
	FILE *ppm;
	char line[256];
	struct xe2data in;
	unsigned long n;

	ppm = fopen("ppm.dat", "r");
	if (ppm == 0) {
		fprintf(stderr, "can't open ppm.dat\n");
		return 1;
	}
	printf("Reading PPM catalog data from ppm.dat ...\n");

	n = 0;
	while (fgets(line, sizeof(line), ppm) != 0) {
		char c, sc[3];
		long rah, ram, ded, dem;
		double ras, des;

		in.namecode = PPM;
		get_integer(line, 2, 7, &in.num1);
		get_char(line, 128, &c);
		if (c == 'D') in.typecode = DOUBLE;
		else in.typecode = STAR;
		get_integer(line, 28, 29, &rah);
		get_integer(line, 31, 32, &ram);
		get_fp(line, 34, 39, &ras);
		in.ra = rah + ram / 60.0 + ras / 3600.0;
		get_integer(line, 43, 44, &ded);
		get_integer(line, 46, 47, &dem);
		get_fp(line, 49, 53, &des);
		in.dec = ded + dem / 60.0 + des / 3600.0;
		get_char(line, 42, &c);
		if (c == '-') in.dec = -in.dec;
		get_fp(line, 20, 23, &in.mag);
		get_string(line, 25, 26, sc);
		in.sc[0] = in.sc[1] = ' ';
		if (sc[0] != '\0') in.sc[0] = sc[0];
		if (sc[1] != '\0') in.sc[1] = sc[1];
		get_fp(line, 56, 62, &in.pmra);
		in.pmra *= 15000.0 * cos(in.dec * M_PI/180.0); /* convert to mas/yr*cos(dec) */
		get_fp(line, 64, 69, &in.pmdec);
		in.pmdec *= 1000.0; /* convert to mas/yr */
		/* pack this into an xe2 structure */
		if (packxe2(&in, ppmxe2[n])) {
			n++;
			if (n % 1000 == 0) printf("%ld\r", n);
		}
	}
	fclose(ppm);
	printf("%ld PPM records.\n", n);

	printf("Sorting data ...\n");
	/* sort all records by declination value */
	qsort(ppmxe2[0], n, XE2SIZE, sortxe2);

	printf("Writing output file ppm1.xe2.\n");
	ppm = fopen("ppm1.xe2", "wb");
	fprintf(ppm, "XE2.\n");
	fwrite(ppmxe2[0], XE2SIZE, n, ppm);
	fclose(ppm);
	return 0;
}
