/*
 *   DIS/x : An implementation of the IEEE 1278.1 protocol
 *
 *   Copyright (C) 1996, Riley Rainey (rainey@netcom.com)
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of either:
 *
 *   a) the GNU Library General Public License as published by the Free
 *   Software Foundation; either version 2 of the License, or (at your
 *   option) any later version.  A description of the terms and conditions
 *   of the GLPL may be found in the "COPYING.LIB" file.
 *
 *   b) the "Artistic License" which comes with this Kit.  Information
 *   about this license may be found in the "Artistic" file.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *   Library General Public License or the Artistic License for more details.
 *
 *   You should have received a copy of the GNU Library General Public
 *   License along with this library; if not, write to the Free
 *   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *   Information describing how to contact the author can be found in the
 *   README file.
 */
#ifdef HAVE_NDBM
#include <ndbm.h>
#else
#include <sdbm.h>
#endif
#include <dis/dis.h>
#include <sys/file.h>
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <string.h>
#include <memory.h>
#include <stdio.h>

DBM *entities;

int
OpenDatabase ()
{
	entities = dbm_open ("dis-entities", O_RDONLY, 0644);
	if (!entities) {
		entities = dbm_open ("../data/dis-entities", O_RDONLY, 0644);
		if (!entities) {
		    fprintf (stderr, "Unable to open dis-entities database\n");
		    fprintf (stderr, "Perhaps simxd was run from the wrong directory\n");
		    exit (1);
		}
	}
	return 0;
}

int
FetchEntity (dis_entity_type *id, char *s, int size)
{
	datum	key, value;
	int	i;

	key.dptr = (char *) id;
	key.dsize = sizeof (dis_entity_type);

	value = dbm_fetch (entities, key);
	if (value.dptr) {
		memcpy (s, value.dptr, size);
		-- size;
		i = value.dsize > size ? size : value.dsize;
		s[i] = '\0';
		return 0;
	}
	return -1;
}

/*
 *  Under construction.
 */

int
FindEntity (char * pattern, dis_entity_type * match,
	char * s, int size)
{
	datum	key, value;
	char	*p;
	int	len;
	static	char *pat;

	if (pattern) {
	    key = dbm_firstkey (entities);
	    if (pat) {
	    	free (pat);
	    }
	    pat = strdup (pattern);
	}
	else {
	    key = dbm_nextkey (entities);
	}
	
	len = strlen(pat);
	
	for ( ; key.dptr ; key = dbm_nextkey(entities)) {
	    value = dbm_fetch (entities, key);
	    if ((p = strchr (value.dptr, *pattern)) != NULL) {
		if (strncasecmp (p, pattern, len) == 0) {
			memcpy (key.dptr, match,
				sizeof (dis_entity_type));
			strncpy (s, value.dptr, size);
			return 1;
		}
	    }
	}

	*s = '\0';
	return 0;
}
