/**---------------------------------------------------------------------------
 ** 
 ** misc.c -- Miscellaneous utilities
 ** 
 ** Author          : Pierre Jaccard
 ** Created On      : 1999/07/15 11:22:01
 ** Last Modified By: Pierre Jaccard
 ** Last Modified On: 1999/07/16 21:20:55
 ** Update Count    : 2
 ** Directory       : /home/pego/pcd1/codas3c/gfi/src/libs/misc/
 ** Version         : 0.0
 ** Status          : Unknown
 ** ---------------------------------------------------------------------- ** 
 ** DESCRIPTION: 
 ** 
 **    This file provides functions that do not fit yet elsewhere. 
 ** 
 ** ---------------------------------------------------------------------- ** 
 ** REVISIONS: 
 ** ---------------------------------------------------------------------- ** 
 ** CHANGES: 
 **------------------------------------------------------------------------**/

#include "misc.h"

/* ------------------------------------------------------------------
   Given an ULONG, this procedure returns the number of the first non-zero
   bit, starting from zero. ¨

   RETURNS: -1 if the parsed bits are all zero, or the first encountered bit
            that is non-zero.
	------------------------------------------------------------------ */

#if PROTOTYPE_ALLOWED
int get_bit_number(/* Long bit to parse */
                   ULONG flagg)
#else
int get_bit_number(flagg)
ULONG flagg;
#endif
{

	int n=0;

	/* Avoid infinite loops */
	if(flagg == 0) return(-1);

	/* Shift right until bit 0 is non-zero */
	while((flagg & BIT0) == 0){
		flagg >>= 1;
		n++;
	}

	return(n);
}

/* ------------------------------------------------------------------
	Given a reference angle and an angle, both in degrees but not necessary
	between 0 and 360, this function returns the corresponding nearest value of
	angle relative to the reference angle. 

  RETURNS: the new angle
	------------------------------------------------------------------ */
#if PROTOTYPE_ALLOWED
double nearest_angle(/* Reference angle */
                     double ref_angle, 
                     /* Current angle */
                     double angle)
#else
double nearest_angle(ref_angle, angle) 
double ref;
double angle;
#endif
{

	double ref, alpha, d1, d2;

	/* Convert angles into range 0..360 */
	ref = ((int) ref_angle)%360 + (ref_angle - (int) ref_angle);
	ref = (ref<0) ? ref+360.0 : ref;
	alpha = ((long) angle)%360 + (angle - (long) angle);
	alpha = (alpha<0) ? alpha+360.0 : alpha;

	/* Difference between angles, along both circular directions */
	d1 = alpha - ref;
	d2 = 360.0 - abs_val(d1);
	
	/* Select direction for shortest difference and recalculate angle */
	if(abs_val(d1) <= (d2))
		alpha = ref_angle + d1;
	else if (d1<=0) 
		alpha = ref_angle + d2;
	else
		alpha = ref_angle - d2;

	return(alpha);
}

