/*
Copyright (C) 1997-2001 Id Software, Inc.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

#include "environ.h"

#include "g_local.h"
#include "stdlog.h"     //WF24      StdLog
#include "bot_procs.h"//ERASER
#include "p_trail.h"//ERASER

char *LoadEntFile(char *mapname, char *entities);//newent 5/99
void Create_All_Home_Bases (void);//WF34

typedef struct
{
	char	*name;
	void	(*spawn)(edict_t *ent);
} spawn_t;

void SP_info_player_start (edict_t *ent);
void SP_info_player_deathmatch (edict_t *ent);
void SP_info_player_coop (edict_t *ent);
void SP_info_player_intermission (edict_t *ent);

void SP_func_plat (edict_t *ent);
void SP_func_rotating (edict_t *ent);
void SP_func_button (edict_t *ent);
void SP_func_door (edict_t *ent);
void SP_func_door_secret (edict_t *ent);
void SP_func_door_rotating (edict_t *ent);
void SP_func_water (edict_t *ent);
void SP_func_train (edict_t *ent);
void SP_func_conveyor (edict_t *self);
void SP_func_wall (edict_t *self);
void SP_func_object (edict_t *self);
void SP_func_explosive (edict_t *self);
void SP_func_timer (edict_t *self);
void SP_func_clock (edict_t *ent);
void SP_func_killbox (edict_t *ent);
void SP_func_static (edict_t *ent);
void SP_func_bobbing ( edict_t *ent );
void SP_func_pendulum ( edict_t *ent );

void SP_trigger_always (edict_t *ent);
void SP_trigger_once (edict_t *ent);
void SP_trigger_multiple (edict_t *ent);
void SP_trigger_relay (edict_t *ent);
void SP_trigger_push (edict_t *ent);
void SP_trigger_hurt (edict_t *ent);
void SP_trigger_key (edict_t *ent);
void SP_trigger_counter (edict_t *ent);
void SP_trigger_elevator (edict_t *ent);
void SP_trigger_gravity (edict_t *ent);
void SP_trigger_monsterjump (edict_t *ent);

void SP_target_temp_entity (edict_t *ent);
void SP_target_speaker (edict_t *ent);
void SP_target_explosion (edict_t *ent);
void SP_target_changelevel (edict_t *ent);
void SP_target_secret (edict_t *ent);
void SP_target_goal (edict_t *ent);
void SP_target_splash (edict_t *ent);
void SP_target_spawner (edict_t *ent);
void SP_target_blaster (edict_t *ent);
void SP_target_crosslevel_trigger (edict_t *ent);
void SP_target_crosslevel_target (edict_t *ent);
void SP_target_laser (edict_t *self);
void SP_target_help (edict_t *ent);
void SP_target_actor (edict_t *ent);
void SP_target_earthquake (edict_t *ent);
void SP_target_character (edict_t *ent);
void SP_target_string (edict_t *ent);
void SP_target_location (edict_t *self);
void SP_target_position (edict_t *self);
void SP_target_print (edict_t *self);

void SP_worldspawn (edict_t *ent);
void SP_viewthing (edict_t *ent);

void SP_light (edict_t *self);
void SP_light_mine1 (edict_t *ent);
void SP_light_mine2 (edict_t *ent);
void SP_info_null (edict_t *self);
void SP_info_notnull (edict_t *self);
void SP_info_camp (edict_t *self);
void SP_path_corner (edict_t *self);
void SP_point_combat (edict_t *self);

void SP_misc_explobox (edict_t *self);
void SP_misc_banner (edict_t *self);
void SP_misc_satellite_dish (edict_t *self);
void SP_misc_actor (edict_t *self);
void SP_misc_gib_arm (edict_t *self);
void SP_misc_gib_leg (edict_t *self);
void SP_misc_gib_head (edict_t *self);
void SP_misc_insane (edict_t *self);
void SP_misc_deadsoldier (edict_t *self);
void SP_misc_viper (edict_t *self);
void SP_misc_viper_bomb (edict_t *self);
void SP_misc_bigviper (edict_t *self);
void SP_misc_strogg_ship (edict_t *self);
void SP_misc_teleporter_dest (edict_t *self);
void SP_misc_blackhole (edict_t *self);
void SP_misc_eastertank (edict_t *self);
void SP_misc_easterchick (edict_t *self);
void SP_misc_easterchick2 (edict_t *self);
void SP_misc_model (edict_t *ent);
void SP_misc_portal_surface (edict_t *ent);
void SP_misc_portal_camera (edict_t *ent);

void SP_monster_berserk (edict_t *self);
void SP_monster_gladiator (edict_t *self);
void SP_monster_gunner (edict_t *self);
void SP_monster_infantry (edict_t *self);
void SP_monster_soldier_light (edict_t *self);
void SP_monster_soldier (edict_t *self);
void SP_monster_soldier_ss (edict_t *self);
void SP_monster_tank (edict_t *self);
void SP_monster_medic (edict_t *self);
void SP_monster_flipper (edict_t *self);
void SP_monster_chick (edict_t *self);
void SP_monster_parasite (edict_t *self);
void SP_monster_flyer (edict_t *self);
void SP_monster_brain (edict_t *self);
void SP_monster_floater (edict_t *self);
void SP_monster_hover (edict_t *self);
void SP_monster_mutant (edict_t *self);
void SP_monster_supertank (edict_t *self);
void SP_monster_boss2 (edict_t *self);
void SP_monster_jorg (edict_t *self);
void SP_monster_boss3_stand (edict_t *self);

void SP_monster_commander_body (edict_t *self);

void SP_turret_breach (edict_t *self);
void SP_turret_base (edict_t *self);
void SP_turret_driver (edict_t *self);


spawn_t	spawns[] = {
	{"info_player_start", SP_info_player_start},
	{"info_player_deathmatch", SP_info_player_deathmatch},
	{"info_player_coop", SP_info_player_coop},
	{"info_player_intermission", SP_info_player_intermission},
//ZOID
	{"team_CTF_redspawn", SP_team_CTF_redspawn},
	{"team_CTF_bluespawn", SP_team_CTF_bluespawn},
	{"team_CTF_redplayer", SP_team_CTF_redplayer},
	{"team_CTF_blueplayer", SP_team_CTF_blueplayer},
//ZOID
//WF34 - Support for LMCTF maps
//	{"info_player_red", SP_info_player_team1},
//	{"info_player_blue", SP_info_player_team2},
//	{"info_position", SP_info_position},
// more WF
//	{"item_flagreturn_team1", SP_item_flagreturn},
//	{"item_flagreturn_team2", SP_item_flagreturn},
//WF34
	{"func_plat", SP_func_plat},
	{"func_button", SP_func_button},
	{"func_door", SP_func_door},
	{"func_door_secret", SP_func_door_secret},
	{"func_door_rotating", SP_func_door_rotating},
	{"func_rotating", SP_func_rotating},
	{"func_train", SP_func_train},
	{"func_water", SP_func_water},
	{"func_conveyor", SP_func_conveyor},
	{"func_clock", SP_func_clock},
	{"func_wall", SP_func_wall},
	{"func_object", SP_func_object},
	{"func_timer", SP_func_timer},
	{"func_explosive", SP_func_explosive},
	{"func_killbox", SP_func_killbox},
	{"func_static", SP_func_static},
	{"func_bobbing", SP_func_bobbing},
	{"func_pendulum", SP_func_pendulum},

	{"trigger_always", SP_trigger_always},
	{"trigger_once", SP_trigger_once},
	{"trigger_multiple", SP_trigger_multiple},
	{"trigger_relay", SP_trigger_relay},
	{"trigger_push", SP_trigger_push},
	{"trigger_hurt", SP_trigger_hurt},
	{"trigger_counter", SP_trigger_counter},
	{"trigger_elevator", SP_trigger_elevator},
	{"trigger_gravity", SP_trigger_gravity},
	{"trigger_monsterjump", SP_trigger_monsterjump},

	{"target_temp_entity", SP_target_temp_entity},
	{"target_speaker", SP_target_speaker},
	{"target_explosion", SP_target_explosion},
	{"target_changelevel", SP_target_changelevel},
	{"target_secret", SP_target_secret},
	{"target_goal", SP_target_goal},
	{"target_splash", SP_target_splash},
	{"target_spawner", SP_target_spawner},
	{"target_blaster", SP_target_blaster},
	{"target_crosslevel_trigger", SP_target_crosslevel_trigger},
	{"target_crosslevel_target", SP_target_crosslevel_target},
	{"target_laser", SP_target_laser},
	{"target_help", SP_target_help},

#if 0 // remove monster code
	{"target_actor", SP_target_actor},
#endif

	{"target_earthquake", SP_target_earthquake},
	{"target_character", SP_target_character},
	{"target_string", SP_target_string},
	{"target_location", SP_target_location},
	{"target_position", SP_target_position},
	{"target_print", SP_target_print},

	{"worldspawn", SP_worldspawn},
	{"viewthing", SP_viewthing},

	{"light", SP_light},
	{"light_mine1", SP_light_mine1},
	{"light_mine2", SP_light_mine2},
	{"info_null", SP_info_null},
	{"func_group", SP_info_null},
	{"info_notnull", SP_info_notnull},
	{"info_camp", SP_info_camp},
	{"path_corner", SP_path_corner},
	{"point_combat", SP_point_combat},

	{"misc_explobox", SP_misc_explobox},
	{"misc_banner", SP_misc_banner},

	{"misc_satellite_dish", SP_misc_satellite_dish},
#if 0 // remove monster code
	{"misc_actor", SP_misc_actor},
#endif
	{"misc_gib_arm", SP_misc_gib_arm},
	{"misc_gib_leg", SP_misc_gib_leg},
	{"misc_gib_head", SP_misc_gib_head},
#if 0 // remove monster code
	{"misc_insane", SP_misc_insane},
#endif
	{"misc_deadsoldier", SP_misc_deadsoldier},
	{"misc_viper", SP_misc_viper},
	{"misc_viper_bomb", SP_misc_viper_bomb},
	{"misc_bigviper", SP_misc_bigviper},
	{"misc_strogg_ship", SP_misc_strogg_ship},
	{"misc_teleporter_dest", SP_misc_teleporter_dest},
//ZOID
	{"trigger_teleport", SP_trigger_teleport},
	{"info_teleport_destination", SP_info_teleport_destination},
//ZOID
	{"misc_blackhole", SP_misc_blackhole},
	{"misc_eastertank", SP_misc_eastertank},
	{"misc_easterchick", SP_misc_easterchick},
	{"misc_easterchick2", SP_misc_easterchick2},
	{"misc_model", SP_misc_model},
	{"misc_portal_surface", SP_misc_portal_surface},
	{"misc_portal_camera", SP_misc_portal_camera},

#if 0 // remove monster code
	{"monster_berserk", SP_monster_berserk},
	{"monster_gladiator", SP_monster_gladiator},
	{"monster_gunner", SP_monster_gunner},
	{"monster_infantry", SP_monster_infantry},
	{"monster_soldier_light", SP_monster_soldier_light},
	{"monster_soldier", SP_monster_soldier},
	{"monster_soldier_ss", SP_monster_soldier_ss},
	{"monster_tank", SP_monster_tank},
	{"monster_tank_commander", SP_monster_tank},
	{"monster_medic", SP_monster_medic},
	{"monster_flipper", SP_monster_flipper},
	{"monster_chick", SP_monster_chick},
	{"monster_parasite", SP_monster_parasite},
	{"monster_flyer", SP_monster_flyer},
	{"monster_brain", SP_monster_brain},
	{"monster_floater", SP_monster_floater},
	{"monster_hover", SP_monster_hover},
	{"monster_mutant", SP_monster_mutant},
	{"monster_supertank", SP_monster_supertank},
	{"monster_boss2", SP_monster_boss2},
	{"monster_boss3_stand", SP_monster_boss3_stand},
	{"monster_jorg", SP_monster_jorg},

	{"monster_commander_body", SP_monster_commander_body},

	{"turret_breach", SP_turret_breach},
	{"turret_base", SP_turret_base},
	{"turret_driver", SP_turret_driver},
#endif

	{NULL, NULL}
};

/*
===============
ED_CallSpawn

Finds the spawn function for the entity and calls it
===============
*/
void ED_CallSpawn (edict_t *ent)
{
	spawn_t	*s;
	gitem_t	*item;
	int		i;

	if (!ent->classname)
	{
		if ( developer->value )
			gi.dprintf ("ED_CallSpawn: NULL classname\n");
		return;
	}

	// check item spawn functions
	for (i=0,item=itemlist ; i<game.num_items ; i++,item++)
	{
		if (!item->classname)
			continue;
		if (!Q_stricmp(item->classname, ent->classname))
		{	// found it
			SpawnItem (ent, item);
			return;
		}
	}

	// check normal spawn functions
	for (s=spawns ; s->name ; s++)
	{
		if (!Q_stricmp(s->name, ent->classname))
		{	// found it
			s->spawn (ent);
			return;
		}
	}

	if ( developer->value )
		gi.dprintf ("%s doesn't have a spawn function\n", ent->classname);
}

