/* $VER: WBStars_libraries.c 2.07 (14 Apr 1998)
*/

#include <exec/types.h>
#include <exec/io.h>
#include <exec/memory.h>
#include <devices/timer.h>

#include <proto/exec.h>
#include <clib/alib_protos.h>
#include <proto/dos.h>

#include "WBStars_include.h"
#include "WBStars_protos.h"

struct IntuitionBase	*IntuitionBase=NULL;
struct GfxBase		*GfxBase=NULL;
struct Library		*CxBase=NULL;
struct Library		*IconBase=NULL;
struct Library		*LayersBase=NULL;
struct Library		*TimerBase;
char OS3=FALSE;

struct timerequest *tr;

void delete_timer(struct timerequest *tr );
struct timerequest *create_timer( ULONG unit );

char	OpenLibraries()		/* opens all needed libraries	*/
{				/* returns TRUE on success	*/
	IntuitionBase	=(struct IntuitionBase*)OpenLibrary("intuition.library",0L);
	CxBase		=OpenLibrary("commodities.library",37L);
	IconBase	=OpenLibrary("icon.library",36L);
	LayersBase	=OpenLibrary("layers.library",0L);
	if(GfxBase	=(struct GfxBase*)OpenLibrary("graphics.library",39L))
		{OS3=TRUE;}else
		{GfxBase=(struct GfxBase*)OpenLibrary("graphics.library",0L);}

	tr		= create_timer( UNIT_MICROHZ );
	TimerBase	= (struct Library *)tr->tr_node.io_Device;

	if( !IntuitionBase || !GfxBase || !CxBase || !IconBase || !LayersBase || !TimerBase)
	{
		return FALSE;
	}
	return TRUE;
}

void	CloseLibraries()	/* closes all opened libraries	*/
{
	if(IntuitionBase)	CloseLibrary((struct Library*)IntuitionBase);
	if(GfxBase)		CloseLibrary((struct Library*)GfxBase);
	if(CxBase)		CloseLibrary(CxBase);
	if(IconBase)		CloseLibrary(IconBase);
	if(LayersBase)		CloseLibrary(LayersBase);
	TimerBase = (struct Library *)(-1);
	delete_timer( tr );

}

struct timerequest *create_timer( ULONG unit )
{
	/* return a pointer to a timer request.  If any problem, return NULL */
	LONG			error;
	struct MsgPort		*timerport;
	struct timerequest	*TimerIO;

	timerport	= CreatePort( 0, 0 );

	if( timerport==NULL )
	    return NULL;

	TimerIO		= (struct timerequest *)CreateExtIO( timerport, sizeof( struct timerequest ) );
	if( TimerIO==NULL )
	{
		DeletePort(timerport);   /* Delete message port */
		return NULL;
	}

	error		= OpenDevice( TIMERNAME, unit,(struct IORequest *) TimerIO, 0L );
	if( error!=0 )
	{
		delete_timer( TimerIO );
		return NULL;
	}
	return TimerIO;
}

void delete_timer(struct timerequest *tr )
{
	struct MsgPort *tp;

	if( tr!=0 )
	{
		tp	= tr->tr_node.io_Message.mn_ReplyPort;

		if( tp!=0 )
			DeletePort(tp);

		CloseDevice( (struct IORequest *) tr );
		DeleteExtIO( (struct IORequest *) tr );
	}
}
