/* $Id: preload.c,v 1.3 1997/06/27 12:41:56 archer Exp $
 *	PRELOAD.C - Pre-load data files
 */
#include "lorenai.h"
#include "misc.h"
#include <string.h>
#include <ctype.h>


/**
 ** Special prototypes
 **/
extern void read_map(char *);


/**
 ** Local variables
 **/
ttype_s	unknown_area_type;


/**
 ** Internal: PRE_LOAD_AREA
 **	Figure out the types of the area and other relevant info
 **/
static void pre_load_area(char *name)
{
ttype_s	*t;
char	*s, *e;
FILE	*f;
/*
 * Pre-allocate "unknown"
 */
	unknown_area_type.name = "unknown";
	unknown_area_type.worldview = X11_ColorByName("gray80", 0);
	unknown_area_type.move      = 20;
/*
 * Any cache file?
 */
	if ((f = fopen(name, "r")) == 0)
		return;
	while (file_gets(f)) {
		if (!isalpha(work[0]))
			continue;
/*
 * Find out the word
 */
		for (s = work; *s; s++)
			if (*s == '\t')
				break;
		if (*s)
			*s++ = 0;
		for (t = area_types; t; t = t->next)
			if (strcmp(t->name, work) == 0)
				break;
/*
 * Uh oh! An unknown terrain type!
 */
		if (!t) {
			t = (ttype_s *)malloc(sizeof(*t));
			*t = unknown_area_type;
			t->next = area_types;
			area_types = t;
			t->name = strdup(work);
		}
/*
 * Fill in the color
 */
		while (isspace(*s))
			s++;
		for (e = s; *e; e++)
			if (*e == '\t')
				break;
		if (*e)
			*e++ = '\0';
		t->worldview = X11_ColorByName(s, t->worldview);
		while (isspace(*e))
			e++;
		t->move = atoi(e);
/*** HACK ***/
	}
}


/**
 ** PRE_LOAD_ITEMS
 **	Figure out the types of items
 **/
static void pre_load_items(char *name)
{
FILE	*f;
item_s	*i;
char	*s, *e;
char	man = 0;
/*
 * Any cache file?
 */
	if ((f = fopen(name, "r")) == 0)
		return;
	while (file_gets(f)) {
/*
 * Special hints
 */
		if (strncmp(work, "# Men", 5) == 0)
			man = 1;
		if (strncmp(work, "# Item", 6) == 0)
			man = 0;
		if (!isalpha(work[0]))
			continue;
		if ((s = strchr(work, '/')) == 0)
			continue;
/*
 * Valid item entry
 */
		*s++ = '\0';
		if ((e = strchr(s, '\t')) != 0)
			*e++ = '\0';
/*
 * Allocate the item entry
 */
		i = (item_s *)malloc(sizeof(*i));
		i->next = known_items;
		known_items = i;
		i->singular = strdup(work);
		i->plural   = strdup(s);
		i->man      = man;
		if (man && strcmp(s - 7, "leader") == 0)
			i->leader = 1;
	}
}


/**
 ** PRE_LOAD
 **	Load the various data files around
 **/
void pre_load(void)
{
/*
 * Pre-load terrain types
 */
	pre_load_area("types.hex");
	pre_load_items("types.itm");
/*
 * Read the cached map
 */
	read_map("cache.map");
}
