#ifdef MSDOS
#include <dos.h>
#include <errno.h>
#include <alloc.h>

#define USEHMA 1
#ifdef USEHMA

int weOwnHMA = 0;
static short a20State = 0;

#ifdef	LARGEDATA
#define	HUGE	huge
#else
#define	HUGE
#endif

union header {
	struct {
		union header HUGE *ptr;
		unsigned long size;
	} s;
	long l[2];
};

typedef union header HEADER;
#define	ABLKSIZE	(sizeof (HEADER))
extern unsigned long Frees;	/* Total frees */
extern unsigned long Heapsize;

int
initHMA()
{
HEADER HUGE *up;
unsigned nu;

	xms_init();
	errno = 0;
	xms_allocHMA (0xFFFF);
	if (!errno)	{
		weOwnHMA = 1;
		up = (HEADER HUGE *) MK_FP (0xffff, 0x0010);
		xms_getA20State (&a20State);
		if (!a20State)
			xms_globEnabA20();
		nu = 65520 / ABLKSIZE;
		up->s.size = nu;
		up->s.ptr = up;	/* satisfy audit */
		free((void *)(up + 1));
		Heapsize += nu*ABLKSIZE;
		Frees--;	/* Nullify increment inside free() */
	}
	return weOwnHMA;
}


void
termHMA ()
{
	if (weOwnHMA)	{
		if (!a20State)
			xms_globDisabA20();	
		xms_freeHMA ();
	}
}	


void
hmastat ()
{
	tprintf ("High Memory Area is %sowned by TNOS", weOwnHMA ? "" : "NOT ");
	if (weOwnHMA)
		tprintf (" - Extra 64K in use");
	tputc ('\n');
}
#endif

#endif /* MSDOS */