/*
=============
ED_NewString
=============
*/
char *ED_NewString (char *string)
{
	char	*newb, *new_p;
	int		i,l;
	
	l = strlen(string) + 1;

	newb = gi.TagMalloc (l, TAG_LEVEL);

	new_p = newb;

	for (i=0 ; i< l ; i++)
	{
		if (string[i] == '\\' && i < l-1)
		{
			i++;
			if (string[i] == 'n') {
				*new_p++ = '\n';
			} else {
				*new_p++ = '/';
				*new_p++ = string[i];
			}
		}
		else
			*new_p++ = string[i];
	}
	
	return newb;
}




/*
===============
ED_ParseField

Takes a key/value pair and sets the binary values
in an edict
===============
*/
void ED_ParseField (char *key, char *value, edict_t *ent)
{
	field_t	*f;
	qbyte	*b;
	float	v;
	vec3_t	vec;

	for (f=fields ; f->name ; f++)
	{
		if (!Q_stricmp(f->name, key))
		{	// found it
			if (f->flags & FFL_SPAWNTEMP)
				b = (qbyte *)&st;
			else
				b = (qbyte *)ent;

			switch (f->type)
			{
			case F_LSTRING:
				*(char **)(b+f->ofs) = ED_NewString (value);
				break;
			case F_VECTOR:
				sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]);
				((float *)(b+f->ofs))[0] = vec[0];
				((float *)(b+f->ofs))[1] = vec[1];
				((float *)(b+f->ofs))[2] = vec[2];
				break;
			case F_INT:
				*(int *)(b+f->ofs) = atoi(value);
				break;
			case F_FLOAT:
				*(float *)(b+f->ofs) = atof(value);
				break;
			case F_ANGLEHACK:
				v = atof(value);
				((float *)(b+f->ofs))[0] = 0;
				((float *)(b+f->ofs))[1] = v;
				((float *)(b+f->ofs))[2] = 0;
				break;
			case F_IGNORE:
				break;
			}
			return;
		}
	}

	if ( developer->value )
		gi.dprintf ("%s is not a field\n", key);
}

