/**---------------------------------------------------------------------------
 ** 
 ** convert.c -- Miscellaneous conversion utilities
 ** 
 ** Author          : Pierre Jaccard
 ** Created On      : 1999/07/15 11:53:31
 ** Last Modified By: Pierre Jaccard
 ** Last Modified On: 1999/07/16 21:16:02
 ** Update Count    : 2
 ** Directory       : /home/pego/pcd1/codas3c/gfi/src/libs/misc/
 ** Version         : 0.0
 ** Status          : Unknown
 ** ---------------------------------------------------------------------- ** 
 ** DESCRIPTION: 
 ** 
 **    This file provides miscellaneous conversion functions.
 ** 
 ** ---------------------------------------------------------------------- ** 
 ** REVISIONS: 
 ** ---------------------------------------------------------------------- ** 
 ** CHANGES: 
 **------------------------------------------------------------------------**/

#include "convert.h"

/* ------------------------------------------------------------------
	 This function converts an array of double into an arry of LONG. In order
	 to lose the least information in this conversion, it looks at the largest
	 value in the array, and scales then all data so that the largest value
	 yields (MAXLONG-1). Bad values are set to MAXLONG.

	 RETURN: the scaling factor applied to the data.
	 ------------------------------------------------------------------ */
#if PROTOTYPE_ALLOWED
double double_to_long(/* Pointer to array of LONG */
                      LONG *dst, 
                      /* Pointer to array of DOUBLE */
                      DOUBLE *src, 
                      /* Number of elements in arrays */
                      int n)
#else
     double double_to_long(dst, src, n)
     LONG *dst;
     DOUBLE *src;
     int n;
#endif
{

	double max, r;
	int i;

	/* Get the maximal absolute value */
	max = MINFLOAT;
	for(i=0; i<n; i++){
		if(*(src+i) < ADJ_BADFLOAT)
			max = max_val( abs_val(*(src+i)), max);
	}

	/* Calculate the scaling factor */
	r = ((DOUBLE) (MAXLONG-1))/max;

	/* Fill the array of LONG */
	for(i=0; i<n; i++){
		if(*(src+i) < ADJ_BADFLOAT){
			*(dst+i) = (LONG) (*(src+i) * r);
			/* Be sure that it is not set to MAXLONG */
			if(*(dst+i) == MAXLONG)
				*(dst+i) -= 1;
		}
		else
			*(dst+i) = MAXLONG;
	}

	return(r);

}
