
/**************************************************************************
 *                                                                        *
 * Copyright (c) 1996 Michael Richmond and Richard Treffers               *
 *                                                                        *
 *                    This software may be copied and distributed for     *
 *                    educational, research and not for profit services   *
 *                    provided that this copyright and statement are      *
 *                    included in all such copies.                        *
 *                                                                        *
 **************************************************************************/


/*
	automatically sets span and zero for image files.
	it samples the image at a number of randomly-selected
	points, finding maximum and minimum pixel values.

	    'zero' is set to the median value
	    'span' is set to (maximum-median)

	revised by MWR 10/17/1991
	scramble changed- so DATA_MAX goes to INT_MAX -2/15/92 -RRT

	increased NDARTS from 50  and changed *pzero (see below)
	also fixed compar
	RRT 10/28/92 

	4/20/94 INT_MAX --> RAND_MAX  if it is defined
*/

#include <stdio.h>
#include <math.h>
#include <stdlib.h> /* to get RAND_MAX */
#include <time.h>
#include "pcvista.h"
#include "fits.h"

/* and if it isn't */
#ifndef RAND_MAX
#include <limits.h>
#define RAND_MAX INT_MAX
#endif

#ifdef PROTO
static double scramble(void);
static void sort(int16 *);
#else	/* PROTO */
static double scramble();
#endif

#define NDARTS 250		/* number of randomly-sampled points */

extern int image_max_color;

void 
autospan(fh, pspan, pzero, sr, sc, nr, nc)
FITS_HANDLE fh;
int *pspan;
int *pzero;
int sr, sc, nr, nc;
{
	int i, row, col;
	int16 data[NDARTS];

	i = time((time_t *) NULL);
	srand(i);
	for (i = 0; i < NDARTS; i++) {
		row = sr + (int)(nr*scramble());
		col = sc + (int)(nc*scramble());	
		fits_get_data(fh, row, col, &(data[i]), 1);
	}

	/* this is the new version.  MWR 10/17/1991 */
	/* changed from NDARTS/2 --> 0.1*NDARTS RRT 12/28/92 */
	sort(data);

	*pzero = data[(int)NDARTS/10];
	*pspan = data[NDARTS-1] - *pzero;

	/* 
	 * this is the old version 
	 * 	*pspan = max - min;
	 * 	*pzero = min;
	 */
	
	if (*pspan <= image_max_color)
		*pspan = image_max_color + 1;
}

	/* sort the data values */

static void
sort(data)
int16 data[];
{
	int compar();

	qsort((char *) &(data[0]), NDARTS, sizeof(int16), compar);
}

	/* return 1 if the first value is greater, -1 if the second, 0 if
	   they are equal */

int
compar(a, b)
int16 *a, *b;
{
	if (*a > *b) 
		return(1);
	else if (*a < *b) 
		return(-1);
	else
		return(0);
}


static double 
scramble()		/* returns 0 to 1.0 */
{
	double val;
	val=(double)rand();

	return(val /(double)RAND_MAX);
}
