/* lksym.c */

/*
 * (C) Copyright 1989,1990
 * All Rights Reserved
 *
 * Alan R. Baldwin
 * 721 Berkeley St.
 * Kent, Ohio  44240
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/* #include <alloc.h> */
#include "aslink.h"

/*
 * This routine is called early in the
 * game to set up the symbol hashtable.
 */
VOID
modinit()
{
	struct mod **mpp;

        mpp = &modhash[0];
	while (mpp < &modhash[NHASH])
		*mpp++ = NULL;
}

/*
 * Find/Create a global symbol entry.
 *
 * S xxxxxx Defnnnn
 *   |      |  |
 *   |      |  `-- sp->s_addr
 *   |      `----- sp->s_type
 *   `------------ sp->s_id
 *
 */
struct mod *
newmod()
{
	struct mod *tsp;
	char id[NCPS];

	getid(id, -1);
	tsp = lkpmod(id, 1);

	/*
	 * Place pointer in header symbol list
	 */

/*	if (headp == NULL) {
		fprintf(stderr, "No header defined\n");
		exit(1);
	}
	nglob = hp->h_nglob;
	s = hp->s_list;
	for (i=0; i < nglob ;++i) {
		if (s[i] == NULL) {
			s[i] = tsp;
			return(tsp);
		}
	}
	fprintf(stderr, "Header symbol list overflow\n");
	exit(1);
*/
   	return (tsp);
}

/*
 * Lookup the name `id' in the hashtable.
 * If it is not found either return a
 * `NULL' (`f' is false) or a
 * pointer to a newly created hash table
 * entry (`f' is true).
 */
struct mod *
lkpmod(id, f)
char *id;
int f;
{
	register struct mod *sp;
	register int h;

	h = hash(id);
	sp = modhash[h];
	while (sp != NULL) {
		if (symeq(id, sp->m_id))
			return (sp);
		sp = sp->m_mp;
	}
	if (f == 0)
		return (NULL);
	sp = (struct mod *) new (sizeof(struct mod));
	sp->m_mp = modhash[h];
        modhash[h] = sp;
	strncpy(sp->m_id, id, NCPS);
	return (sp);
}



/*
 * Compare two symbol names.
 */

/*
int
symeq(p1, p2)
register char *p1, *p2;
{
	register n;

	n = NCPS;
	do {

#if	CASE_SENSITIVE
		if (*p1++ != *p2++)
			return (0);
#else
		if (ccase[*p1++] != ccase[*p2++])
			return (0);
#endif

	} while (--n);
	return (1);
}
*/

int chksym()
{
	char id[NCPS];
        char c;

	getid(id, -1);

   	c = getnb();
        
        if ( c == 'R' )
           	return 0;
        else if ( c == 'D' ) {
           	if ( !lkpsym( id, 0 ) )
                   	return 0;
                else
                   	return 1;
        }
        else {
           	fprintf( stderr, "Illegal symbol type %c for %.8s\n", c, id );
                exit(1);
        }
   	
}


int remmod( char * id )
{
	struct mod *sp, *psp;
        int h;

	h = hash(id);
	sp = modhash[h];
        
        if ( sp == NULL )
           return 0;
        
        if ( symeq(id, sp->m_id) ) {
           	modhash[h] = sp->m_mp;
                free( sp );
                return 1;
        }
        
        psp = sp;
        sp = sp->m_mp;
        
	while (sp != NULL) {
		if (symeq(id, sp->m_id))
                {
                	psp->m_mp = sp->m_mp;
                        free( sp );
			return (1);
                }
                psp = sp;
		sp = sp->m_mp;
	}
        
        
        return 0;
}