/*
====================
G_AddSpawnVarToken
Added for g_Gametype entity spawning
====================
*/
char *G_AddSpawnVarToken( const char *string ) {
	int		l;
	char	*dest;

	l = strlen( string );
	if ( level.numSpawnVarChars + l + 1 > MAX_SPAWN_VARS_CHARS ) 
	{
		gi.dprintf ("WTF\n");
		gi.dprintf ("Next Position:%i\n", level.numSpawnVarChars);
		gi.dprintf ("String Length: %i\n", l);
		gi.dprintf ("String       : %s \n", string);
		gi.error( "G_AddSpawnVarToken: MAX_SPAWN_VARS" );
	}


	dest = level.spawnVarChars + level.numSpawnVarChars;
	memcpy( dest, string, l+1 );

	level.numSpawnVarChars += l + 1;
	gi.dprintf ("DEBUG:memcpy Position: %i String: %s Dest: %i\n",level.numSpawnVarChars,string,dest);

	return dest;

}

/*
====================
ED_ParseEdict

Parses an edict out of the given string, returning the new position
ed should be a properly initialized empty edict.
====================
*/
char *ED_ParseEdict (char *data, edict_t *ent)
{
	qboolean	init;
	char		keyname[256];
	char		*com_token;

	level.numSpawnVars = 0;
	level.numSpawnVarChars = 0;
// gametype whoopsie

	init = qfalse;
	memset (&st, 0, sizeof(st));

// go through all the dictionary pairs
	while (1)
	{	
	// parse key
		com_token = COM_Parse (&data);
		if (com_token[0] == '}')
			break;
		if (!data)
			gi.error ("ED_ParseEntity: EOF without closing brace");

		Q_strncpyz (keyname, com_token, sizeof(keyname));
		
	// parse value	
		com_token = COM_Parse (&data);
		if (!data)
			gi.error ("ED_ParseEntity: EOF without closing brace");

		if (com_token[0] == '}')
			gi.error ("ED_ParseEntity: closing brace without data");
// gametype
		level.spawnVars[ level.numSpawnVars ][0] = G_AddSpawnVarToken( keyname );
		level.spawnVars[ level.numSpawnVars ][1] = G_AddSpawnVarToken( com_token );
		level.numSpawnVars++;
// end gametype

		init = qtrue;	

	// keynames with a leading underscore are used for utility comments,
	// and are immediately discarded by quake
		if (keyname[0] == '_')
			continue;

		ED_ParseField (keyname, com_token, ent);

	}

	if (!init)
		memset (ent, 0, sizeof(*ent));

	return data;
}


