gave names to nearly all structs and enums which should make for better C++ error...
[xonotic/darkplaces.git] / pr_edict.c
index dc4166a..1fe3079 100644 (file)
@@ -22,27 +22,31 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "quakedef.h"
 
 dprograms_t            *progs;
-dfunction_t            *pr_functions;
+mfunction_t            *prog->functions;
 char                   *pr_strings;
+int                            pr_stringssize;
 ddef_t                 *pr_fielddefs;
 ddef_t                 *pr_globaldefs;
 dstatement_t   *pr_statements;
 globalvars_t   *pr_global_struct;
 float                  *pr_globals;                    // same as pr_global_struct
-int                            pr_edict_size;                  // in bytes
+int                            prog->edict_size;                       // in bytes
 int                            pr_edictareasize;               // LordHavoc: in bytes
 
+int                            pr_maxknownstrings;
+int                            pr_numknownstrings;
+const char             **pr_knownstrings;
+
 unsigned short pr_crc;
 
-mempool_t              *progs_mempool;
-mempool_t              *edictstring_mempool;
+mempool_t              *serverprogs_mempool;
 
 int            type_size[8] = {1,sizeof(string_t)/4,1,3,1,1,sizeof(func_t)/4,sizeof(void *)/4};
 
-ddef_t *ED_FieldAtOfs (int ofs);
-qboolean       ED_ParseEpair (void *base, ddef_t *key, char *s);
+ddef_t *ED_FieldAtOfs(int ofs);
+qboolean ED_ParseEpair(prvm_edict_t *ent, ddef_t *key, const char *s);
 
-cvar_t pr_checkextension = {0, "pr_checkextension", "1"};
+cvar_t pr_checkextension = {CVAR_READONLY, "pr_checkextension", "1"};
 cvar_t nomonsters = {0, "nomonsters", "0"};
 cvar_t gamecfg = {0, "gamecfg", "0"};
 cvar_t scratch1 = {0, "scratch1", "0"};
@@ -68,19 +72,11 @@ cvar_t      nehx18 = {0, "nehx18", "0"};cvar_t      nehx19 = {0, "nehx19", "0"};
 cvar_t cutscene = {0, "cutscene", "1"};
 // LordHavoc: optional runtime bounds checking (speed drain, but worth it for security, on by default - breaks most QCCX features (used by CRMod and others))
 cvar_t pr_boundscheck = {0, "pr_boundscheck", "1"};
+// LordHavoc: prints every opcode as it executes - warning: this is significant spew
+cvar_t pr_traceqc = {0, "pr_traceqc", "0"};
 
-#define        MAX_FIELD_LEN   64
-#define GEFV_CACHESIZE 2
-
-typedef struct {
-       ddef_t  *pcache;
-       char    field[MAX_FIELD_LEN];
-} gefv_cache;
-
-static gefv_cache      gefvCache[GEFV_CACHESIZE] = {{NULL, ""}, {NULL, ""}};
-
-ddef_t *ED_FindField (char *name);
-dfunction_t *ED_FindFunction (char *name);
+ddef_t *ED_FindField (const char *name);
+mfunction_t *PRVM_ED_FindFunction (const char *name);
 
 // LordHavoc: in an effort to eliminate time wasted on GetEdictFieldValue...  these are defined as externs in progs.h
 int eval_gravity;
@@ -90,6 +86,8 @@ int eval_button5;
 int eval_button6;
 int eval_button7;
 int eval_button8;
+int eval_buttonuse;
+int eval_buttonchat;
 int eval_glow_size;
 int eval_glow_trail;
 int eval_glow_color;
@@ -116,11 +114,29 @@ int eval_ping;
 int eval_movement;
 int eval_pmodel;
 int eval_punchvector;
-
-dfunction_t *SV_PlayerPhysicsQC;
-dfunction_t *EndFrameQC;
-
-int FindFieldOffset(char *field)
+int eval_viewzoom;
+int eval_clientcolors;
+int eval_tag_entity;
+int eval_tag_index;
+int eval_light_lev;
+int eval_color;
+int eval_style;
+int eval_pflags;
+int eval_cursor_active;
+int eval_cursor_screen;
+int eval_cursor_trace_start;
+int eval_cursor_trace_endpos;
+int eval_cursor_trace_ent;
+int eval_colormod;
+int eval_playermodel;
+int eval_playerskin;
+
+mfunction_t *SV_PlayerPhysicsQC;
+mfunction_t *EndFrameQC;
+//KrimZon - SERVER COMMANDS IN QUAKEC
+mfunction_t *SV_ParseClientCommandQC;
+
+int FindFieldOffset(const char *field)
 {
        ddef_t *d;
        d = ED_FindField(field);
@@ -138,6 +154,8 @@ void FindEdictFieldOffsets(void)
        eval_button6 = FindFieldOffset("button6");
        eval_button7 = FindFieldOffset("button7");
        eval_button8 = FindFieldOffset("button8");
+       eval_buttonuse = FindFieldOffset("buttonuse");
+       eval_buttonchat = FindFieldOffset("buttonchat");
        eval_glow_size = FindFieldOffset("glow_size");
        eval_glow_trail = FindFieldOffset("glow_trail");
        eval_glow_color = FindFieldOffset("glow_color");
@@ -164,12 +182,30 @@ void FindEdictFieldOffsets(void)
        eval_movement = FindFieldOffset("movement");
        eval_pmodel = FindFieldOffset("pmodel");
        eval_punchvector = FindFieldOffset("punchvector");
+       eval_viewzoom = FindFieldOffset("viewzoom");
+       eval_clientcolors = FindFieldOffset("clientcolors");
+       eval_tag_entity = FindFieldOffset("tag_entity");
+       eval_tag_index = FindFieldOffset("tag_index");
+       eval_light_lev = FindFieldOffset("light_lev");
+       eval_color = FindFieldOffset("color");
+       eval_style = FindFieldOffset("style");
+       eval_pflags = FindFieldOffset("pflags");
+       eval_cursor_active = FindFieldOffset("cursor_active");
+       eval_cursor_screen = FindFieldOffset("cursor_screen");
+       eval_cursor_trace_start = FindFieldOffset("cursor_trace_start");
+       eval_cursor_trace_endpos = FindFieldOffset("cursor_trace_endpos");
+       eval_cursor_trace_ent = FindFieldOffset("cursor_trace_ent");
+       eval_colormod = FindFieldOffset("colormod");
+       eval_playermodel = FindFieldOffset("playermodel");
+       eval_playerskin = FindFieldOffset("playerskin");
 
        // LordHavoc: allowing QuakeC to override the player movement code
-       SV_PlayerPhysicsQC = ED_FindFunction ("SV_PlayerPhysics");
+       SV_PlayerPhysicsQC = PRVM_ED_FindFunction ("SV_PlayerPhysics");
        // LordHavoc: support for endframe
-       EndFrameQC = ED_FindFunction ("EndFrame");
-};
+       EndFrameQC = PRVM_ED_FindFunction ("EndFrame");
+       //KrimZon - SERVER COMMANDS IN QUAKEC
+       SV_ParseClientCommandQC = PRVM_ED_FindFunction ("SV_ParseClientCommand");
+}
 
 /*
 =================
@@ -178,10 +214,31 @@ ED_ClearEdict
 Sets everything to NULL
 =================
 */
-void ED_ClearEdict (edict_t *e)
+void ED_ClearEdict (prvm_edict_t *e)
 {
-       memset (&e->v, 0, progs->entityfields * 4);
-       e->free = false;
+       int num;
+       memset (e->v, 0, progs->entityfields * 4);
+       e->priv.server->free = false;
+       // LordHavoc: for consistency set these here
+       num = PRVM_NUM_FOR_EDICT(e) - 1;
+       if (num >= 0 && num < svs.maxclients)
+       {
+               prvm_eval_t *val;
+               // set colormap and team on newly created player entity
+               e->fields.server->colormap = num + 1;
+               e->fields.server->team = (svs.clients[num].colors & 15) + 1;
+               // set netname/clientcolors back to client values so that
+               // DP_SV_CLIENTNAME and DPV_SV_CLIENTCOLORS will not immediately
+               // reset them
+               e->fields.server->netname = PRVM_SetEngineString(svs.clients[num].name);
+               if ((val = PRVM_GETEDICTFIELDVALUE(e, eval_clientcolors)))
+                       val->_float = svs.clients[num].colors;
+               // NEXUIZ_PLAYERMODEL and NEXUIZ_PLAYERSKIN
+               if( eval_playermodel )
+                       PRVM_GETEDICTFIELDVALUE(host_client->edict, eval_playermodel)->string = PRVM_SetEngineString(svs.clients[num].playermodel);
+               if( eval_playerskin )
+                       PRVM_GETEDICTFIELDVALUE(host_client->edict, eval_playerskin)->string = PRVM_SetEngineString(svs.clients[num].playerskin);
+       }
 }
 
 /*
@@ -195,28 +252,30 @@ instead of being removed and recreated, which can cause interpolated
 angles and bad trails.
 =================
 */
