#include <stdio.h>
#include "utype.h"
#include "umem.h"
#include "if.h"
#include "input.h"
#include "parser.h"
#include "register.h"
#include "macros.h"

extern short *bufptr;
extern HASHREC **hashtable;

BOOL ifskip = FALSE;
LIST *iflist = 0;

static BOOL definedmacro(void)
{
	short buf[200], *p = buf;
	BOOL rv;
	skipSpace(&bufptr);
	
	while(*bufptr && !iswhitespacechar(*bufptr))
		*p++ = *bufptr++;
	bufptr++;
	*p = 0;

	rv = (FindMacro(buf) != 0);
	skipSpace(&bufptr);
	if (*bufptr)
		Extraneous();
	return(rv);
}
static void BadIf(void)
{
	if (!iflist)
		Error("Missing !if");
}
static void ifpush(BOOL flag)
{
	LIST *h = AllocateMemory(sizeof(LIST));
	h->data = (void *) ifskip;
	h->link = iflist;
	iflist = h;
	ifskip = !flag;
}
static void ifpop(void)
{
	LIST *h = iflist;
	BadIf();
	iflist = h->link;
	ifskip = (BOOL)(h->data);
	DeallocateMemory(h);
}
void ifdef(void)
{
	ifpush(definedmacro());
}
void ifndef(void)
{
	ifpush(!definedmacro());
}
void ifelse (void)
{
	BadIf();
	ifskip = !ifskip;
}
void ifendif(void)
{
	ifpop();
}