/*
================
G_FindTeams

Chain together all entities with a matching team field.

All but the first will have the FL_TEAMSLAVE flag set.
All but the last will have the teamchain field set to the next one
================
*/
void G_FindTeams (void)
{
	edict_t	*e, *e2, *chain;
	int		i, j;
	int		c, c2;

	c = 0;
	c2 = 0;
	for (i=1, e=g_edicts+i ; i < globals.num_edicts ; i++,e++)
	{
		if (!e->inuse)
			continue;
		if (!e->team)
			continue;
		if (e->flags & FL_TEAMSLAVE)
			continue;
		chain = e;
		e->teammaster = e;
		c++;
		c2++;
		for (j=i+1, e2=e+1 ; j < globals.num_edicts ; j++,e2++)
		{
			if (!e2->inuse)
				continue;
			if (!e2->team)
				continue;
			if (e2->flags & FL_TEAMSLAVE)
				continue;
			if (!strcmp(e->team, e2->team))
			{
				c2++;
				chain->teamchain = e2;
				e2->teammaster = e;
				chain = e2;
				e2->flags |= FL_TEAMSLAVE;
			}
		}
	}

	if ( developer->value )
		gi.dprintf ("%i teams with %i entities\n", c, c2);
}
//ERASER START
void CheckNodeCalculation(edict_t	*ent)
{
	if (nodes_done || (trail_head >= 500))	// assume it's done if > 500 nodes
	{
//		if (bot_calc_nodes->value)
//		{
			gi.cvar_set("bot_calc_nodes", "0");
			gi.dprintf("\nDynamic node-table generation DISABLED\n\n");
//		}
	}
	else
	{
//		if (!bot_calc_nodes->value)
//		{
			gi.cvar_set("bot_calc_nodes", "0");
			gi.dprintf("\nDynamic node-table generation ENABLED\n\n");
//		}
	}

	G_FreeEdict(ent);
}

// gametype
qboolean	G_SpawnInt( const char *key, const char *defaultString, int *out ) {
	char		*s;
	qboolean	present;

	present = G_SpawnString( key, defaultString, &s );
	*out = atoi( s );
	return present;
}
qboolean	G_SpawnString( const char *key, const char *defaultString, char **out ) {
	int		i;
	
	for ( i = 0 ; i < level.numSpawnVars ; i++ ) {
		if ( !Q_stricmp( key, level.spawnVars[i][0] ) ) {
			*out = level.spawnVars[i][1];
			return qtrue;
		}
	}

	*out = (char *)defaultString;
	return qfalse;
}
// gametype


/*
==============
SpawnEntities

Creates a server's entity / program execution context by
parsing textual entity definitions out of an ent file.
==============
*/
void SpawnEntities (char *mapname, char *entities, char *spawnpoint)
{
	edict_t		*ent;
	int			inhibit;
	char		*com_token;
	int			i;
	float		skill_level;
	char		*s, *value, *gametypeName;
	static char *gametypeNames[] = {"ffa", "tournament", "single", "team", "ctf", "oneflag", "commandpoint", "harvester", "teamtournament"};

	skill_level = floor (skill->value);
	clamp (skill_level, 0, 3);
	if (skill->value != skill_level)
		gi.cvar_forceset("skill", va("%f", skill_level));

	SaveClientData ();

	gi.FreeTags (TAG_LEVEL);

	memset (&level, 0, sizeof(level));
	memset (g_edicts, 0, game.maxentities * sizeof (g_edicts[0]));

	Q_strncpyz (level.mapname, mapname, sizeof(level.mapname));
	Q_strncpyz (game.spawnpoint, spawnpoint, sizeof(game.spawnpoint));

	// set client fields on player ents
	for (i=0 ; i<game.maxclients ; i++)
		g_edicts[i+1].client = game.clients + i;

	ent = NULL;
	inhibit = 0;

	entities = LoadEntFile(mapname, entities);//newent 5/99
// parse ents
	while (1)
	{
		
		// parse the opening brace	
		com_token = COM_Parse (&entities);
		if (!entities)
			break;
		if (com_token[0] != '{')
			gi.error ("ED_LoadFromFile: found %s when expecting {",com_token);

		if (!ent)
			ent = g_edicts;
		else
		{
			for ( i = 0 ; i < level.numSpawnVars ; i++ )
			{
			ED_ParseField( level.spawnVars[i][0], level.spawnVars[i][1], ent ); // gametype
			}
			ent = G_Spawn ();
		}
		entities = ED_ParseEdict (entities, ent);
		// remove things (except the world) from different skill levels or deathmatch
		if (ent != g_edicts)
		{
			
// **** gametype
// hrmph
//error C2108: subscript is not of integral type
//warning C4047: '=' : 'char *' differs in levels of indirection from 'char ** '
			if( G_SpawnString( "gametype", NULL, &value ) ) 
			{
				
				if( g_gametype->value >= GT_FFA && g_gametype->value < GT_MAX_GAME_TYPE )
					
				{
					gametypeName = gametypeNames[g_gametype->value]; //here
					gi.dprintf ("Spawn: %s\n", gametypeName);

					s = strstr( value, gametypeName );
					if( !s ) 
					{
						G_FreeEdict (ent);	
						inhibit++;
						continue;
					}
				}
			}
// **** gametype
			if ( deathmatch->value )
			{
				if ( ctf->value || ((int)(dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS)) ) {

					if ( st.notteam ) {
						G_FreeEdict (ent);	
						inhibit++;
						continue;
					}
				} else if ( (ent->spawnflags & SPAWNFLAG_NOT_DEATHMATCH) || st.notfree ) {
					G_FreeEdict (ent);	
					inhibit++;
					continue;
				}
			}
			else
			{
				if ( /* ((coop->value) && (ent->spawnflags & SPAWNFLAG_NOT_COOP)) || */
					((skill->value == 0) && (ent->spawnflags & SPAWNFLAG_NOT_EASY)) ||
					((skill->value == 1) && (ent->spawnflags & SPAWNFLAG_NOT_MEDIUM)) ||
					(((skill->value == 2) || (skill->value == 3)) && (ent->spawnflags & SPAWNFLAG_NOT_HARD))
					)
				{
					G_FreeEdict (ent);	
					inhibit++;
					continue;
				} else if ( st.notsingle || st.notfree ) {
					G_FreeEdict (ent);	
					inhibit++;
					continue;
				}
			}

			ent->spawnflags &= ~(SPAWNFLAG_NOT_EASY|SPAWNFLAG_NOT_MEDIUM|SPAWNFLAG_NOT_HARD|SPAWNFLAG_NOT_COOP|SPAWNFLAG_NOT_DEATHMATCH);
		}

		ED_CallSpawn (ent);
	}	

	if ( developer->value )
		gi.dprintf ("%i entities inhibited\n", inhibit);

	G_FindTeams ();
//ERASER START
/*	if (!G_Find(NULL, FOFS(classname), "team_CTF_redflag")) // WFA Check
	{	// not a CTF level
		gi.cvar_forceset("ctf", "0");
	}
	else	// make sure CTF is enabled, since there is a flag
	{
*/		gi.cvar_forceset("ctf", "1");
//		gi.cvar_forceset("grapple", "1");

		if (ctf->value) {
			gi.configstring (CS_STATUSBAR, ctf_statusbar);
			//precaches
			//gi.imageindex("sbctf1");
			//gi.imageindex("sbctf2");
			gi.imageindex("i_ctf1");
			gi.imageindex("i_ctf2");
			gi.imageindex("i_ctf1d");
			gi.imageindex("i_ctf2d");
			gi.imageindex("i_ctf1t");
			gi.imageindex("i_ctf2t");
			gi.imageindex("i_ctfj");
		}
//	}
//ERASER END
	PlayerTrail_Init ();

//ZOID
//	CTFSpawn();
//ZOID
//WF
//	Create_All_Home_Bases ();

	sl_Logging( &gi, "The Weapons Factory" );        // StdLog
	sl_GameStart( &gi, level );     //      StdLog 
//WF
//ERASER START spawn an entity, that will decide whether or not to disable node calculation
	ent = G_Spawn();
	ent->think = CheckNodeCalculation;
	ent->nextthink = level.time + 1.5;	// give the items time to set their reachable nodes

	check_nodes_done = NULL;
//ERASER END
}