-edict_t *ED_Alloc (void)
+prvm_edict_t *ED_Alloc (void)
 {
        int                     i;
-       edict_t         *e;
+       prvm_edict_t            *e;
 
-       for ( i=svs.maxclients+1 ; i<sv.num_edicts ; i++)
+       for (i = svs.maxclients + 1;i < prog->num_edicts;i++)
        {
-               e = EDICT_NUM(i);
+               e = PRVM_EDICT_NUM(i);
                // the first couple seconds of server time can involve a lot of
                // freeing and allocating, so relax the replacement policy
-               if (e->free && ( e->freetime < 2 || sv.time - e->freetime > 0.5 ) )
+               if (e->priv.server->free && ( e->priv.server->freetime < 2 || sv.time - e->priv.server->freetime > 0.5 ) )
                {
                        ED_ClearEdict (e);
                        return e;
                }
        }
-       
+
        if (i == MAX_EDICTS)
                Host_Error ("ED_Alloc: no free edicts");
-               
-       sv.num_edicts++;
-       e = EDICT_NUM(i);
+
+       prog->num_edicts++;
+       if (prog->num_edicts >= prog->max_edicts)
+               SV_IncreaseEdicts();
+       e = PRVM_EDICT_NUM(i);
        ED_ClearEdict (e);
 
        return e;
@@ -230,23 +289,23 @@ Marks the edict as free
 FIXME: walk all entities and NULL out references to this entity
 =================
 */
-void ED_Free (edict_t *ed)
+void ED_Free (prvm_edict_t *ed)
 {
        SV_UnlinkEdict (ed);            // unlink from world bsp
 
-       ed->free = true;
-       ed->v.model = 0;
-       ed->v.takedamage = 0;
-       ed->v.modelindex = 0;
-       ed->v.colormap = 0;
-       ed->v.skin = 0;
-       ed->v.frame = 0;
-       VectorClear(ed->v.origin);
-       VectorClear(ed->v.angles);
-       ed->v.nextthink = -1;
-       ed->v.solid = 0;
-       
-       ed->freetime = sv.time;
+       ed->priv.server->free = true;
+       ed->fields.server->model = 0;
+       ed->fields.server->takedamage = 0;
+       ed->fields.server->modelindex = 0;
+       ed->fields.server->colormap = 0;
+       ed->fields.server->skin = 0;
+       ed->fields.server->frame = 0;
+       VectorClear(ed->fields.server->origin);
+       VectorClear(ed->fields.server->angles);
+       ed->fields.server->nextthink = -1;
+       ed->fields.server->solid = 0;
+
+       ed->priv.server->freetime = sv.time;
 }
 
 //===========================================================================
@@ -260,7 +319,7 @@ ddef_t *ED_GlobalAtOfs (int ofs)
 {
        ddef_t          *def;
        int                     i;
-       
+
        for (i=0 ; i<progs->numglobaldefs ; i++)
        {
                def = &pr_globaldefs[i];
@@ -279,7 +338,7 @@ ddef_t *ED_FieldAtOfs (int ofs)
 {
        ddef_t          *def;
        int                     i;
-       
+
        for (i=0 ; i<progs->numfielddefs ; i++)
        {
                def = &pr_fielddefs[i];
@@ -294,15 +353,15 @@ ddef_t *ED_FieldAtOfs (int ofs)
 ED_FindField
 ============
 */
-ddef_t *ED_FindField (char *name)
+ddef_t *ED_FindField (const char *name)
 {
-       ddef_t          *def;
-       int                     i;
+       ddef_t *def;
+       int i;
 
        for (i=0 ; i<progs->numfielddefs ; i++)
        {
                def = &pr_fielddefs[i];
-               if (!strcmp(pr_strings + def->s_name,name) )
+               if (!strcmp(PRVM_GetString(def->s_name), name))
                        return def;
        }
        return NULL;
@@ -313,15 +372,15 @@ ddef_t *ED_FindField (char *name)
 ED_FindGlobal
 ============
 */
-ddef_t *ED_FindGlobal (char *name)
+ddef_t *ED_FindGlobal (const char *name)
 {
-       ddef_t          *def;
-       int                     i;
-       
+       ddef_t *def;
+       int i;
+
        for (i=0 ; i<progs->numglobaldefs ; i++)
        {
                def = &pr_globaldefs[i];
-               if (!strcmp(pr_strings + def->s_name,name) )
+               if (!strcmp(PRVM_GetString(def->s_name), name))
                        return def;
        }
        return NULL;
@@ -330,18 +389,18 @@ ddef_t *ED_FindGlobal (char *name)
 
 /*
 ============
-ED_FindFunction
+PRVM_ED_FindFunction
 ============
 */
-dfunction_t *ED_FindFunction (char *name)
+mfunction_t *PRVM_ED_FindFunction (const char *name)
 {
-       dfunction_t             *func;
+       mfunction_t             *func;
        int                             i;
-       
+
        for (i=0 ; i<progs->numfunctions ; i++)
        {
-               func = &pr_functions[i];
-               if (!strcmp(pr_strings + func->s_name,name) )
+               func = &prog->functions[i];
+               if (!strcmp(PRVM_GetString(func->s_name), name))
                        return func;
        }
        return NULL;
@@ -349,51 +408,18 @@ dfunction_t *ED_FindFunction (char *name)
 
 
 /*
-eval_t *GetEdictFieldValue(edict_t *ed, char *field)
-{
-       ddef_t                  *def = NULL;
-       int                             i;
-       static int              rep = 0;
-
-       for (i=0 ; i<GEFV_CACHESIZE ; i++)
-       {
-               if (!strcmp(field, gefvCache[i].field))
-               {
-                       def = gefvCache[i].pcache;
-                       goto Done;
-               }
-       }
-
-       def = ED_FindField (field);
-
-       if (strlen(field) < MAX_FIELD_LEN)
-       {
-               gefvCache[rep].pcache = def;
-               strcpy (gefvCache[rep].field, field);
-               rep ^= 1;
-       }
-
-Done:
-       if (!def)
-               return NULL;
-
-       return (eval_t *)((char *)&ed->v + def->ofs*4);
-}
-*/
-
-/*
 ============
 PR_ValueString
 
 Returns a string describing *data in a type specific manner
 =============
 */
-int NoCrash_NUM_FOR_EDICT(edict_t *e);
-char *PR_ValueString (etype_t type, eval_t *val)
+//int NoCrash_NUM_FOR_EDICT(prvm_edict_t *e);
+char *PR_ValueString (etype_t type, prvm_eval_t *val)
 {
        static char line[1024]; // LordHavoc: enlarged a bit (was 256)
        ddef_t *def;
-       dfunction_t *f;
+       mfunction_t *f;
        int n;
 
        type &= ~DEF_SAVEGLOBAL;
@@ -401,42 +427,43 @@ char *PR_ValueString (etype_t type, eval_t *val)
        switch (type)
        {
        case ev_string:
-               sprintf (line, "%s", pr_strings + val->string);
+               strlcpy (line, PRVM_GetString (val->string), sizeof (line));
                break;
        case ev_entity:
-               n = NoCrash_NUM_FOR_EDICT(PROG_TO_EDICT(val->edict));
+               //n = NoCrash_NUM_FOR_EDICT(PRVM_PROG_TO_EDICT(val->edict));
+               n = val->edict;
                if (n < 0 || n >= MAX_EDICTS)
-                       sprintf (line, "entity %i (invalid!)", n);
+                       dpsnprintf (line, sizeof (line), "entity %i (invalid!)", n);
                else
-                       sprintf (line, "entity %i", n);
+                       dpsnprintf (line, sizeof (line), "entity %i", n);
                break;
        case ev_function:
-               f = pr_functions + val->function;
-               sprintf (line, "%s()", pr_strings + f->s_name);
+               f = prog->functions + val->function;
+               dpsnprintf (line, sizeof (line), "%s()", PRVM_GetString(f->s_name));
                break;
        case ev_field:
                def = ED_FieldAtOfs ( val->_int );
-               sprintf (line, ".%s", pr_strings + def->s_name);
+               dpsnprintf (line, sizeof (line), ".%s", PRVM_GetString(def->s_name));
                break;
        case ev_void:
-               sprintf (line, "void");
+               dpsnprintf (line, sizeof (line), "void");
                break;
        case ev_float:
                // LordHavoc: changed from %5.1f to %10.4f
-               sprintf (line, "%10.4f", val->_float);
+               dpsnprintf (line, sizeof (line), "%10.4f", val->_float);
                break;
        case ev_vector:
                // LordHavoc: changed from %5.1f to %10.4f
-               sprintf (line, "'%10.4f %10.4f %10.4f'", val->vector[0], val->vector[1], val->vector[2]);
+               dpsnprintf (line, sizeof (line), "'%10.4f %10.4f %10.4f'", val->vector[0], val->vector[1], val->vector[2]);
                break;
        case ev_pointer:
-               sprintf (line, "pointer");
+               dpsnprintf (line, sizeof (line), "pointer");
                break;
        default:
-               sprintf (line, "bad type %i", type);
+               dpsnprintf (line, sizeof (line), "bad type %i", type);
                break;
        }
-       
+
        return line;
 }
 
@@ -448,44 +475,66 @@ Returns a string describing *data in a type specific manner
 Easier to parse than PR_ValueString
 =============
 */
-char *PR_UglyValueString (etype_t type, eval_t *val)
+char *PR_UglyValueString (etype_t type, prvm_eval_t *val)
 {
-       static char     line[256];
-       ddef_t          *def;
-       dfunction_t     *f;
-       
+       static char line[4096];
+       int i;
+       const char *s;
+       ddef_t *def;
+       mfunction_t *f;
+
        type &= ~DEF_SAVEGLOBAL;
 
        switch (type)
        {
        case ev_string:
-               sprintf (line, "%s", pr_strings + val->string);
+               // Parse the string a bit to turn special characters
+               // (like newline, specifically) into escape codes,
+               // this fixes saving games from various mods
+               s = PRVM_GetString (val->string);
+               for (i = 0;i < (int)sizeof(line) - 2 && *s;)
+               {
+                       if (*s == '\n')
+                       {
+                               line[i++] = '\\';
+                               line[i++] = 'n';
+                       }
+                       else if (*s == '\r')
+                       {
+                               line[i++] = '\\';
+                               line[i++] = 'r';
+                       }
+                       else
+                               line[i++] = *s;
+                       s++;
+               }
+               line[i] = '\0';
                break;
        case ev_entity:
-               sprintf (line, "%i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict)));
+               dpsnprintf (line, sizeof (line), "%i", PRVM_NUM_FOR_EDICT(PRVM_PROG_TO_EDICT(val->edict)));
                break;
        case ev_function:
-               f = pr_functions + val->function;
-               sprintf (line, "%s", pr_strings + f->s_name);
+               f = prog->functions + val->function;
+               strlcpy (line, PRVM_GetString (f->s_name), sizeof (line));
                break;
        case ev_field:
                def = ED_FieldAtOfs ( val->_int );
-               sprintf (line, "%s", pr_strings + def->s_name);
+               dpsnprintf (line, sizeof (line), ".%s", PRVM_GetString(def->s_name));
                break;
        case ev_void:
-               sprintf (line, "void");
+               dpsnprintf (line, sizeof (line), "void");
                break;
        case ev_float:
-               sprintf (line, "%f", val->_float);
+               dpsnprintf (line, sizeof (line), "%f", val->_float);
                break;
        case ev_vector:
-               sprintf (line, "%f %f %f", val->vector[0], val->vector[1], val->vector[2]);
+               dpsnprintf (line, sizeof (line), "%f %f %f", val->vector[0], val->vector[1], val->vector[2]);
                break;
        default:
-               sprintf (line, "bad type %i", type);
+               dpsnprintf (line, sizeof (line), "bad type %i", type);
                break;
        }
-       
+
        return line;
 }
 
@@ -508,17 +557,17 @@ char *PR_GlobalString (int ofs)
        val = (void *)&pr_globals[ofs];
        def = ED_GlobalAtOfs(ofs);
        if (!def)
-               sprintf (line,"%i(\?\?\?)", ofs); // LordHavoc: escaping the ?s so it is not a trigraph
+               dpsnprintf (line, sizeof (line), "%i(?)", ofs);
        else
        {
                s = PR_ValueString (def->type, val);
-               sprintf (line,"%i(%s)%s", ofs, pr_strings + def->s_name, s);
+               dpsnprintf (line, sizeof (line), "%i(%s)%s", ofs, PRVM_GetString(def->s_name), s);
        }
 
        i = strlen(line);
        for ( ; i<20 ; i++)
-               strcat (line," ");
-       strcat (line," ");
+               strlcat (line, " ", sizeof (line));
+       strlcat (line, " ", sizeof (line));
 
        return line;
 }
@@ -531,14 +580,14 @@ char *PR_GlobalStringNoContents (int ofs)
 
        def = ED_GlobalAtOfs(ofs);
        if (!def)
-               sprintf (line,"%i(\?\?\?)", ofs); // LordHavoc: escaping the ?s so it is not a trigraph
+               dpsnprintf (line, sizeof (line), "%i(?)", ofs);
        else
-               sprintf (line,"%i(%s)", ofs, pr_strings + def->s_name);
+               dpsnprintf (line, sizeof (line), "%i(%s)", ofs, PRVM_GetString(def->s_name));
 
        i = strlen(line);
        for ( ; i<20 ; i++)
-               strcat (line," ");
-       strcat (line," ");
+               strlcat (line, " ", sizeof (line));
+       strlcat (line, " ", sizeof (line));
 
        return line;
 }
@@ -553,32 +602,32 @@ For debugging
 */
 // LordHavoc: optimized this to print out much more quickly (tempstring)
 // LordHavoc: changed to print out every 4096 characters (incase there are a lot of fields to print)
-void ED_Print (edict_t *ed)
+void ED_Print(prvm_edict_t *ed)
 {
        int             l;
        ddef_t  *d;
        int             *v;
        int             i, j;
-       char    *name;
+       const char      *name;
        int             type;
        char    tempstring[8192], tempstring2[260]; // temporary string buffers
 
-       if (ed->free)
+       if (ed->priv.server->free)
        {
-               Con_Print("FREE\n");
+               Con_Print("FREE\n");
                return;
        }
 
        tempstring[0] = 0;
-       sprintf(tempstring, "\nEDICT %i:\n", NUM_FOR_EDICT(ed));
+       dpsnprintf (tempstring, sizeof (tempstring), "\nEDICT %i:\n", PRVM_NUM_FOR_EDICT(ed));
        for (i=1 ; i<progs->numfielddefs ; i++)
        {
                d = &pr_fielddefs[i];
-               name = pr_strings + d->s_name;
+               name = PRVM_GetString(d->s_name);
                if (name[strlen(name)-2] == '_')
                        continue;       // skip _x, _y, _z vars
-                       
-               v = (int *)((char *)&ed->v + d->ofs*4);
+
+               v = (int *)((char *)ed->v + d->ofs*4);
 
        // if the value is still all 0, skip the field
                type = d->type & ~DEF_SAVEGLOBAL;
@@ -591,34 +640,34 @@ void ED_Print (edict_t *ed)
 
                if (strlen(name) > 256)
                {
-                       strncpy(tempstring2, name, 256);
+                       memcpy (tempstring2, name, 256);
                        tempstring2[256] = tempstring2[257] = tempstring2[258] = '.';
                        tempstring2[259] = 0;
                        name = tempstring2;
                }
-               strcat(tempstring, name);
+               strlcat (tempstring, name, sizeof (tempstring));
                for (l = strlen(name);l < 14;l++)
                        strcat(tempstring, " ");
                strcat(tempstring, " ");
 
-               name = PR_ValueString(d->type, (eval_t *)v);
+               name = PR_ValueString(d->type, (prvm_eval_t *)v);
                if (strlen(name) > 256)
                {
-                       strncpy(tempstring2, name, 256);
+                       memcpy(tempstring2, name, 256);
                        tempstring2[256] = tempstring2[257] = tempstring2[258] = '.';
                        tempstring2[259] = 0;
                        name = tempstring2;
                }
-               strcat(tempstring, name);
-               strcat(tempstring, "\n");
+               strlcat (tempstring, name, sizeof (tempstring));
+               strlcat (tempstring, "\n", sizeof (tempstring));
                if (strlen(tempstring) >= 4096)
                {
-                       Con_Printf("%s", tempstring);
+                       Con_Print(tempstring);
                        tempstring[0] = 0;
                }
        }
        if (tempstring[0])
-               Con_Printf("%s", tempstring);
+               Con_Print(tempstring);
 }
 
 /*
@@ -628,30 +677,30 @@ ED_Write
 For savegames
 =============
 */
-void ED_Write (QFile *f, edict_t *ed)
+void ED_Write (qfile_t *f, prvm_edict_t *ed)
 {
        ddef_t  *d;
        int             *v;
        int             i, j;
-       char    *name;
+       const char      *name;
        int             type;
 
-       Qprintf (f, "{\n");
+       FS_Print(f, "{\n");
 
-       if (ed->free)
+       if (ed->priv.server->free)
        {
-               Qprintf (f, "}\n");
+               FS_Print(f, "}\n");
                return;
        }
-       
+
        for (i=1 ; i<progs->numfielddefs ; i++)
        {
                d = &pr_fielddefs[i];
-               name = pr_strings + d->s_name;
+               name = PRVM_GetString(d->s_name);
                if (name[strlen(name)-2] == '_')
                        continue;       // skip _x, _y, _z vars
 
-               v = (int *)((char *)&ed->v + d->ofs*4);
+               v = (int *)((char *)ed->v + d->ofs*4);
 
        // if the value is still all 0, skip the field
                type = d->type & ~DEF_SAVEGLOBAL;
@@ -661,16 +710,16 @@ void ED_Write (QFile *f, edict_t *ed)
                if (j == type_size[type])
                        continue;
 
-               Qprintf (f,"\"%s\" ",name);
-               Qprintf (f,"\"%s\"\n", PR_UglyValueString(d->type, (eval_t *)v));
+               FS_Printf(f,"\"%s\" ",name);
+               FS_Printf(f,"\"%s\"\n", PR_UglyValueString(d->type, (prvm_eval_t *)v));
        }
 
-       Qprintf (f, "}\n");
+       FS_Print(f, "}\n");
 }
 
 void ED_PrintNum (int ent)
 {
-       ED_Print (EDICT_NUM(ent));
+       ED_Print(PRVM_EDICT_NUM(ent));
 }
 
 /*
@@ -683,9 +732,9 @@ For debugging, prints all the entities in the current server
 void ED_PrintEdicts (void)
 {
        int             i;
-       
-       Con_Printf ("%i entities\n", sv.num_edicts);
-       for (i=0 ; i<sv.num_edicts ; i++)
+
+       Con_Printf("%i entities\n", prog->num_edicts);
+       for (i=0 ; i<prog->num_edicts ; i++)
                ED_PrintNum (i);
 }
 
@@ -693,17 +742,17 @@ void ED_PrintEdicts (void)
 =============
 ED_PrintEdict_f
 
-For debugging, prints a single edicy
+For debugging, prints a single edict
 =============
 */
 void ED_PrintEdict_f (void)
 {
        int             i;
-       
+
        i = atoi (Cmd_Argv(1));
-       if (i >= sv.num_edicts)
+       if (i < 0 || i >= prog->num_edicts)
        {
-               Con_Printf("Bad edict number\n");
+               Con_Print("Bad edict number\n");
                return;
        }
        ED_PrintNum (i);
@@ -719,29 +768,29 @@ For debugging
 void ED_Count (void)
 {
        int             i;
-       edict_t *ent;
+       prvm_edict_t    *ent;
        int             active, models, solid, step;
 
        active = models = solid = step = 0;
-       for (i=0 ; i<sv.num_edicts ; i++)
+       for (i=0 ; i<prog->num_edicts ; i++)
        {
-               ent = EDICT_NUM(i);
-               if (ent->free)
+               ent = PRVM_EDICT_NUM(i);
+               if (ent->priv.server->free)
                        continue;
                active++;
-               if (ent->v.solid)
+               if (ent->fields.server->solid)
                        solid++;
-               if (ent->v.model)
+               if (ent->fields.server->model)
                        models++;
-               if (ent->v.movetype == MOVETYPE_STEP)
+               if (ent->fields.server->movetype == MOVETYPE_STEP)
                        step++;
        }
 
-       Con_Printf ("num_edicts:%3i\n", sv.num_edicts);
-       Con_Printf ("active    :%3i\n", active);
-       Con_Printf ("view      :%3i\n", models);
-       Con_Printf ("touch     :%3i\n", solid);
-       Con_Printf ("step      :%3i\n", step);
+       Con_Printf("num_edicts:%3i\n", prog->num_edicts);
+       Con_Printf("active    :%3i\n", active);
+       Con_Printf("view      :%3i\n", models);
+       Con_Printf("touch     :%3i\n", solid);
+       Con_Printf("step      :%3i\n", step);
 
 }
 
@@ -759,14 +808,14 @@ FIXME: need to tag constants, doesn't really work
 ED_WriteGlobals
 =============
 */
-void ED_WriteGlobals (QFile *f)
+void ED_WriteGlobals (qfile_t *f)
 {
        ddef_t          *def;
        int                     i;
-       char            *name;
+       const char              *name;
        int                     type;
 
-       Qprintf (f,"{\n");
+       FS_Print(f,"{\n");
        for (i=0 ; i<progs->numglobaldefs ; i++)
        {
                def = &pr_globaldefs[i];
@@ -778,11 +827,39 @@ void ED_WriteGlobals (QFile *f)
                if (type != ev_string && type != ev_float && type != ev_entity)
                        continue;
 
-               name = pr_strings + def->s_name;                
-               Qprintf (f,"\"%s\" ", name);
-               Qprintf (f,"\"%s\"\n", PR_UglyValueString(type, (eval_t *)&pr_globals[def->ofs]));              
+               name = PRVM_GetString(def->s_name);
+               FS_Printf(f,"\"%s\" ", name);
+               FS_Printf(f,"\"%s\"\n", PR_UglyValueString(type, (prvm_eval_t *)&pr_globals[def->ofs]));
+       }
+       FS_Print(f,"}\n");
+}
+
+/*
+=============
+ED_EdictSet_f
+
+Console command to set a field of a specified edict
+=============
+*/
+void ED_EdictSet_f(void)
+{
+       prvm_edict_t *ed;
+       ddef_t *key;
+
+       if(Cmd_Argc() != 4)
+       {
+               Con_Print("edictset <edict number> <field> <value>\n");
+               return;
        }
-       Qprintf (f,"}\n");
+       ed = PRVM_EDICT_NUM(atoi(Cmd_Argv(1)));
+
+       if((key = ED_FindField(Cmd_Argv(2))) == 0)
+       {
+               Con_Printf("Key %s not found !\n", Cmd_Argv(2));
+               return;
+       }
+
+       ED_ParseEpair(ed, key, Cmd_Argv(3));
 }
 
 /*
@@ -790,25 +867,23 @@ void ED_WriteGlobals (QFile *f)
 ED_ParseGlobals
 =============
 */
-void ED_ParseGlobals (char *data)
+void ED_ParseGlobals (const char *data)
 {
-       char    keyname[1024]; // LordHavoc: good idea? bad idea?  was 64
-       ddef_t  *key;
+       char keyname[1024]; // LordHavoc: good idea? bad idea?  was 64
+       ddef_t *key;
 
        while (1)
-       {       
-       // parse key
-               data = COM_Parse (data);
+       {
+               // parse key
+               if (!COM_ParseToken(&data, false))
+                       Host_Error ("ED_ParseEntity: EOF without closing brace");
                if (com_token[0] == '}')
                        break;
-               if (!data)
-                       Host_Error ("ED_ParseEntity: EOF without closing brace");
 
                strcpy (keyname, com_token);
 
-       // parse value
-               data = COM_Parse (data);
-               if (!data)
+               // parse value
+               if (!COM_ParseToken(&data, false))
                        Host_Error ("ED_ParseEntity: EOF without closing brace");
 
                if (com_token[0] == '}')
@@ -817,11 +892,11 @@ void ED_ParseGlobals (char *data)
                key = ED_FindGlobal (keyname);
                if (!key)
                {
-                       Con_DPrintf ("'%s' is not a global\n", keyname);
+                       Con_DPrintf("'%s' is not a global\n", keyname);
                        continue;
                }
 
-               if (!ED_ParseEpair ((void *)pr_globals, key, com_token))
+               if (!ED_ParseEpair(NULL, key, com_token))
                        Host_Error ("ED_ParseGlobals: parse error");
        }
 }
@@ -831,107 +906,105 @@ void ED_ParseGlobals (char *data)
 
 /*
 =============
-ED_NewString
-=============
-*/
-char *ED_NewString (char *string)
-{
-       char    *new, *new_p;
-       int             i,l;
-
-       l = strlen(string) + 1;
-       new = Mem_Alloc(edictstring_mempool, l);
-       new_p = new;
-
-       for (i=0 ; i< l ; i++)
-       {
-               if (string[i] == '\\' && i < l-1)
-               {
-                       i++;
-                       if (string[i] == 'n')
-                               *new_p++ = '\n';
-                       else
-                               *new_p++ = '\\';
-               }
-               else
-                       *new_p++ = string[i];
-       }
-
-       return new;
-}
-
-
-/*
-=============
 ED_ParseEval
 
 Can parse either fields or globals
 returns false if error
 =============
 */
-qboolean       ED_ParseEpair (void *base, ddef_t *key, char *s)
+qboolean ED_ParseEpair(prvm_edict_t *ent, ddef_t *key, const char *s)
 {
-       int             i;
-       char    string[128];
-       ddef_t  *def;
-       char    *v, *w;
-       void    *d;
-       dfunction_t     *func;
-
-       d = (void *)((int *)base + key->ofs);
+       int i, l;
+       char *new_p;
+       ddef_t *def;
+       prvm_eval_t *val;
+       mfunction_t *func;
 
+       if (ent)
+               val = (prvm_eval_t *)((int *)ent->v + key->ofs);
+       else
+               val = (prvm_eval_t *)((int *)pr_globals + key->ofs);
        switch (key->type & ~DEF_SAVEGLOBAL)
        {
        case ev_string:
-               *(string_t *)d = ED_NewString (s) - pr_strings;
+               l = strlen(s) + 1;
+               new_p = PR_AllocString(l);
+               val->string = PR_SetQCString(new_p);
+               for (i = 0;i < l;i++)
+               {
+                       if (s[i] == '\\' && i < l-1)
+                       {
+                               i++;
+                               if (s[i] == 'n')
+                                       *new_p++ = '\n';
+                               else if (s[i] == 'r')
+                                       *new_p++ = '\r';
+                               else
+                                       *new_p++ = s[i];
+                       }
+                       else
+                               *new_p++ = s[i];
+               }
                break;
-               
+
        case ev_float:
-               *(float *)d = atof (s);
+               while (*s && *s <= ' ')
+                       s++;
+               val->_float = atof(s);
                break;
-               
+
        case ev_vector:
-               strcpy (string, s);
-               v = string;
-               w = string;
-               for (i=0 ; i<3 ; i++)
+               for (i = 0;i < 3;i++)
                {
-                       while (*v && *v != ' ')
-                               v++;
-                       *v = 0;
-                       ((float *)d)[i] = atof (w);
-                       w = v = v+1;
+                       while (*s && *s <= ' ')
+                               s++;
+                       if (*s)
+                               val->vector[i] = atof(s);
+                       else
+                               val->vector[i] = 0;
+                       while (*s > ' ')
+                               s++;
                }
                break;
 
        case ev_entity:
-               *(int *)d = EDICT_TO_PROG(EDICT_NUM(atoi (s)));
+               while (*s && *s <= ' ')
+                       s++;
+               i = atoi(s);
+               if (i < 0 || i >= MAX_EDICTS)
+                       Con_Printf("ED_ParseEpair: ev_entity reference too large (edict %i >= MAX_EDICTS %i)\n", i, MAX_EDICTS);
+               while (i >= prog->max_edicts)
+                       SV_IncreaseEdicts();
+               // if SV_IncreaseEdicts was called the base pointer needs to be updated
+               if (ent)
+                       val = (prvm_eval_t *)((int *)ent->v + key->ofs);
+               val->edict = PRVM_EDICT_TO_PROG(PRVM_EDICT_NUM(i));
                break;
-               
+
        case ev_field:
-               def = ED_FindField (s);
+               def = ED_FindField(s);
                if (!def)
                {
-                       // LordHavoc: don't warn about worldspawn sky/fog fields because they don't require mod support
-                       if (strcmp(s, "sky") && strcmp(s, "fog") && strncmp(s, "fog_", 4) && strcmp(s, "farclip"))
-                               Con_DPrintf ("Can't find field %s\n", s);
+                       Con_DPrintf("ED_ParseEpair: Can't find field %s\n", s);
                        return false;
                }
-               *(int *)d = G_INT(def->ofs);
+               //val->_int = PRVM_G_INT(def->ofs); // AK Please check this - seems to be an org. quake bug
+               val->_int = def->ofs;
                break;
-       
+
        case ev_function:
-               func = ED_FindFunction (s);
+               func = PRVM_ED_FindFunction(s);
                if (!func)
                {
-                       Con_DPrintf ("Can't find function %s\n", s);
+                       Con_Printf("ED_ParseEpair: Can't find function %s\n", s);
                        return false;
                }
-               *(func_t *)d = func - pr_functions;
+               val->function = func - prog->functions;
                break;
 
        default:
-               break;
+               Con_Printf("ED_ParseEpair: Unknown key->type %i for key \"%s\"\n", key->type, PRVM_GetString(key->s_name));
+               return false;
        }
        return true;
 }
@@ -945,45 +1018,40 @@ ed should be a properly initialized empty edict.
 Used for initial level load and for savegames.
 ====================
 */
-char *ED_ParseEdict (char *data, edict_t *ent)
+const char *ED_ParseEdict (const char *data, prvm_edict_t *ent)
 {
-       ddef_t          *key;
-       qboolean        anglehack;
-       qboolean        init;
-       char            keyname[256];
-       int                     n;
+       ddef_t *key;
+       qboolean anglehack;
+       qboolean init;
+       char keyname[256];
+       int n;
 
        init = false;
 
 // clear it
-       if (ent != sv.edicts)   // hack
-               memset (&ent->v, 0, progs->entityfields * 4);
+       if (ent != prog->edicts)        // hack
+               memset (ent->v, 0, progs->entityfields * 4);
 
 // go through all the dictionary pairs
        while (1)
        {
        // parse key
-               data = COM_Parse (data);
+               if (!COM_ParseToken(&data, false))
+                       Host_Error ("ED_ParseEntity: EOF without closing brace");
                if (com_token[0] == '}')
                        break;
-               if (!data)
-                       Host_Error ("ED_ParseEntity: EOF without closing brace");
 
                // anglehack is to allow QuakeEd to write single scalar angles
                // and allow them to be turned into vectors. (FIXME...)
-               if (!strcmp(com_token, "angle"))
-               {
-                       strcpy (com_token, "angles");
-                       anglehack = true;
-               }
-               else
-                       anglehack = false;
+               anglehack = !strcmp (com_token, "angle");
+               if (anglehack)
+                       strlcpy (com_token, "angles", sizeof (com_token));
 
                // FIXME: change light to _light to get rid of this hack
                if (!strcmp(com_token, "light"))
-                       strcpy (com_token, "light_lev");        // hack for single light def
+                       strlcpy (com_token, "light_lev", sizeof (com_token));   // hack for single light def
 
-               strcpy (keyname, com_token);
+               strlcpy (keyname, com_token, sizeof (keyname));
 
                // another hack to fix heynames with trailing spaces
                n = strlen(keyname);
@@ -994,8 +1062,7 @@ char *ED_ParseEdict (char *data, edict_t *ent)
                }
 
        // parse value
-               data = COM_Parse (data);
-               if (!data)
+               if (!COM_ParseToken(&data, false))
                        Host_Error ("ED_ParseEntity: EOF without closing brace");
 
                if (com_token[0] == '}')
@@ -1011,23 +1078,23 @@ char *ED_ParseEdict (char *data, edict_t *ent)
                key = ED_FindField (keyname);
                if (!key)
                {
-                       Con_DPrintf ("'%s' is not a field\n", keyname);
+                       Con_DPrintf("'%s' is not a field\n", keyname);
                        continue;
                }
 
                if (anglehack)
                {
                        char    temp[32];
-                       strcpy (temp, com_token);
-                       sprintf (com_token, "0 %s 0", temp);
+                       strlcpy (temp, com_token, sizeof (temp));
+                       dpsnprintf (com_token, sizeof (com_token), "0 %s 0", temp);
                }
 
-               if (!ED_ParseEpair ((void *)&ent->v, key, com_token))
+               if (!ED_ParseEpair(ent, key, com_token))
                        Host_Error ("ED_ParseEdict: parse error");
        }
 
        if (!init)
-               ent->free = true;
+               ent->priv.server->free = true;
 
        return data;
 }
@@ -1048,81 +1115,89 @@ Used for both fresh maps and savegame loads.  A fresh map would also need
 to call ED_CallSpawnFunctions () to let the objects initialize themselves.
 ================
 */
-void ED_LoadFromFile (char *data)
-{      
-       edict_t         *ent;
-       int                     inhibit;
-       dfunction_t     *func;
+void ED_LoadFromFile (const char *data)
+{
+       prvm_edict_t *ent;
+       int parsed, inhibited, spawned, died;
+       mfunction_t *func;
 
        ent = NULL;
-       inhibit = 0;
-       pr_global_struct->time = sv.time;
-       
+       parsed = 0;
+       inhibited = 0;
+       spawned = 0;
+       died = 0;
+       prog->globals.server->time = sv.time;
+
 // parse ents
        while (1)
        {
-// parse the opening brace     
-               data = COM_Parse (data);
-               if (!data)
+// parse the opening brace
+               if (!COM_ParseToken(&data, false))
                        break;
                if (com_token[0] != '{')
                        Host_Error ("ED_LoadFromFile: found %s when expecting {",com_token);
 
                if (!ent)
-                       ent = EDICT_NUM(0);
+                       ent = PRVM_EDICT_NUM(0);
                else
                        ent = ED_Alloc ();
                data = ED_ParseEdict (data, ent);
+               parsed++;
 
 // remove things from different skill levels or deathmatch
-               if (deathmatch.integer)
+               if (gamemode != GAME_TRANSFUSION) //Transfusion does this in QC
                {
-                       if (((int)ent->v.spawnflags & SPAWNFLAG_NOT_DEATHMATCH))
+                       if (deathmatch.integer)
+                       {
+                               if (((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_DEATHMATCH))
+                               {
+                                       ED_Free (ent);
+                                       inhibited++;
+                                       continue;
+                               }
+                       }
+                       else if ((current_skill <= 0 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_EASY  ))
+                               || (current_skill == 1 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_MEDIUM))
+                               || (current_skill >= 2 && ((int)ent->fields.server->spawnflags & SPAWNFLAG_NOT_HARD  )))
                        {
-                               ED_Free (ent);  
-                               inhibit++;
+                               ED_Free (ent);
+                               inhibited++;
                                continue;
                        }
                }
-               else if ((current_skill == 0 && ((int)ent->v.spawnflags & SPAWNFLAG_NOT_EASY  ))
-                         || (current_skill == 1 && ((int)ent->v.spawnflags & SPAWNFLAG_NOT_MEDIUM))
-                         || (current_skill >= 2 && ((int)ent->v.spawnflags & SPAWNFLAG_NOT_HARD  )))
-               {
-                       ED_Free (ent);  
-                       inhibit++;
-                       continue;
-               }
-
 //
 // immediately call spawn function
 //
-               if (!ent->v.classname)
+               if (!ent->fields.server->classname)
                {
-                       Con_Print("No classname for:\n");
-                       ED_Print (ent);
+                       Con_Print("No classname for:\n");
+                       ED_Print(ent);
                        ED_Free (ent);
                        continue;
                }
 
        // look for the spawn function
-               func = ED_FindFunction ( pr_strings + ent->v.classname );
+               func = PRVM_ED_FindFunction (PRVM_GetString(ent->fields.server->classname));
 
                if (!func)
                {
                        if (developer.integer) // don't confuse non-developers with errors
                        {
-                               Con_Print("No spawn function for:\n");
-                               ED_Print (ent);
+                               Con_Print("No spawn function for:\n");
+                               ED_Print(ent);
                        }
                        ED_Free (ent);
                        continue;
                }
 
-               pr_global_struct->self = EDICT_TO_PROG(ent);
-               PR_ExecuteProgram (func - pr_functions, "");
+               prog->globals.server->self = PRVM_EDICT_TO_PROG(ent);
+               PRVM_ExecuteProgram (func - prog->functions, "QC function spawn is missing");
+               spawned++;
+               if (ent->priv.server->free)
+                       died++;
        }
 
-       Con_DPrintf ("%i entities inhibited\n", inhibit);
+       Con_DPrintf("%i entities parsed, %i inhibited, %i spawned (%i removed self, %i stayed)\n", parsed, inhibited, spawned, died, spawned - died);
 }
 
 
@@ -1137,39 +1212,57 @@ dpfield_t;
 
 dpfield_t dpfields[] =
 {
-       {ev_float, "gravity"},
+       {ev_entity, "cursor_trace_ent"},
+       {ev_entity, "drawonlytoclient"},
+       {ev_entity, "exteriormodeltoclient"},
+       {ev_entity, "nodrawtoclient"},
+       {ev_entity, "tag_entity"},
+       {ev_entity, "viewmodelforclient"},
+       {ev_float, "alpha"},
+       {ev_float, "ammo_cells1"},
+       {ev_float, "ammo_lava_nails"},
+       {ev_float, "ammo_multi_rockets"},
+       {ev_float, "ammo_nails1"},
+       {ev_float, "ammo_plasma"},
+       {ev_float, "ammo_rockets1"},
+       {ev_float, "ammo_shells1"},
        {ev_float, "button3"},
        {ev_float, "button4"},
        {ev_float, "button5"},
        {ev_float, "button6"},
        {ev_float, "button7"},
        {ev_float, "button8"},
+       {ev_float, "buttonchat"},
+       {ev_float, "buttonuse"},
+       {ev_float, "clientcolors"},
+       {ev_float, "cursor_active"},
+       {ev_float, "fullbright"},
+       {ev_float, "glow_color"},
        {ev_float, "glow_size"},
        {ev_float, "glow_trail"},
-       {ev_float, "glow_color"},
-       {ev_float, "items2"},
-       {ev_float, "scale"},
-       {ev_float, "alpha"},
-       {ev_float, "renderamt"},
-       {ev_float, "rendermode"},
-       {ev_float, "fullbright"},
-       {ev_float, "ammo_shells1"},
-       {ev_float, "ammo_nails1"},
-       {ev_float, "ammo_lava_nails"},
-       {ev_float, "ammo_rockets1"},
-       {ev_float, "ammo_multi_rockets"},
-       {ev_float, "ammo_cells1"},
-       {ev_float, "ammo_plasma"},
+       {ev_float, "gravity"},
        {ev_float, "idealpitch"},
-       {ev_float, "pitch_speed"},
-       {ev_entity, "viewmodelforclient"},
-       {ev_entity, "nodrawtoclient"},
-       {ev_entity, "exteriormodeltoclient"},
-       {ev_entity, "drawonlytoclient"},
+       {ev_float, "items2"},
+       {ev_float, "light_lev"},
+       {ev_float, "pflags"},
        {ev_float, "ping"},
-       {ev_vector, "movement"},
+       {ev_float, "pitch_speed"},
        {ev_float, "pmodel"},
-       {ev_vector, "punchvector"}
+       {ev_float, "renderamt"}, // HalfLife support
+       {ev_float, "rendermode"}, // HalfLife support
+       {ev_float, "scale"},
+       {ev_float, "style"},
+       {ev_float, "tag_index"},
+       {ev_float, "viewzoom"},
+       {ev_vector, "color"},
+       {ev_vector, "colormod"},
+       {ev_vector, "cursor_screen"},
+       {ev_vector, "cursor_trace_endpos"},
+       {ev_vector, "cursor_trace_start"},
+       {ev_vector, "movement"},
+       {ev_vector, "punchvector"},
+       {ev_string, "playermodel"},
+       {ev_string, "playerskin"}
 };
 
 /*
@@ -1177,56 +1270,64 @@ dpfield_t dpfields[] =
 PR_LoadProgs
 ===============
 */
-void PR_LoadProgs (void)
+extern void PR_Cmd_Reset (void);
+void PR_LoadProgs (const char *progsname)
 {
        int i;
        dstatement_t *st;
        ddef_t *infielddefs;
-       void *temp;
-
-// flush the non-C variable lookup cache
-       for (i=0 ; i<GEFV_CACHESIZE ; i++)
-               gefvCache[i].field[0] = 0;
+       dfunction_t *dfunctions;
 
-       Mem_EmptyPool(progs_mempool);
-       Mem_EmptyPool(edictstring_mempool);
+       if (!progsname || !*progsname)
+               Host_Error("PR_LoadProgs: passed empty progsname");
 
-       temp = COM_LoadFile ("progs.dat", false);
-       if (!temp)
-               Host_Error ("PR_LoadProgs: couldn't load progs.dat");
+       PR_FreeAll();
 
-       progs = (dprograms_t *)Mem_Alloc(progs_mempool, com_filesize);
+       progs = (dprograms_t *)FS_LoadFile (progsname, serverprogs_mempool, false);
+       if (!progs)
+               Host_Error ("PR_LoadProgs: couldn't load %s", progsname);
 
-       memcpy(progs, temp, com_filesize);
-       Mem_Free(temp);
+       Con_DPrintf("Programs occupy %iK.\n", fs_filesize/1024);
 
-       Con_DPrintf ("Programs occupy %iK.\n", com_filesize/1024);
-
-       pr_crc = CRC_Block((byte *)progs, com_filesize);
+       pr_crc = CRC_Block((qbyte *)progs, fs_filesize);
 
 // byte swap the header
-       for (i=0 ; i<sizeof(*progs)/4 ; i++)
+       for (i = 0;i < (int) sizeof(*progs) / 4;i++)
                ((int *)progs)[i] = LittleLong ( ((int *)progs)[i] );
 
        if (progs->version != PROG_VERSION)
                Host_Error ("progs.dat has wrong version number (%i should be %i)", progs->version, PROG_VERSION);
-       if (progs->crc != PROGHEADER_CRC)
+       if (progs->crc != PROGHEADER_CRC && progs->crc != 32401) // tenebrae crc also allowed
                Host_Error ("progs.dat system vars have been modified, progdefs.h is out of date");
 
-       pr_functions = (dfunction_t *)((byte *)progs + progs->ofs_functions);
+       //prog->functions = (dfunction_t *)((qbyte *)progs + progs->ofs_functions);
+       dfunctions = (dfunction_t *)((qbyte *)progs + progs->ofs_functions);
+
        pr_strings = (char *)progs + progs->ofs_strings;
-       pr_globaldefs = (ddef_t *)((byte *)progs + progs->ofs_globaldefs);
+       pr_stringssize = 0;
+       for (i = 0;i < progs->numstrings;i++)
+       {
+               if (progs->ofs_strings + pr_stringssize >= fs_filesize)
+                       Host_Error ("progs.dat strings go past end of file\n");
+               pr_stringssize += strlen (pr_strings + pr_stringssize) + 1;
+       }
+       pr_numknownstrings = 0;
+       pr_maxknownstrings = 0;
+       pr_knownstrings = NULL;
+
+       pr_globaldefs = (ddef_t *)((qbyte *)progs + progs->ofs_globaldefs);
 
        // we need to expand the fielddefs list to include all the engine fields,
        // so allocate a new place for it
-       infielddefs = (ddef_t *)((byte *)progs + progs->ofs_fielddefs);
-       pr_fielddefs = Mem_Alloc(progs_mempool, (progs->numfielddefs + DPFIELDS) * sizeof(ddef_t));
+       infielddefs = (ddef_t *)((qbyte *)progs + progs->ofs_fielddefs);
+       pr_fielddefs = PR_Alloc((progs->numfielddefs + DPFIELDS) * sizeof(ddef_t));
+       prog->functions = PR_Alloc(sizeof(mfunction_t) * progs->numfunctions);
 
-       pr_statements = (dstatement_t *)((byte *)progs + progs->ofs_statements);
+       pr_statements = (dstatement_t *)((qbyte *)progs + progs->ofs_statements);
 
        // moved edict_size calculation down below field adding code
 
-       pr_global_struct = (globalvars_t *)((byte *)progs + progs->ofs_globals);
+       pr_global_struct = (globalvars_t *)((qbyte *)progs + progs->ofs_globals);
        pr_globals = (float *)pr_global_struct;
 
 // byte swap the lumps
@@ -1238,14 +1339,15 @@ void PR_LoadProgs (void)
                pr_statements[i].c = LittleShort(pr_statements[i].c);
        }
 
-       for (i=0 ; i<progs->numfunctions; i++)
+       for (i = 0;i < progs->numfunctions;i++)
        {
-               pr_functions[i].first_statement = LittleLong (pr_functions[i].first_statement);
-               pr_functions[i].parm_start = LittleLong (pr_functions[i].parm_start);
-               pr_functions[i].s_name = LittleLong (pr_functions[i].s_name);
-               pr_functions[i].s_file = LittleLong (pr_functions[i].s_file);
-               pr_functions[i].numparms = LittleLong (pr_functions[i].numparms);
-               pr_functions[i].locals = LittleLong (pr_functions[i].locals);
+               prog->functions[i].first_statement = LittleLong (dfunctions[i].first_statement);
+               prog->functions[i].parm_start = LittleLong (dfunctions[i].parm_start);
+               prog->functions[i].s_name = LittleLong (dfunctions[i].s_name);
+               prog->functions[i].s_file = LittleLong (dfunctions[i].s_file);
+               prog->functions[i].numparms = LittleLong (dfunctions[i].numparms);
+               prog->functions[i].locals = LittleLong (dfunctions[i].locals);
+               memcpy(prog->functions[i].parm_size, dfunctions[i].parm_size, sizeof(dfunctions[i].parm_size));
        }
 
        for (i=0 ; i<progs->numglobaldefs ; i++)
@@ -1266,11 +1368,11 @@ void PR_LoadProgs (void)
        }
 
        // append the darkplaces fields
-       for (i = 0;i < DPFIELDS;i++)
+       for (i = 0;i < (int) DPFIELDS;i++)
        {
                pr_fielddefs[progs->numfielddefs].type = dpfields[i].type;
                pr_fielddefs[progs->numfielddefs].ofs = progs->entityfields;
-               pr_fielddefs[progs->numfielddefs].s_name = dpfields[i].string - pr_strings;
+               pr_fielddefs[progs->numfielddefs].s_name = PRVM_SetEngineString(dpfields[i].string);
                if (pr_fielddefs[progs->numfielddefs].type == ev_vector)
                        progs->entityfields += 3;
                else
@@ -1282,9 +1384,9 @@ void PR_LoadProgs (void)
                ((int *)pr_globals)[i] = LittleLong (((int *)pr_globals)[i]);
 
        // moved edict_size calculation down here, below field adding code
-       pr_edict_size = progs->entityfields * 4 + sizeof (edict_t) - sizeof(entvars_t);
-
-       pr_edictareasize = pr_edict_size * MAX_EDICTS;
+       // LordHavoc: this no longer includes the prvm_edict_t header
+       prog->edict_size = progs->entityfields * 4;
+       pr_edictareasize = prog->edict_size * MAX_EDICTS;
 
        // LordHavoc: bounds check anything static
        for (i = 0,st = pr_statements;i < progs->numstatements;i++,st++)
@@ -1386,20 +1488,115 @@ void PR_LoadProgs (void)
        }
 
        FindEdictFieldOffsets(); // LordHavoc: update field offset list
+       PR_Execute_ProgsLoaded();
+       PR_Cmd_Reset();
 }
 
 
 void PR_Fields_f (void)
 {
-       int i;
+       int i, j, ednum, used, usedamount;
+       int *counts;
+       const char *name;
+       char tempstring[5000], tempstring2[260];
+       prvm_edict_t *ed;
+       ddef_t *d;
+       int *v;
        if (!sv.active)
        {
-               Con_Printf("no progs loaded\n");
+               Con_Print("no progs loaded\n");
                return;
        }
+       counts = Mem_Alloc(tempmempool, progs->numfielddefs * sizeof(int));
+       for (ednum = 0;ednum < prog->max_edicts;ednum++)
+       {
+               ed = PRVM_EDICT_NUM(ednum);
+               if (ed->priv.server->free)
+                       continue;
+               for (i = 1;i < progs->numfielddefs;i++)
+               {
+                       d = &pr_fielddefs[i];
+                       name = PRVM_GetString(d->s_name);
+                       if (name[strlen(name)-2] == '_')
+                               continue;       // skip _x, _y, _z vars
+                       v = (int *)((char *)ed->v + d->ofs*4);
+                       // if the value is still all 0, skip the field
+                       for (j = 0;j < type_size[d->type & ~DEF_SAVEGLOBAL];j++)
+                       {
+                               if (v[j])
+                               {
+                                       counts[i]++;
+                                       break;
+                               }
+                       }
+               }
+       }
+       used = 0;
+       usedamount = 0;
+       tempstring[0] = 0;
        for (i = 0;i < progs->numfielddefs;i++)
-               Con_Printf("%s\n", (pr_strings + pr_fielddefs[i].s_name));
-       Con_Printf("%i entity fields, totalling %i bytes per edict, %i edicts, %i bytes total spent on edict fields\n", progs->entityfields, progs->entityfields * 4, MAX_EDICTS, progs->entityfields * 4 * MAX_EDICTS);
+       {
+               d = &pr_fielddefs[i];
+               name = PRVM_GetString(d->s_name);
+               if (name[strlen(name)-2] == '_')
+                       continue;       // skip _x, _y, _z vars
+               switch(d->type & ~DEF_SAVEGLOBAL)
+               {
+               case ev_string:
+                       strlcat (tempstring, "string   ", sizeof (tempstring));
+                       break;
+               case ev_entity:
+                       strlcat (tempstring, "entity   ", sizeof (tempstring));
+                       break;
+               case ev_function:
+                       strlcat (tempstring, "function ", sizeof (tempstring));
+                       break;
+               case ev_field:
+                       strlcat (tempstring, "field    ", sizeof (tempstring));
+                       break;
+               case ev_void:
+                       strlcat (tempstring, "void     ", sizeof (tempstring));
+                       break;
+               case ev_float:
+                       strlcat (tempstring, "float    ", sizeof (tempstring));
+                       break;
+               case ev_vector:
+                       strlcat (tempstring, "vector   ", sizeof (tempstring));
+                       break;
+               case ev_pointer:
+                       strlcat (tempstring, "pointer  ", sizeof (tempstring));
+                       break;
+               default:
+                       dpsnprintf (tempstring2, sizeof (tempstring2), "bad type %i ", d->type & ~DEF_SAVEGLOBAL);
+                       strlcat (tempstring, tempstring2, sizeof (tempstring));
+                       break;
+               }
+               if (strlen(name) > 256)
+               {
+                       memcpy(tempstring2, name, 256);
+                       tempstring2[256] = tempstring2[257] = tempstring2[258] = '.';
+                       tempstring2[259] = 0;
+                       name = tempstring2;
+               }
+               strcat (tempstring, name);
+               for (j = strlen(name);j < 25;j++)
+                       strcat(tempstring, " ");
+               dpsnprintf (tempstring2, sizeof (tempstring2), "%5d", counts[i]);
+               strlcat (tempstring, tempstring2, sizeof (tempstring));
+               strlcat (tempstring, "\n", sizeof (tempstring));
+               if (strlen(tempstring) >= 4096)
+               {
+                       Con_Print(tempstring);
+                       tempstring[0] = 0;
+               }
+               if (counts[i])
+               {
+                       used++;
+                       usedamount += type_size[d->type & ~DEF_SAVEGLOBAL];
+               }
+       }
+       Mem_Free(counts);
+       Con_Printf("%i entity fields (%i in use), totalling %i bytes per edict (%i in use), %i edicts allocated, %i bytes total spent on edict fields (%i needed)\n", progs->entityfields, used, progs->entityfields * 4, usedamount * 4, prog->max_edicts, progs->entityfields * 4 * prog->max_edicts, usedamount * 4 * prog->max_edicts);
 }
 
 void PR_Globals_f (void)
@@ -1407,11 +1604,11 @@ void PR_Globals_f (void)
        int i;
        if (!sv.active)
        {
-               Con_Printf("no progs loaded\n");
+               Con_Print("no progs loaded\n");
                return;
        }
        for (i = 0;i < progs->numglobaldefs;i++)
-               Con_Printf("%s\n", (pr_strings + pr_globaldefs[i].s_name));
+               Con_Printf("%s\n", PRVM_GetString(pr_globaldefs[i].s_name));
        Con_Printf("%i global variables, totalling %i bytes\n", progs->numglobals, progs->numglobals * 4);
 }
 
@@ -1420,11 +1617,13 @@ void PR_Globals_f (void)
 PR_Init
 ===============
 */
+extern void PR_Cmd_Init(void);
 void PR_Init (void)
 {
        Cmd_AddCommand ("edict", ED_PrintEdict_f);
        Cmd_AddCommand ("edicts", ED_PrintEdicts);
        Cmd_AddCommand ("edictcount", ED_Count);
+       Cmd_AddCommand ("edictset", ED_EdictSet_f);
        Cmd_AddCommand ("profile", PR_Profile_f);
        Cmd_AddCommand ("pr_fields", PR_Fields_f);
        Cmd_AddCommand ("pr_globals", PR_Globals_f);
@@ -1459,43 +1658,192 @@ void PR_Init (void)
        Cvar_RegisterVariable (&cutscene); // for Nehahra but useful to other mods as well
        // LordHavoc: optional runtime bounds checking (speed drain, but worth it for security, on by default - breaks most QCCX features (used by CRMod and others))
        Cvar_RegisterVariable (&pr_boundscheck);
+       Cvar_RegisterVariable (&pr_traceqc);
+
+       serverprogs_mempool = Mem_AllocPool("server progs", 0, NULL);
+
+       PR_Cmd_Init();
+}
+
+/*
+===============
+PR_Shutdown
+===============
+*/
+extern void PR_Cmd_Shutdown(void);
+void PR_Shutdown (void)
+{
+       PR_Cmd_Shutdown();
 
-       progs_mempool = Mem_AllocPool("progs.dat");
-       edictstring_mempool = Mem_AllocPool("edict strings");
+       Mem_FreePool(&serverprogs_mempool);
 }
 
-// LordHavoc: turned EDICT_NUM into a #define for speed reasons
-edict_t *EDICT_NUM_ERROR(int n)
+void *_PR_Alloc(size_t buffersize, const char *filename, int fileline)
 {
-       Host_Error ("EDICT_NUM: bad number %i", n);
+       return _Mem_Alloc(serverprogs_mempool, buffersize, filename, fileline);
+}
+
+void _PR_Free(void *buffer, const char *filename, int fileline)
+{
+       _Mem_Free(buffer, filename, fileline);
+}
+
+void _PR_FreeAll(const char *filename, int fileline)
+{
+       progs = NULL;
+       pr_fielddefs = NULL;
+       prog->functions = NULL;
+       _Mem_EmptyPool(serverprogs_mempool, filename, fileline);
+}
+
+// LordHavoc: turned PRVM_EDICT_NUM into a #define for speed reasons
+prvm_edict_t *EDICT_NUM_ERROR(int n, char *filename, int fileline)
+{
+       Host_Error ("PRVM_EDICT_NUM: bad number %i (called at %s:%i)", n, filename, fileline);
        return NULL;
 }
+
 /*
-edict_t *EDICT_NUM(int n)
+int NUM_FOR_EDICT_ERROR(prvm_edict_t *e)
+{
+       Host_Error ("PRVM_NUM_FOR_EDICT: bad pointer %p (world is %p, entity number would be %i)", e, prog->edicts, e - prog->edicts);
+       return 0;
+}
+
+int PRVM_NUM_FOR_EDICT(prvm_edict_t *e)
+{
+       int n;
+       n = e - prog->edicts;
+       if ((unsigned int)n >= MAX_EDICTS)
+               Host_Error ("PRVM_NUM_FOR_EDICT: bad pointer");
+       return n;
+}
+
+//int NoCrash_NUM_FOR_EDICT(prvm_edict_t *e)
+//{
+//     return e - prog->edicts;
+//}
+
+//#define      PRVM_EDICT_TO_PROG(e) ((qbyte *)(((prvm_edict_t *)e)->v) - (qbyte *)(prog->edictsfields))
+//#define PRVM_PROG_TO_EDICT(e) (prog->edicts + ((e) / (progs->entityfields * 4)))
+int PRVM_EDICT_TO_PROG(prvm_edict_t *e)
 {
-       if (n < 0 || n >= sv.max_edicts)
-               Sys_Error ("EDICT_NUM: bad number %i", n);
-       return (edict_t *)((byte *)sv.edicts+ (n)*pr_edict_size);
+       int n;
+       n = e - prog->edicts;
+       if ((unsigned int)n >= (unsigned int)prog->max_edicts)
+               Host_Error("PRVM_EDICT_TO_PROG: invalid edict %8p (number %i compared to world at %8p)\n", e, n, prog->edicts);
+       return n;// EXPERIMENTAL
+       //return (qbyte *)e->v - (qbyte *)prog->edictsfields;
+}
+prvm_edict_t *PRVM_PROG_TO_EDICT(int n)
+{
+       if ((unsigned int)n >= (unsigned int)prog->max_edicts)
+               Host_Error("PRVM_PROG_TO_EDICT: invalid edict number %i\n", n);
+       return prog->edicts + n; // EXPERIMENTAL
+       //return prog->edicts + ((n) / (progs->entityfields * 4));
 }
 */
 
-int NUM_FOR_EDICT(edict_t *e)
+const char *PRVM_GetString(int num)
 {
-       int             b;
+       if (num >= 0 && num < pr_stringssize)
+               return pr_strings + num;
+       else if (num < 0 && num >= -pr_numknownstrings)
+       {
+               num = -1 - num;
+               if (!pr_knownstrings[num])
+                       Host_Error("PRVM_GetString: attempt to get string that is already freed\n");
+               return pr_knownstrings[num];
+       }
+       else
+       {
+               Host_Error("PRVM_GetString: invalid string offset %i\n", num);
+               return "";
+       }
+}
 
-       b = (byte *)e - (byte *)sv.edicts;
-       b = b / pr_edict_size;
+int PR_SetQCString(const char *s)
+{
+       int i;
+       if (!s)
+               return 0;
+       if (s >= pr_strings && s <= pr_strings + pr_stringssize)
+               return s - pr_strings;
+       for (i = 0;i < pr_numknownstrings;i++)
+               if (pr_knownstrings[i] == s)
+                       return -1 - i;
+       Host_Error("PR_SetQCString: unknown string\n");
+       return -1 - i;
+}
 
-       if (b < 0 || b >= sv.num_edicts)
-               Host_Error ("NUM_FOR_EDICT: bad pointer");
-       return b;
+int PRVM_SetEngineString(const char *s)
+{
+       int i;
+       if (!s)
+               return 0;
+       if (s >= pr_strings && s <= pr_strings + pr_stringssize)
+               Host_Error("PRVM_SetEngineString: s in pr_strings area\n");
+       for (i = 0;i < pr_numknownstrings;i++)
+               if (pr_knownstrings[i] == s)
+                       return -1 - i;
+       // new unknown engine string
+       if (developer.integer >= 3)
+               Con_Printf("new engine string %p\n", s);
+       for (i = 0;i < pr_numknownstrings;i++)
+               if (!pr_knownstrings[i])
+                       break;
+       if (i >= pr_numknownstrings)
+       {
+               if (i >= pr_maxknownstrings)
+               {
+                       const char **oldstrings = pr_knownstrings;
+                       pr_maxknownstrings += 128;
+                       pr_knownstrings = PR_Alloc(pr_maxknownstrings * sizeof(char *));
+                       if (pr_numknownstrings)
+                               memcpy((char **)pr_knownstrings, oldstrings, pr_numknownstrings * sizeof(char *));
+               }
+               pr_numknownstrings++;
+       }
+       pr_knownstrings[i] = s;
+       return -1 - i;
 }
 
-int NoCrash_NUM_FOR_EDICT(edict_t *e)
+char *PR_AllocString(int bufferlength)
 {
-       int             b;
+       int i;
+       if (!bufferlength)
+               return 0;
+       for (i = 0;i < pr_numknownstrings;i++)
+               if (!pr_knownstrings[i])
+                       break;
+       if (i >= pr_numknownstrings)
+       {
+               if (i >= pr_maxknownstrings)
+               {
+                       const char **oldstrings = pr_knownstrings;
+                       pr_maxknownstrings += 128;
+                       pr_knownstrings = PR_Alloc(pr_maxknownstrings * sizeof(char *));
+                       if (pr_numknownstrings)
+                               memcpy((char **)pr_knownstrings, oldstrings, pr_numknownstrings * sizeof(char *));
+               }
+               pr_numknownstrings++;
+       }
+       return (char *)(pr_knownstrings[i] = PR_Alloc(bufferlength));
+}
 
-       b = (byte *)e - (byte *)sv.edicts;
-       b = b / pr_edict_size;
-       return b;
+void PR_FreeString(char *s)
+{
+       int i;
+       if (!s)
+               Host_Error("PR_FreeString: attempt to free a NULL string\n");
+       if (s >= pr_strings && s <= pr_strings + pr_stringssize)
+               Host_Error("PR_FreeString: attempt to free a constant string\n");
+       for (i = 0;i < pr_numknownstrings;i++)
+               if (pr_knownstrings[i] == s)
+                       break;
+       if (i == pr_numknownstrings)
+               Host_Error("PR_FreeString: attempt to free a non-existent or already freed string\n");
+       PR_Free((char *)pr_knownstrings[i]);
+       pr_knownstrings[i] = NULL;
 }
+