
/*
 * GENCAT_PPMX2 - Generate PPMX catalog (second phase)
 * Made by Daniel E. Severin (CONICET) in 2015-2017
 */

#include "common.h"
#include <unordered_map>

struct PPMXstar_struct *PPMXstar;
int PPMXstars; /* number of PPMX stars */

/*
 * main
 */
int main(int argc, char** argv)
{
	FILE *stream;
	char buffer[1024];
	char cell[256];

	printf("GENCAT_PPMX2 - Generate PPMX catalog (second phase).\n");
    printf("Made by Daniel E. Severin (CONICET) in 2015-2017.\n");

	/* read PPMX data */
	stream = fopen("ppmx_data.bin", "rb");
	if (stream == NULL) {
		perror("Error reading bin file");
		exit(1);
	}
	fread(&PPMXstars, sizeof(int), 1, stream);
	PPMXstar = (struct PPMXstar_struct *)calloc(PPMXstars, sizeof(struct PPMXstar_struct));
	fread(PPMXstar, sizeof(struct PPMXstar_struct), PPMXstars, stream);
	fclose(stream);

    /* read Xmatch cross-table between PPMX and APASS */
	stream = fopen("tables\\xmatch_apass.dat", "rt");
	if (stream == NULL) {
		perror("Error reading Xmatch file");
		exit(1);
	}

	fgets(buffer, 1023, stream); /* discard the first line */

	while (fgets(buffer, 1023, stream) != NULL) {
		/* read PPMX ident. number */
		readfield(buffer, cell, 36, 6);
		int ppmx_id = atoi(cell);

		/* read Vmag */
		readfield(buffer, cell, 129, 6);
		float vmag = 15.0;
		if (cell[0] != ' ') vmag = atof(cell);

		/* update Vmag in PPMX only if it is brighter than current
		 * (if there are two APASS stars for the same PPMX star, keep the brightest one) */
		if (vmag < PPMXstar[ppmx_id].vmag) {
			PPMXstar[ppmx_id].vmag = vmag;
			PPMXstar[ppmx_id].Vmag_assigned = true;
		}
	}
	fclose(stream);

	/* now, compute magnitudes in CD scale */
	for (int i = 0; i < PPMXstars; i++) {
		if (PPMXstar[i].Vmag_assigned == false) {
			/* if the magnitude is not yet assigned for this star, use V = C+1.5 (although it is somewhat "arbitrary", is better than assigning a constant magnitude) */
			float vmag = PPMXstar[i].cmag + 1.5;
			printf("Warning: star PPMX %s without V magnitude, assigning Cmag+1.5 = %.2f by default\n", PPMXstar[i].ppmx_name, vmag);
			PPMXstar[i].vmag = vmag;
		}
		PPMXstar[i].mag = convert_V(PPMXstar[i].vmag);
	}

	/* finally, write again PPMX data */
	stream = fopen("ppmx_data.bin", "wb");
	if (stream == NULL) {
		perror("Error creating bin file");
		exit(1);
	}
	fwrite(&PPMXstars, sizeof(int), 1, stream);
	fwrite(PPMXstar, sizeof(struct PPMXstar_struct), PPMXstars, stream);
	fclose(stream);

	free(PPMXstar);
	return 0;
}
