


#include <stdio.h>
#include <math.h>
#include "bait.h"
#include "pf.h"
#include "multipht.h"

#define APER_POS   10		/* starting position of first "aper=" */
#define APER_LEN    7		/* length of "aper=4 " (add 1 if rad>9) */

	/* set the 'aper_rad[]' array values based up the aperture
	   sizes given by a COMMENT line in the .pht header. 
	   if the sizes cannot be determined, set them to -1 */

	/* fixed a bug Dick mentioned in 'pick_aper()'  6/8/92  MWR */

set_apertures(pfp)
pf_handle pfp;
{
	int i, naper, pos;
	char line[PF_LEN + 1];

	for (i = 0; i < MAX_APER; i++) {
		aper_rad[i] = -1;
	}

	naper = 0;
	while (pf_getcomment(pfp, line) != NULL) {
		pos = APER_POS;
		for (i = 0; i < MAX_APER; i++) {
			if (sscanf(line + pos, "aper=%d", &(aper_rad[i])) != 1)
				break;
			naper++;
			pos += APER_LEN;
			if (aper_rad[i] > 9)
				pos++;
		}
		if (naper > 0)
			break;
	}

	if (debug_flag) {
		printf("set_apertures: I found %d apertures\n", naper);
		for (i = 0; i < naper; i++)
			printf("aper[%d] = %d\n", i, aper_rad[i]);
	}

}

	/* for each star in the given image, set the zero'th element
	   of the 'mag[]' and 'err[]' arrays to the value in the
	   "correct" aperture.  The "correct" aperture is

	       a. the passed param 'aper', if it is >= 0
	    or
	       b. the aperture just larger than the average stellar fwhm
	    or
	       c. the largest aperture with data, if both a. and b. 
	             cannot be applied
	    or 
	       d. the zeroth aperture, if a. b. and c.
	             cannot be applied
	*/

pick_aper(im, aper)
struct s_image *im;
int aper;
{
	int i, j, naper, best;
	double avg;
	struct s_star *s;

	naper = 0;
	best = -1;
	for (i = 0; i < MAX_APER; i++) {
		if (aper_rad[i] > 0)
			naper = i;
	}
	avg = 0;
	for (i = 0; i < im->num_star; i++) {
		s = &(im->stars[i]);
		avg += s->fwhm;
	}
	avg = avg/(2.0*im->num_star);	/* convert FWHM diameter -> radius */
	for (j = 0; j <= naper; j++) {		/* fixed </<= bug from Dick 6/8/92 */
		if (aper_rad[j] >= avg) {
			best = j;
			break;
		}
	}
	if (naper < 0)
		naper = 0;

	if (debug_flag) {
		printf("in pick_aper: aper=%d, avg fwhm=%lf, best=%d\n", 
					aper, avg, best);
		if (aper >= 0)
			printf("  going to use aper=%d\n", aper);
		else if (best >= 0)
			printf("  going to use best=%d\n", best);
		else
			printf("  going to use naper=%d\n", naper);
	}
	
	if (aper >= 0)
		aper = aper;
	else if (best >= 0)
		aper = best;
	else
		aper = naper;

	for (i = 0; i < im->num_star; i++) {
		s = &(im->stars[i]);
		if (aper >= 0) {
			s->mag[0] = s->mag[aper];
			s->err[0] = s->err[aper];
			continue;
		}
		if (best >= 0) {
			s->mag[0] = s->mag[best];
			s->err[0] = s->err[best];
			continue;
		}
		s->mag[0] = s->mag[naper];
		s->err[0] = s->err[naper];
	}
}
