#include <stdio.h>

#include "adltypes.h"
#include "adlprog.h"
#include "adlrun.h"

struct	macro
    *mactab;

void define( char *str1, char *str2 )
{
    struct macro
	*temp;

    temp = (struct macro *)calloc( sizeof( struct macro ), 1 );
    if( temp == (struct macro *)0 ) {
	error( ADLERR_MEMORY );
    }

    temp->next = mactab;
    mactab = temp;
    strncpy( mactab->name, str1, MLEN );
    strncpy( mactab->val, str2, SLEN );
}


int16 nummacro( void )
{
    int16
	count;
    struct macro
	*m;

    count = 0;
    for( m = mactab; m; m = m->next ) {
	count++;
    }
    return count;
}


void undef( char *str )
{
    struct macro
	*which,
	*last;

    if( !mactab ) {
	/* No macros defined */
	return;
    }

    if( !strcmp( mactab->name, str ) ) {
	/* First entry is the one we want */
	which = mactab;
	mactab = mactab->next;
	free( which );
	return;
    }

    /* Look for it in the rest of the table */
    which = mactab->next;
    last = mactab;
    while( which ) {
	if( !strcmp( which->name, str ) ) {
	    last->next = which->next;
	    free( which );
	    return;
	}
	last = which;
	which = which->next;
    }
}


char *expand( char *str )
{
  struct macro
	*which;

    which = mactab;
    while( which ) {
	if( !strcmp( which->name, str ) ) {
	    return which->val;
	}
	which = which->next;
    }
    return str;
}


void clearmacro( void )
{
    struct macro
	*which, *temp;

    which = mactab;
    while( which ) {
	temp = which->next;
	free( which );
	which = temp;
    }
    mactab = (struct macro *)0;
}

/*** EOF adlmacro.c ***/