//===================================================================

#if 0
	// cursor positioning
	xl <value>
	xr <value>
	yb <value>
	yt <value>
	xv <value>
	yv <value>

	// drawing
	statpic <name>
	pic <stat>
	num <fieldwidth> <stat>
	string <stat>

	// control
	if <stat>
	ifeq <stat> <value>
	ifbit <stat> <value>
	endif

#endif

//char *single_statusbar = "single";

//char *dm_statusbar = "dm";
/*
char *single_statusbar = 
"yb	-24 "

// health
"xv	0 "
"hnum "
"xv	50 "
"pic 0 "

// ammo
"if 2 "
"	xv	100 "
"	anum "
"	xv	150 "
"	pic 2 "
"endif "

// armor
"if 4 "
"	xv	200 "
"	rnum "
"	xv	250 "
"	pic 4 "
"endif "

// selected item
"if 6 "
"	xv	296 "
"	pic 6 "
"endif "

"yb	-50 "

// picked up item
"if 7 "
"	xv	0 "
"	pic 7 "
"	xv	26 "
"	yb	-42 "
"	stat_string 8 "
"	yb	-50 "
"endif "

// timer
"if 9 "
"	xv	262 "
"	num	2	10 "
"	xv	296 "
"	pic	9 "
"endif "

//  help / weapon icon 
"if 11 "
"	xv	148 "
"	pic	11 "
"endif "
;

char *dm_statusbar =
"yb	-24 "

// health
"xv	0 "
"hnum "
"xv	50 "
"pic 0 "

// ammo
"if 2 "
"	xv	100 "
"	anum "
"	xv	150 "
"	pic 2 "
"endif "

// armor
"if 4 "
"	xv	200 "
"	rnum "
"	xv	250 "
"	pic 4 "
"endif "

// selected item
"if 6 "
"	xv	296 "
"	pic 6 "
"endif "

"yb	-50 "

// picked up item
"if 7 "
"	xv	0 "
"	pic 7 "
"	xv	26 "
"	yb	-42 "
"	stat_string 8 "
"	yb	-50 "
"endif "

// timer
"if 9 "
"	xv	246 "
"	num	2	10 "
"	xv	296 "
"	pic	9 "
"endif "

//  help / weapon icon 
"if 11 "
"	xv	148 "
"	pic	11 "
"endif "

//  frags
"xr	-50 "
"yt 2 "
"num 3 14"
;
*/
//ERASER START
extern qboolean	respawn_flag;
extern int num_dm_spots;
//ERASER END

