/************************************************************************
 *	TITLE:			JAZUTIL.C					*
 *	PROJECT:		JAGUAR/JAZ				*
 *	FUNCTION:		MAIN JAZ MODULE				*
 *	PROGRAMMER:		Andreas Binner			*
 *	DATE:			5/95					*
 *									*
 *              COPYRIGHT 1993,1994 Atari U.S. Corporation              *
 *          UNATHORIZED REPRODUCTION, ADAPTATION, DISTRIBUTION,         *
 *          PERFORMANCE OR DISPLAY OF THIS COMPUTER PROGRAM OR          *
 *        THE ASSOCIATED AUDIOVISUAL WORK IS STRICTLY PROHIBITED.       *
 *                            ALL RIGHTS RESERVED.                      *
 *									*
 ************************************************************************/

#include "portab.h"
#include "jazutil.h"
#include "tunes.h"

LONG log_dual(ULONG v)
{
	LONG l;
	
	l=0;
	v>>=1;
	while (v>=0x1000)
	{
		v>>=1;
		l++;
	}
	
	return(l);
}

LONG log_dual_r(ULONG v)
{
	LONG l;
	
	l=1;
	v<<=1;
	while (v<0x1000)
	{
		v<<=1;
		l++;
	}
	
	return(l);
}

LONG log_tune(LONG v)
{
	LONG l;
	
	l=0;
	while (tunes[l]<=v && l<12)
		l++;
		
	return(l-1);
}

/******************************************/
/* Octave:  -5 to 5                       */
/* Halfstep: 0 to 11                      */
/* Fine:     0 to 243                     */
/******************************************/
 
ULONG ohf2tune(LONG o,LONG h,LONG f)
{
	ULONG tv;
	
	if (o>=0)
		tv = 0x1000L<<o;
	else
		tv = 0x1000L>>(-o);

	tv = (tv * tunes[h]) / 4096L;

	tv = (tv * (f+4096L)) / 4096L;

	return tv;
}


VOID tune2ohf (ULONG tune,LONG *po,LONG *ph,LONG *pf)
{
	LONG o,h,f;
	
	if (tune>=0x1000)
	{
		o=log_dual(tune);
		tune/=(1L<<o);
		h=log_tune(tune);
		tune=(tune*0x1000)/tunes[h];
		f=tune-4096L;
	}
	else
	{
		o=log_dual_r(tune);
		tune*=(1L<<o);
		h=log_tune(tune);
		tune=(tune*0x1000)/tunes[h];
		f=tune-4096L;
		o=-o;
	}
	*po=o;
	*ph=h;
	*pf=f;
}