/*QUAKED worldspawn (0 0 0) ?

Only used for the world.
"sky"	environment map name
"skyaxis"	vector axis for rotating sky
"skyrotate"	speed of rotation in degrees/second
"sounds"	music cd track number
"gravity"	800 is default gravity
"message"	text to print at user logon
*/
void SP_worldspawn (edict_t *ent)
{
	ent->movetype = MOVETYPE_PUSH;
	ent->solid = SOLID_BSP;
	ent->inuse = qtrue;			// since the world doesn't use G_Spawn()
	ent->s.modelindex = 1;		// world model is always index 1
	VectorClear (ent->s.origin);
	VectorClear (ent->s.angles);

	//---------------

	// reserve some spots for dead player bodies for coop / deathmatch
	InitBodyQue ();

	// set configstrings for items
	SetItemNames ();

	if (st.nextmap)
		strcpy (level.nextmap, st.nextmap);

	// make some data visible to the server
	if (ent->message && ent->message[0])
	{
		gi.configstring ( CS_MESSAGE, ent->message );
		Q_strncpyz ( level.level_name, ent->message, sizeof(level.level_name) );
	}
	else
		Q_strncpyz ( level.level_name, level.mapname, sizeof(level.level_name) );

	// send music
	if ( st.music ) {
		gi.configstring ( CS_AUDIOTRACK, st.music );
	}

	gi.configstring (CS_MAXCLIENTS, va("%i", (int)(maxclients->value) ) );

	// status bar program
	gi.configstring (CS_STATUSBAR, ctf_statusbar);
			CTFPrecache();
/*	if (deathmatch->value)
//ZOID

		if (ctf->value) {
			gi.configstring (CS_STATUSBAR, ctf_statusbar);
			CTFPrecache();
		} else
//ZOID
			gi.configstring (CS_STATUSBAR, dm_statusbar);
	else
		gi.configstring (CS_STATUSBAR, single_statusbar);
*/
	//---------------
// #######################################
//ERASER START//FIXME ACRID
	// set ammo item lookups
	item_shells = FindItem("shells");
	item_cells = FindItem("cells");
	item_bullets = FindItem("bullets");
	item_rockets = FindItem("rockets");
	item_slugs = FindItem("slugs");
	item_grenades = FindItem("grenades");

	item_blaster	= FindItem("Blaster");
	item_shotgun	= FindItem("shotgun");
	item_supershotgun	= FindItem("super shotgun");
	item_machinegun	= FindItem("machinegun");
	item_chaingun	= FindItem("chaingun");
	item_grenadelauncher	= FindItem("grenade launcher");
	item_rocketlauncher	= FindItem("rocket launcher");
	item_railgun	= FindItem("railgun");
	item_hyperblaster	= FindItem("hyperblaster");
	item_bfg10k	= FindItem("bfg10k");

//ACRID TEST NEW WF WEAPONS
	item_sniperrifle = FindItem("Sniper Rifle");
	item_lightninggun = FindItem("Lightning Gun");
	item_infecteddart = FindItem("Infected Dart Launcher");
    item_pulsecannon = FindItem("Pulse Cannon");
	item_needler = FindItem("Needler");
	item_flamethrower = FindItem("FlameThrower");
	item_telsacoil = FindItem("Telsa Coil");
	item_pelletrocketlauncher = FindItem("Pellet Rocket Launcher");
	item_rocketnapalmlauncher = FindItem("Rocket Napalm Launcher");
	item_rocketclusterlauncher = FindItem("Cluster Rocket Launcher");
	item_shc = FindItem("SHC Rifle");
	item_handgrenades = FindItem("Grenades");
	item_poisondart = FindItem("Poison Dart Launcher");
	item_ak47 = FindItem("AK47");
	item_pistol = FindItem("Pistol");
	item_knife = FindItem("Knife");
	//*item_sentryspot, *item_depotspot
	item_armordart = FindItem("Poison Dart Launcher");
	item_stingerrocketlauncher = FindItem("Stinger Launcher");

//ACRID END NEW WF WEAPONS 
// -ss
/*
	if (!respawn_flag)		// only read in bots once, or team links for players will become corrupted
	{
		// read data from bots.cfg
		ReadBotConfig();
	}
*/
/*	else if (teamplay->value)	// clear the scores
	{
		int i;

		for (i=0; i<MAX_TEAMS; i++)
		{
			if (!bot_teams[i])
				break;

			bot_teams[i]->score = 0;
			bot_teams[i]->last_grouping = 0;
		}
	}*///remove bot team
//ERASER END
// ##########################################################

	// help icon for statusbar
	gi.imageindex ("pics/i_help");
	gi.imageindex ("pics/help");
	//compass 5/99
	gi.imageindex ("north");
    gi.imageindex ("northwest");
	gi.imageindex ("northeast");
	gi.imageindex ("west");
	gi.imageindex ("east");
	gi.imageindex ("southwest");
	gi.imageindex ("southeast");
	gi.imageindex ("south");
	gi.imageindex ("up");
	gi.imageindex ("down");
	if (!st.gravity)
		gi.cvar_set("sv_gravity", "800");
	else
		gi.cvar_set("sv_gravity", st.gravity);

	snd_fry = gi.soundindex ("sound/player/fry.wav");	// standing in lava / slime

	PrecacheItem (FindItem ("Blaster"));

	gi.soundindex ("sound/player/lava1.wav");
	gi.soundindex ("sound/player/lava2.wav");

	gi.soundindex ("sound/misc/pc_up.wav");
	gi.soundindex ("sound/misc/talk1.wav");

	gi.soundindex ("sound/misc/udeath.wav");

	// sexed sounds
	gi.soundindex ("*death1.wav");
	gi.soundindex ("*death2.wav");
	gi.soundindex ("*death3.wav");
	gi.soundindex ("*death4.wav");
	gi.soundindex ("*fall1.wav");
	gi.soundindex ("*fall2.wav");	
	gi.soundindex ("*gurp1.wav");		// drowning damage
	gi.soundindex ("*gurp2.wav");	
	gi.soundindex ("*pain25_1.wav");
	gi.soundindex ("*pain25_2.wav");
	gi.soundindex ("*pain50_1.wav");
	gi.soundindex ("*pain50_2.wav");
	gi.soundindex ("*pain75_1.wav");
	gi.soundindex ("*pain75_2.wav");
	gi.soundindex ("*pain100_1.wav");
	gi.soundindex ("*pain100_2.wav");
//ERASER START
	gi.soundindex ("player/female/death1.wav");
	gi.soundindex ("player/female/death2.wav");
	gi.soundindex ("player/female/death3.wav");
	gi.soundindex ("player/female/death4.wav");

	gi.soundindex ("player/female/fall1.wav");
	gi.soundindex ("player/female/fall2.wav");	

	gi.soundindex ("player/female/gurp1.wav");		// drowning damage
	gi.soundindex ("player/female/gurp2.wav");	

	gi.soundindex ("player/female/jump1.wav");		// player jump

	gi.soundindex ("player/female/pain25_1.wav");
	gi.soundindex ("player/female/pain25_2.wav");
	gi.soundindex ("player/female/pain50_1.wav");
	gi.soundindex ("player/female/pain50_2.wav");
	gi.soundindex ("player/female/pain75_1.wav");
	gi.soundindex ("player/female/pain75_2.wav");
	gi.soundindex ("player/female/pain100_1.wav");
	gi.soundindex ("player/female/pain100_2.wav");

	//-------------------
//ERASER END
	// sexed models//WF34 S
	// THIS ORDER MUST MATCH THE DEFINES IN g_local.h
	// you can add more, max 15

	//splitmodels (tagged weapons: md3) use the Q3 weapons folder
	gi.modelindex ("#gauntlet/gauntlet.md3");			//1		WEAP_BLASTER
	gi.modelindex ("#shotgunq2/shotgunq2.md3");			//2		WEAP_SHOTGUN
	gi.modelindex ("#shotgun/shotgun.md3");				//3		WEAP_SUPERSHOTGUN
	gi.modelindex ("#machinegun/machinegun.md3");		//4		WEAP_MACHINEGUN
	gi.modelindex ("#megachaingun/megachaingun.md3");	//5		WEAP_CHAINGUN
	gi.modelindex ("#grenades/grenades.md3");			//6		WEAP_GRENADES
	gi.modelindex ("#grenadel/grenadel.md3");			//7		WEAP_GRENADELAUNCHER
	gi.modelindex ("#rocketl/rocketl.md3");				//8		WEAP_ROCKETLAUNCHER
	gi.modelindex ("#plasma/plasma.md3");				//9		WEAP_HYPERBLASTER
	gi.modelindex ("#railgun/railgun.md3");				//10	WEAP_RAILGUN
	gi.modelindex ("#bfg/bfg.md3");						//11	WEAP_BFG	
	gi.modelindex ("#grapple/grapple.md3");				//12	WEAP_GRAPPLE
	gi.modelindex ("#knife/knife.md3");					//13	WEAP_KNIFE
	gi.modelindex ("#sniperrifle/sniperrifle.md3");		//14	WEAP_SNIPERRIFLE
	gi.modelindex ("#dartgun/dartgun.md3");				//13	WEAP_INFECTEDDART

	
/*	//Quake2 references
	//sexed models
	gi.modelindex ("#w_blaster.md3");
	gi.modelindex ("#w_shotgun.md3");
	gi.modelindex ("#w_sshotgun.md3");
	gi.modelindex ("#w_machinegun.md3");
	gi.modelindex ("#w_chaingun.md3");
	gi.modelindex ("#a_grenades.md3");
	gi.modelindex ("#w_glauncher.md3");
	gi.modelindex ("#w_rlauncher.md3");
	gi.modelindex ("#w_hyperblaster.md3");
	gi.modelindex ("#w_railgun.md3");
	gi.modelindex ("#w_bfg.md3");
	gi.modelindex ("#w_grapple.md3");

	gi.modelindex ("#w_blaster.md2");
	gi.modelindex ("#w_shotgun.md2");
	gi.modelindex ("#w_sshotgun.md2");
	gi.modelindex ("#w_machinegun.md2");
	gi.modelindex ("#w_chaingun.md2");
	gi.modelindex ("#a_grenades.md2");
	gi.modelindex ("#w_glauncher.md2");
	gi.modelindex ("#w_rlauncher.md2");
	gi.modelindex ("#w_hyperblaster.md2");
	gi.modelindex ("#w_railgun.md2");
	gi.modelindex ("#w_bfg.md2");
	gi.modelindex ("#w_grapple.md2");//TRY THIS ERASER
	gi.modelindex ("#w_knife.md2");
	gi.modelindex ("#w_sniperrifle.md2");//8/99 acrid
	gi.modelindex ("#w_infecteddart.md2");//8/99 acrid
*/
/*
	//-------------------

	gi.soundindex ("sound/player/gasp1.wav");		// gasping for air
	gi.soundindex ("sound/player/gasp2.wav");		// head breaking surface, not gasping

	gi.soundindex ("sound/player/watr_in.wav");	// feet hitting water
	gi.soundindex ("sound/player/watr_out.wav");	// feet leaving water

	gi.soundindex ("sound/player/watr_un.wav");	// head going underwater
	
	gi.soundindex ("sound/player/u_breath1.wav");
	gi.soundindex ("sound/player/u_breath2.wav");

	gi.soundindex ("sound/items/pkup.wav");		// bonus item pickup
	gi.soundindex ("sound/world/land.wav");		// landing thud
	gi.soundindex ("sound/misc/h2ohit1.wav");		// landing splash

	gi.soundindex ("sound/items/damage.wav");
	gi.soundindex ("sound/items/protect.wav");
	gi.soundindex ("sound/items/protect4.wav");
	gi.soundindex ("sound/weapons/noammo.wav");

	sm_meat_index = gi.modelindex ("models/objects/gibs/sm_meat/tris.md2");
	gi.modelindex ("models/objects/gibs/arm/tris.md2");
	gi.modelindex ("models/objects/gibs/bone/tris.md2");
	gi.modelindex ("models/objects/gibs/bone2/tris.md2");
	gi.modelindex ("models/objects/gibs/chest/tris.md2");
	gi.modelindex ("models/objects/gibs/skull/tris.md2");
	gi.modelindex ("models/objects/gibs/head2/tris.md2");
*/
	//WF34 E
	//-------------------

	gi.soundindex ("player/gasp1.wav");		// gasping for air
	gi.soundindex ("player/gasp2.wav");		// head breaking surface, not gasping

	gi.soundindex ("sound/player/watr_in.wav");	// feet hitting water
	gi.soundindex ("sound/player/watr_out.wav");	// feet leaving water

	gi.soundindex ("sound/player/watr_un.wav");	// head going underwater
	
	gi.soundindex ("player/u_breath1.wav");
	gi.soundindex ("player/u_breath2.wav");

	gi.soundindex ("sound/misc/ar1_pkup.wav");		// bonus item pickup
	gi.soundindex ("sound/world/plop.wav");		// landing thud
	gi.soundindex ("sound/player/watr_in.wav");		// landing splash

	gi.soundindex ("items/damage.wav");
	gi.soundindex ("items/protect.wav");
	gi.soundindex ("items/protect4.wav");
	gi.soundindex ("sound/weapons/noammo.wav");

	gi.soundindex ("infantry/inflies1.wav");

	sm_meat_index = gi.modelindex ("models/objects/gibs/sm_meat/tris.md2");
	gi.modelindex ("models/objects/gibs/arm/tris.md2");
	gi.modelindex ("models/objects/gibs/bone/tris.md2");
	gi.modelindex ("models/objects/gibs/bone2/tris.md2");
	gi.modelindex ("models/objects/gibs/chest/tris.md2");
	gi.modelindex ("models/objects/gibs/skull/tris.md2");
	gi.modelindex ("models/objects/gibs/head2/tris.md2");

//WF24 S
	//models
	gi.modelindex ("wfactory/models/decoys/female/tris.md2");
	gi.modelindex ("wfactory/models/decoys/male/tris.md2");
	gi.modelindex ("wfactory/models/decoys/cyborg/tris.md2");
	gi.modelindex ("models/mapobjects/flagstands/blueflagstand.md3");
	gi.modelindex ("models/mapobjects/flagstands/redflagstand.md3");
	gi.modelindex ("models/specials/sentrygun/sentryturret1.md3");
	gi.modelindex ("models/specials/sentrygun/sentryturret2.md3");
	gi.modelindex ("models/specials/sentrygun/sentryturret3.md3");
	gi.modelindex ("models/specials/sentrygun/sentrystand.md3");
	gi.modelindex ("models/flare/tris.md2");
	gi.modelindex ("models/bolt/tris.md2");
	gi.modelindex ("models/weapons2/dartgun/dart.md3");//WF34 S
	gi.modelindex ("models/nailgun/tris.md2");
	gi.modelindex ("models/sight/tris.md2");
	gi.modelindex ("models/weapons2/spike/spike.md3");
//	gi.modelindex ("models/weapons/v_sniper2/tris.md2"); // EEK A HACK
	gi.modelindex ("models/objects/grenade/tris.md2");
	gi.modelindex ("models/objects/grenade2/tris.md2");
	gi.modelindex ("models/objects/grenade3/tris.md2");
	gi.modelindex ("models/weapons2/wfgrenade/redturret.md3");
	gi.modelindex ("models/weapons2/wfgrenade/blueturret.md3");

//WF34 Sounds
	gi.soundindex ("sound/decoy/cdecoyof.wav");
	gi.soundindex ("sound/decoy/cdecoyon.wav");
	gi.soundindex ("sound/decoy/fdecoyof.wav");
	gi.soundindex ("sound/decoy/fdecoyon.wav");
	gi.soundindex ("sound/decoy/mdecoyof.wav");
	gi.soundindex ("sound/decoy/mdecoyon.wav");
	gi.soundindex ("sound/feedback/flagcap_red.wav");
	gi.soundindex ("sound/feedback/flagcap_blu.wav");
	gi.soundindex ("sound/feedback/flagtk_blu.wav");
	gi.soundindex ("sound/feedback/flagtk_red.wav");
	gi.soundindex ("sound/feedback/flagret_blu.wav");
	gi.soundindex ("sound/feedback/flagret_red.wav");
	gi.soundindex ("sound/specials/depots/med_depot2.wav");
	gi.soundindex ("sound/weapons/dartgun/dart_hit.wav");
	gi.soundindex ("electric.wav");
	gi.soundindex ("sound/specials/homing/homelock.wav");
	gi.soundindex ("sound/specials/jetpack/takeoff.wav");
	gi.soundindex ("sound/weapons2/napalm/jumppack.wav");
	gi.soundindex ("lshoot.wav");
	gi.soundindex ("misc/keyuse.wav");
	gi.soundindex ("misc/lasfly.wav");
	gi.soundindex ("needle.wav");
	gi.soundindex ("scream.wav");
	gi.soundindex ("soldier/solatck1.wav");
	gi.soundindex ("soldier/solidle1.wav");
	gi.soundindex ("soldier/solpain1.wav");
	gi.soundindex ("soldier/solsght1.wav");
	gi.soundindex ("soldier/solsrch1.wav");
	gi.soundindex ("sound/weapons/knife/knifehit.wav");
	gi.soundindex ("sound/weapons/knife/knifescream2.wav");
	gi.soundindex ("sound/weapons/knife/knifeswish.wav");
//	gi.soundindex ("weapons/disembowel.wav");
	gi.soundindex ("sound/weapons/rocket/rockfly2.wav");
	gi.soundindex ("world/airhiss1.wav");
	gi.soundindex ("world/laser.wav");
	gi.soundindex ("world/quake.wav");

//
// Setup light animation tables. 'a' is total darkness, 'z' is doublebright.
//

	// 0 normal
	gi.configstring(CS_LIGHTS+0, "m");
	
	// 1 FLICKER (first variety)
	gi.configstring(CS_LIGHTS+1, "mmnmmommommnonmmonqnmmo");
	
	// 2 SLOW STRONG PULSE
	gi.configstring(CS_LIGHTS+2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
	
	// 3 CANDLE (first variety)
	gi.configstring(CS_LIGHTS+3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
	
	// 4 FAST STROBE
	gi.configstring(CS_LIGHTS+4, "mamamamamama");
	
	// 5 GENTLE PULSE 1
	gi.configstring(CS_LIGHTS+5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
	
	// 6 FLICKER (second variety)
	gi.configstring(CS_LIGHTS+6, "nmonqnmomnmomomno");
	
	// 7 CANDLE (second variety)
	gi.configstring(CS_LIGHTS+7, "mmmaaaabcdefgmmmmaaaammmaamm");
	
	// 8 CANDLE (third variety)
	gi.configstring(CS_LIGHTS+8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
	
	// 9 SLOW STROBE (fourth variety)
	gi.configstring(CS_LIGHTS+9, "aaaaaaaazzzzzzzz");
	
	// 10 FLUORESCENT FLICKER
	gi.configstring(CS_LIGHTS+10, "mmamammmmammamamaaamammma");

	// 11 SLOW PULSE NOT FADE TO BLACK
	gi.configstring(CS_LIGHTS+11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
	
	// styles 32-62 are assigned by the light program for switchable lights

	// 63 testing
	gi.configstring(CS_LIGHTS+63, "a");

}